Skip to content

A desktop coding agent with free access to frontier models.

TypeScript
392 KB
Raw Blame
import { randomBytes, timingSafeEqual } from "node:crypto";
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
import { ArchiveUploader } from "./session-archive/upload.js";
import { SealStream } from "./session-archive/seal.js";
import { tarMemberHeader } from "./session-archive/pack.js";
import { parseApprovalMode, resolveApprovalMode, type ApprovalMode } from "./approval-mode.js";
import { createTaskRecovery, requeueTaskRecoveryAfterEngineLoss, setTaskRecovery } from "./task-recovery.js";
import {
  directoryMatchKey,
  EmptySessionDirectoryCache,
  isSessionListRequest,
  listSessionsByDirectory,
  serveSessionListWithFallback,
  sessionListFallbackDeadlineMs,
  sessionListFallbackQuery,
} from "./session-list-fallback.js";
import { managedPolicyActionSchema } from "./managed-policy-rules.js";
import { readFile, realpath, writeFile, rm, stat } from "node:fs/promises";
import { homedir, hostname } from "node:os";
import { dirname, join, relative, resolve, sep } from "node:path";
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
import { resolveGlobalOpencodeConfigPath } from "@omnirush/paths";
import type { ApprovalRequest, Capabilities, ServerConfig, WorkspaceInfo, Actor, ReloadReason, ReloadTrigger, TokenScope } from "./types.js";
import { agentContextDiagnosticsRequestSchema } from "./agent-context-diagnostics-schema.js";
import { ApprovalService } from "./approvals.js";
import {
  BoundedSseFrameBuffer,
  EnginePool,
  enginePoolForConfig,
  isEngineConnectionFailure,
  setEnginePoolForConfig,
  type EnginePoolConnection,
  type EngineEventProxyLease,
  type EngineSpawnTemplate,
  type RolloverReason,
} from "./engine-pool.js";
import { withEngineDirectoryFence } from "./engine-directory-fence.js";
import { decodeEngineRouteParam, decodeEngineRoutePath } from "./engine-route-path.js";
import { repairEngineStoresAfterServerError } from "./engine-store-repair.js";
import {
  clearEngineInstanceReaperForConfig,
  EngineInstanceReaper,
  engineInstanceReaperForConfig,
  setEngineInstanceReaperForConfig,
  type TrackedEngineInstance,
} from "./engine-instance-reaper.js";
import { shouldDeferInPlaceEngineReload } from "./engine-reload-defer.js";
import { LatestTrailingWorkQueue } from "./latest-trailing-work-queue.js";
import { buildEngineAuthProbeHeader } from "./engine-registry.js";
import { addPlugin, listPlugins, normalizePluginSpec, removePlugin } from "./plugins.js";
import { sanitizePortableOpencodeConfig } from "./portable-opencode.js";
import { addMcp, listMcp, removeMcp, setMcpEnabled } from "./mcp.js";
import { buildOmniRushV2Instructions, waitForOmniRushV2Skills, OMNIRUSH_V2_INSTRUCTION_KEY } from "./opencode-v2-instructions.js";
import {
  callMcpAppTool,
  listMcpAppCatalog,
  McpAppHostError,
  resolveConnectMcpAppResource,
  resolveMcpAppResource,
  resolveSameServerMcpAppResource,
} from "./mcp-app-host.js";
import { CONNECT_MCP_SERVER_NAME_PREFIX } from "./connect-mcp-server-catalog.js";
import {
  buildMcpAppSandboxCsp,
  MCP_APP_SANDBOX_PROXY_CSS,
  MCP_APP_SANDBOX_PROXY_HTML,
  MCP_APP_SANDBOX_PROXY_SCRIPT,
  parseMcpAppSandboxCsp,
} from "./mcp-app-sandbox.js";
import { deleteSkill, listSkills, renderSkillContentForResponse, upsertSkill } from "./skills.js";
import {
  findSkillConflict,
  installSkillBundle,
  listSkillTree,
  prepareSkillBundle,
  readBoundedJsonBody,
  resolveProjectSkillDir,
  SKILL_BUNDLE_MAX_REQUEST_BYTES,
  summarizeSkillBundle,
  updateSkillFiles,
} from "./skill-bundle.js";
import { deleteCommand, listCommands, repairCommands, upsertCommand } from "./commands.js";
import { ApiError, formatError } from "./errors.js";
import { errorCode } from "./atomic-write.js";
import { readJsoncFile, updateJsoncTopLevel, writeJsoncFile } from "./jsonc.js";
import { recordAudit, readAuditEntries, readLastAudit } from "./audit.js";
import { ReloadEventStore } from "./events.js";
import { computeReloadFingerprint } from "./reload-fingerprint.js";
import { startReloadWatchers } from "./reload-watcher.js";
import {
  redactLogAttributes,
  redactServerLogFileRecord,
  resolveServerLogFileSink,
  type ServerLogFileSink,
} from "./server-log-file.js";
import { opencodeConfigPath, omnirushConfigPath, projectCommandsDir, projectSkillsDir } from "./workspace-files.js";
import { ensureDir, exists, hashToken, shortId } from "./utils.js";
import { defaultWorkspaceOmniRushConfig, ensureWorkspaceFiles, readRawOpencodeConfig } from "./workspace-init.js";
import { sanitizeCommandName, validateMcpName, validateUserMcpName } from "./validators.js";
import { TokenService } from "./tokens.js";
import { resetManagedProviderAuthCache, syncManagedProviderAuth } from "./managed-provider-auth.js";
import { EnvService } from "./env-file.js";
import {
  normalizeResourceSnapshot,
  readDesktopCloudSyncState,
  readWorkspaceCloudImports,
  syncDesktopCloudResources,
} from "./desktop-cloud-sync.js";
import { installCloudPlugin, readCloudPluginResolved, readInstalledCloudPlugins, removeCloudPlugin } from "./cloud-plugins.js";
import { resolveClaudePluginBundle } from "./claude-plugin-bundle.js";
import { resolveWorkspaceOpencodeConnection } from "./opencode-connection.js";
import { parseOpencodeConfigErrorBody } from "./opencode-config-compat.js";
import { listPortableFiles } from "./portable-files.js";
import {
  collectWorkspaceExportWarnings,
  sanitizeOmniRushTemplateConfig,
  stripSensitiveWorkspaceExportData,
  type WorkspaceExportSensitiveMode,
} from "./workspace-export-safety.js";
import { serve, type ServeResult } from "./serve-node.js";
import { serveStaticUi } from "./static-ui.js";
import { externalFetch, loopbackFetch } from "./server-fetch.js";
import { registerCoreRoutes } from "./routes/core.js";
import { registerFileRoutes } from "./routes/files.js";
import { registerEditorRoutes } from "./routes/editor.js";
import { registerEditorFormatRoutes } from "./routes/editor-format.js";
import { registerEditorSearchRoutes } from "./routes/editor-search.js";
import { registerOperationRoutes } from "./routes/operations.js";
import { addRoute, matchRoute, type AuthMode, type RequestContext, type Route } from "./routes/registry.js";
import { registerSessionGroupRoutes } from "./routes/session-groups.js";
import { registerUiControlRoutes } from "./routes/ui-control.js";
import { addLocalWorkspace, registerWorkspaceRoutes } from "./routes/workspaces.js";
import { noteTaskPrompt, registerWorkspaceTaskRoutes, type TaskEngine } from "./routes/workspace-tasks.js";
import { registerCloudMcpRoutes } from "./routes/cloud-mcp.js";
import { registerLocalWorkflowRoutes } from "./routes/local-workflows.js";
import type { LocalWorkflowPromptDispatcher, LocalWorkflowService } from "./local-workflows.js";
import { UiControlMailbox } from "./ui-control.js";
import { captureServerException, isExpectedRequestCancellation } from "./telemetry.js";
import {
  completeLocalManagedMcpAuthorization,
  createLocalManagedMcpConnection,
  deleteLocalManagedMcp,
  disconnectLocalManagedMcp,
  getLocalManagedMcpConnection,
  handleLocalManagedMcpGateway,
  listLocalManagedMcpConnectionsSafe,
  reconcileLocalManagedMcpRuntimeEntries,
  setLocalManagedMcpEnabled,
  startLocalManagedMcpAuthorization,
} from "./local-managed-mcp.js";
import {
  markOmniRushCloudMcpStale,
  migrateOmniRushCloudMcpRuntimeConfig,
  OMNIRUSH_CLOUD_MCP_NAME,
  removeOmniRushCloudMcpDesiredConfig,
  type CloudMcpHealth,
} from "./cloud-mcp-health.js";
import { runAgentContextDiagnostics } from "./agent-context-diagnostics.js";
import { createAgentDiagnosticsEngineFetch, validateEffectiveEngineSnapshot } from "./agent-context-engine-inspection.js";
import { selectGoverningAgent, summarizeEffectivePermissions } from "./effective-permissions.js";
import { readWorkspaceRunMode, setWorkspaceRunMode, type WorkspaceRunModeState } from "./workspace-run-mode.js";
import { sanitizeDiagnosticString } from "./diagnostic-sanitizer.js";
import {
  mergeOpencodeConfigs,
  mergeRuntimeProviderUpdate,
  migrateWorkspaceRuntimeConfigToEngineGlobal,
  readEffectiveRuntimeOpencodeConfig,
  readGlobalRuntimeOpencodeConfig,
  readRuntimeOpencodeConfig,
  runtimeDisabledProviderList,
  runtimeMcpMap,
  runtimeProviderMap,
  type RuntimeOpencodeConfig,
  withoutMcpRuntimeConfig,
  writeGlobalRuntimeOpencodeConfig,
  writeRuntimeOpencodeConfig,
} from "./runtime-opencode-config-store.js";
import {
  hasOmniRushWorkspaceConfig,
  mergeOmniRushWorkspaceConfigs,
  readOmniRushWorkspaceConfig,
  seedOmniRushWorkspaceConfigIfEmpty,
  writeOmniRushWorkspaceConfig,
} from "./omnirush-workspace-config-store.js";
import { boxServiceFor } from "./box/desktop.js";
import { BOX_SETUP_ACTIONS, BoxRequiredError, isBoxSetupAction } from "./box/service.js";
import { boxHome } from "./box/common.js";
import { buildathonProjectsFile, reproStateFromBody, writeReproState } from "./buildathon-repro.js";
import { prepareBoxInstallLog } from "./box/install-log.js";
import { rememberServerDefault, watchServerDefault } from "./box/launch.js";
import { rememberWebSearchSwitch, userWebSearchEnabled, webSearchAllowed, watchWebSearchSwitch, webSearchSetting, writeUserWebSearch } from "./web-search.js";
import { askSideQuestion, brokerSideCall } from "./side-question.js";
import { createChatTracker, rememberComputerUseSwitch } from "./computer-use/desktop.js";
import { registerComputerUseRoutes } from "./computer-use/routes.js";
import { findWorkWorkspace, forwardWorkMcp, registerWorkRoutes, type WorkBroker } from "./work/routes.js";
import { rememberWorkSwitch, workDir } from "./work/work.js";
import { isV2WorkRoot, withV2WorkPermissions } from "./work/engine.js";
import { WORK_PROMPT } from "./work/prompt.js";
import {
  applyProviderLockAnswer,
  assertConfigWithinLock,
  assertPluginsUnlocked,
  assertProviderWritable,
  assertEngineStartedWithinLock,
  assertProxiedEngineRequestWithinProviderLock,
  currentProviderLockPolicy,
  engineStartedUnlocked,
  parseJsoncContent,
  providerLockStatus,
  watchProviderLock,
} from "./provider-lock.js";
import { normalizeBackend } from "./box/backends/index.js";
import { buildOmniRushRuntimeConfigObject, claudeEngineProvider, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";
import { assertMcpAllowed, mcpAllowed, mcpDisabledMessage, mcpPolicyForConfig, refuseAccountLinkedMcp } from "./mcp-policy.js";
import { currentMcpPolicy, MCP_FILTER_MISSING, mcpFilterMissing, rememberMcpPolicy, watchMcpPolicy, workspaceMcpReport, writeWorkspaceMcp } from "./mcp-allow/state.js";
import { omnirushMcpPolicyPluginPath } from "./omnirush-extensions-plugin-path.js";
import { isOmniRushUiMcpRegistryEntry } from "./omnirush-ui-mcp-command.js";
import { describeIgnored, type McpAllowEntry } from "./mcp-allow/mcp-allow.mjs";
import { omnirushModelWantsReasoningSummary, readOmniRushModelCatalog } from "./omnirush-model-catalog.js";
import { modelAllowedIn, modelModes, projectMode, serverModelStart } from "./model-modes/model-modes.mjs";
import { switchableModels } from "./model-modes/strict-sessions.mjs";
import { OMNIRUSH_PROVIDER_ID } from "./provider-lock/provider-lock.mjs";
import { serverLocalBox } from "./box/launch.js";
import {
  SUBAGENT_MODEL_FALLBACK_TRACE,
  readSubagentModelSetting,
  resolveSubagentModel,
  sanitizeSubagentModelSetting,
  subagentModelRefusals,
  subagentSettingFor,
  pinnedSubagentSetting,
  writeSubagentModelSetting,
  type EngineModelRef,
  type SubagentModelSetting,
} from "./omnirush-subagent-model.js";
import { modelsNamedIn } from "./omnirush-swarm.js";
import { findManagedEngineWorkspace } from "./workspaces.js";
import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";
import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";
import { createEngineV2Preview, resolveInitialEngineV2PreviewState, type EngineV2Preview } from "./engine-v2-preview.js";
import { MIGRATED_FROM } from "./engine-v2-migration.js";
import { createV2BudgetWrap } from "./engine-v2-budget-wrap.js";
import { convertOfficeAttachments } from "./engine-v2-attachments.js";
import { readArchivedChats, setArchived, withArchived } from "./archived-chats.js";
import { createEditorLsp, LSP_OPS, type LspOp, type LspPayload } from "./editor-lsp.js";
import { APP_SECRET_HEADER, appRequestRefusal } from "./app-request-gate.js";
import { isUploadFileDenied, sessionUploaderEnabled } from "./session-uploader.js";
import { editorUserEditEvent, editorUserReviewEvent } from "./editor-events.js";
import { startCaptureService, type CaptureService } from "./capture-client.js";
import type { LateWritesGate } from "./capture-host.js";
import { buildOpencodeProxyUrl, engineTarget, turnsBeforeCapture, type EngineTarget } from "./session-upload-observer.js";
import { claimSteerId, claimedSteerIds, createSteerTracker, steerRecord } from "./turn-steer.js";
import { FOLDER_NOT_WRITABLE, folderWriteGate, readOnlyPrompt } from "./folder-write-check.js";
import { commandEvent, revertEvent, revertRequest } from "./command-events.js";
import { EditorSaveLog, revertBodyWithEditorSaves } from "./editor-saves.js";
import { AutoCompactor, type AutoCompactOutcome } from "./session-archive/auto-compact.js";
import { brokerAutoCompactPolicy, desktopAutoCompactEngine } from "./auto-compact-engine.js";
import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
import { awaitOmniRushModelCatalogSettled, startOmniRushModelCatalogSync } from "./omnirush-model-catalog-sync.js";
import { OmniRushVoiceService, voiceProjectContext } from "./omnirush-voice.js";
import { GOOD_SESSION_ID_PATTERN, readGoodSession } from "./omnirush-good-session.js";
import { PROJECT_ARCHIVE_BASE_IDLE_MS, PROJECT_ARCHIVE_BASE_MAX_DEFER_MS, projectArchiveSettings } from "./project-archive.js";
import type { ArchiveApiRequestInit } from "./session-archive/upload.js";
import { runtimeStorageDir } from "./runtime-db.js";
import { CLAUDE_AUTO_NOTE, CLAUDE_CODE_VERSION, CLAUDE_PROVIDER_ID, chatPinRules, claudeChatRoute, type ClaudeChatInput } from "./claude-code/chat.js";
import { claudeConfigDirOf, uploadClaudeTurn } from "./claude-code/native.js";
import { prepareDesktopInstallLog } from "./install-log-host.js";
import pkg from "../package.json" with { type: "json" };
import constants from "../../../constants.json" with { type: "json" };
import { BestPracticesEngineReloads } from "./best-practices.js";
import { AGENT_ASSIST_FEATURES, agentAssistFlags, agentAssistForced } from "./agent-assist-config.js";
import { BUNDLED_ENGINE_VERSION } from "./engine-identity.js";
import { createTurnActivity, type TurnActivity } from "./turn-activity.js";

export {
  isSupportedWorkspaceTextFilePath,
  normalizeWorkspaceRelativePath,
  resolveWorkspaceArtifactTargets,
} from "./routes/files.js";
import { stockMode } from "./stock-mode/stock-mode.mjs";

const SERVER_VERSION = pkg.version;
const OPENCODE_VERSION = constants.opencodeVersion.trim().replace(/^v/, "");
const localWorkflowServices = new WeakMap<ServerConfig, LocalWorkflowService>();

let desktopCloudSyncQueue: Promise<void> = Promise.resolve();
const agentDiagnosticsLastRunByServer = new WeakMap<ServerConfig, Map<string, number>>();
const agentDiagnosticsInFlightByServer = new WeakMap<ServerConfig, Set<string>>();
const commandAdmissionsByServer = new WeakMap<ServerConfig, Map<string, { fingerprint: string; admittedAt: number }>>();
const captureServicesByServer = new WeakMap<ServerConfig, CaptureService>();
// /btw (side-question.ts): the model call through this server's gateway broker, when signed in.
const sideCallsByServer = new WeakMap<ServerConfig, ReturnType<typeof brokerSideCall>>();
/** The files the person saved through the desktop editor: an undo of the turns they were saved in keeps them (editor-saves.ts). */
const editorSavesByServer = new WeakMap<ServerConfig, EditorSaveLog>();
function editorSavesFor(config: ServerConfig): EditorSaveLog {
  let log = editorSavesByServer.get(config);
  if (!log) {
    log = new EditorSaveLog();
    editorSavesByServer.set(config, log);
  }
  return log;
}

/** The approval mode a captured session's setup record names (null when it cannot be read). */
async function capturePermissionMode(config: ServerConfig): Promise<ApprovalMode | null> {
  try {
    return resolveApprovalMode(await readGlobalRuntimeOpencodeConfig(config)).mode;
  } catch {
    return null;
  }
}

/** Automatic compaction (session-archive/auto-compact.ts), one per server: its counts live as long as the app. */
const autoCompactorsByServer = new WeakMap<ServerConfig, AutoCompactor>();
/** How long a request waits for the 2.x engine while it starts (its boot timeout, managed-opencode-v2.ts). */
const ENGINE_V2_START_WAIT_MS = 60_000;
const BY_FOLDER_ENGINE_WAIT_MS = 30_000;
const engineV2ByServer = new WeakMap<ServerConfig, EngineV2Preview>();
const editorLspByServer = new WeakMap<ServerConfig, ReturnType<typeof createEditorLsp>>();
function editorLspFor(config: ServerConfig): ReturnType<typeof createEditorLsp> {
  let host = editorLspByServer.get(config);
  if (!host) {
    host = createEditorLsp({ toolsDir: join(runtimeStorageDir(config), "language-servers") });
    editorLspByServer.set(config, host);
  }
  return host;
}
/**
 * How long a prompt waits for its chat's automatic compaction: the window
 * aborts a prompt request after 30 s, and the prompt's own capture steps
 * may take up to about 13 s more. Past it the prompt goes out and the
 * engine runs it right after the compaction.
 */
const AUTO_COMPACT_HOLD_MS = 10_000;
const AUTO_COMPACT_SEED_WAIT_MS = 5_000;
/** How long a sign-out waits for queued uploads to go (POST /omnirush/capture/flush); the rest stays queued for the account. */
const SIGN_OUT_FLUSH_MS = 10_000;
const turnActivityByServer = new WeakMap<ServerConfig, TurnActivity>();
/** Fresh capabilities for computer use (Electron main asks every 60 s while a session is open), per server. */
const computerUseCapabilitiesByServer = new WeakMap<ServerConfig, (maxAgeMs: number) => Promise<unknown>>();
/** Work mode's hop to /omnirush/work/* (work/routes.ts), per server; absent without an omnirush.ai account. */
const workBrokersByServer = new WeakMap<ServerConfig, WorkBroker>();
/** The chats prompted most recently, per server: a computer use call belongs to the latest one still running. */
const computerUseChatsByServer = new WeakMap<ServerConfig, ReturnType<typeof createChatTracker>>();
function computerUseChats(config: ServerConfig): ReturnType<typeof createChatTracker> {
  let chats = computerUseChatsByServer.get(config);
  if (!chats) {
    chats = createChatTracker();
    computerUseChatsByServer.set(config, chats);
  }
  return chats;
}

/** Restarts the engine's projects (when idle) so they pick up the built-in computer use server. */
async function applyComputerUseEngine(config: ServerConfig, reason: RolloverReason = "computer_use"): Promise<void> {
  const pool = enginePoolForConfig(config);
  const workspaces = config.workspaces.filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim());
  const workspace = findManagedEngineWorkspace(workspaces) ?? workspaces[0];
  if (pool && workspace) await pool.requestRollover({ reason, workspace, manual: true });
}

/** Whether the agent works on this server's engine (turn-activity.ts), for an embedding app that asked (onTurnActivity). */
function turnActivityFor(config: ServerConfig): TurnActivity | null {
  const onChange = config.onTurnActivity;
  if (!onChange) return null;
  let activity = turnActivityByServer.get(config);
  if (!activity) {
    activity = createTurnActivity({ busy: () => collectBusyEngineSessions(config), onChange });
    turnActivityByServer.set(config, activity);
  }
  return activity;
}

/** The server stops: no turn runs on it any more. */
export function stopTurnActivity(config: ServerConfig): void {
  turnActivityByServer.get(config)?.stop();
  turnActivityByServer.delete(config);
}
/** Voice dictation's broker hop (omnirush-voice.ts), per server. */
const voiceServicesByServer = new WeakMap<ServerConfig, OmniRushVoiceService>();
/** The broker's integrity read (rate-limited there), per server, for the checklist bar's "Good session ★". */
const sessionIntegrityByServer = new WeakMap<ServerConfig, OmniRushGatewayBroker["sessionIntegrity"]>();
const modelSwitchRefusalsByServer = new WeakMap<ServerConfig, OmniRushGatewayBroker["modelSwitchRefusal"]>();
/** The model a chat is pinned to at the gateway (null before its first model request). */
const chatPinsByServer = new WeakMap<ServerConfig, (sessionId: string) => string | null>();
/** Each server's Claude turn route (claude-code/chat.ts) and the key its engine's Claude provider sends. */
const claudeTurnsByServer = new WeakMap<ServerConfig, { key: string; handle: ReturnType<typeof claudeChatRoute> }>();

/** Recent gateway fallbacks per sub-agent session, for the swarm plugin's task-result note. */
const subagentGatewayFallbacks = new WeakMap<ServerConfig, Map<string, Array<Record<string, unknown>>>>();

/**
 * Records a sub-agent model fallback: a "subagent.model_fallback" trace event
 * on the main session the session uploader tracks (a gateway fallback also makes the
 * session uploader record the model those sub-agent messages really ran on), and,
 * for a gateway fallback, the per-session note the swarm plugin reads back.
 */
function recordSubagentModelFallback(config: ServerConfig, rootSessionId: string | null, data: Record<string, unknown>): void {
  const child = typeof data.child_session_id === "string" ? data.child_session_id : null;
  if (data.kind === "gateway" && child) {
    let byChild = subagentGatewayFallbacks.get(config);
    if (!byChild) {
      byChild = new Map();
      subagentGatewayFallbacks.set(config, byChild);
    }
    const list = byChild.get(child) ?? [];
    list.push(data);
    byChild.delete(child);
    byChild.set(child, list.slice(-16));
    while (byChild.size > 512) byChild.delete(byChild.keys().next().value as string);
  }
  const capture = captureServicesByServer.get(config);
  if (!rootSessionId || !capture?.uploadEnabled || !capture.hasSession(rootSessionId)) return;
  capture.recordTrace(rootSessionId, SUBAGENT_MODEL_FALLBACK_TRACE, data);
}

/** A trace event on a session the uploader has open (and nothing otherwise). */
function recordOpenSessionTrace(config: ServerConfig, sessionId: string, type: string, data: Record<string, unknown>): void {
  const capture = captureServicesByServer.get(config);
  if (!capture?.uploadEnabled || !capture.hasSession(sessionId)) return;
  capture.recordTrace(sessionId, type, data);
}

/** The engine reads of the parallel-task board (routes/workspace-tasks.ts), on the engine generation holding each session. */
function workspaceTaskEngine(config: ServerConfig): TaskEngine {
  return {
    sessionBusy: async (workspace, sessionId) => {
      const statuses = unwrapOpencodeResult(await createWorkspaceOpencodeClient(config, workspace, { sessionId }).session.status(), "/session/status");
      const status = (statuses as Record<string, { type?: string } | undefined>)[sessionId];
      return Boolean(status && status.type !== "idle");
    },
    abort: async (workspace, sessionId) => {
      await createWorkspaceOpencodeClient(config, workspace, { sessionId }).session.abort({ sessionID: sessionId });
    },
    lastReply: async (workspace, sessionId) => {
      const messages = unwrapOpencodeResult(await createWorkspaceOpencodeClient(config, workspace, { sessionId }).session.messages({ sessionID: sessionId, limit: 40 }), "/session/messages");
      const last = [...messages].reverse().find((message) => message.info.role === "assistant" && message.parts.some((part) => part.type === "text" && part.text.trim()));
      return last ? last.parts.flatMap((part) => part.type === "text" && !part.synthetic ? [part.text.trim()] : []).filter(Boolean).join("\n\n") : "";
    },
  };
}

function engineModelRef(value: unknown): (EngineModelRef & { variant: string | null }) | null {
  if (!isRecord(value)) return null;
  const providerID = typeof value.providerID === "string" ? value.providerID.trim() : "";
  const modelID = typeof value.modelID === "string" ? value.modelID.trim() : "";
  if (!providerID || !modelID || providerID.length > 128 || modelID.length > 256) return null;
  const variant = typeof value.variant === "string" && value.variant.trim() ? value.variant.trim().slice(0, 32) : null;
  return { providerID, modelID, variant };
}
const AGENT_DIAGNOSTICS_RATE_LIMIT_CAPACITY = 1_000;
const AGENT_DIAGNOSTICS_MAX_IN_FLIGHT_PER_SERVER = 16;
const AGENT_DIAGNOSTICS_MAX_REQUEST_BYTES = 256 * 1024;
const AGENT_DIAGNOSTICS_DEFAULT_BODY_DEADLINE_MS = 2_000;
const AGENT_DIAGNOSTICS_ERROR_FLUSH_MS = 25;
const COMMAND_ADMISSION_CAPACITY = 10_000;
const UPLOAD_EVENTS_MAX_REQUEST_BYTES = 1024 * 1024;
/** Where engine plugins report browser visits (opencode-plugins/omnirush-session-upload-client.ts). */
const SESSION_UPLOAD_EVENTS_ROUTE = "/session-upload/events";
/** The same route under its pre-2.2.2 name. */
const LEGACY_SESSION_UPLOAD_EVENTS_ROUTE = "/collector/events";
const COMMAND_ADMISSION_TTL_MS = 24 * 60 * 60 * 1_000;

function rethrowMcpAppHostError(error: unknown): never {
  if (!(error instanceof McpAppHostError)) throw error;
  const status = error.code === "invalid_tool_name" || error.code.startsWith("invalid_resource")
    ? 400
    : error.code === "tool_not_found" || error.code === "server_unavailable"
      ? 404
      : error.code === "mcp_unreachable"
        ? 502
        : 422;
  throw new ApiError(status, error.code, error.message);
}

function agentDiagnosticsActorWorkspaceKey(actor: Actor | undefined, workspaceId: string): string {
  const actorKey = actor?.tokenHash ?? actor?.clientId ?? actor?.type ?? "unknown";
  return hashToken(actorKey + "\0" + workspaceId);
}

function requireAgentDiagnosticsRateLimit(config: ServerConfig, actor: Actor | undefined, workspaceId: string): void {
  const now = Date.now();
  const configured = Number(process.env.OMNIRUSH_AGENT_DIAGNOSTICS_COOLDOWN_MS ?? "3000");
  const cooldownMs = Number.isFinite(configured) && configured >= 0 ? configured : 3_000;
  const key = agentDiagnosticsActorWorkspaceKey(actor, workspaceId);
  const agentDiagnosticsLastRun = agentDiagnosticsLastRunByServer.get(config) ?? new Map<string, number>();
  agentDiagnosticsLastRunByServer.set(config, agentDiagnosticsLastRun);
  const previous = agentDiagnosticsLastRun.get(key);
  if (previous !== undefined && now - previous < cooldownMs) {
    throw new ApiError(429, "agent_diagnostics_rate_limited", "Agent diagnostics were run too recently");
  }
  for (const [candidate, at] of agentDiagnosticsLastRun) {
    if (now - at > Math.max(cooldownMs, 60_000)) agentDiagnosticsLastRun.delete(candidate);
  }
  if (agentDiagnosticsLastRun.size >= AGENT_DIAGNOSTICS_RATE_LIMIT_CAPACITY) {
    const oldest = agentDiagnosticsLastRun.keys().next().value;
    if (oldest) agentDiagnosticsLastRun.delete(oldest);
  }
  agentDiagnosticsLastRun.set(key, now);
}

function reserveAgentDiagnosticsRun(
  config: ServerConfig,
  actor: Actor | undefined,
  workspaceId: string,
): () => void {
  const key = agentDiagnosticsActorWorkspaceKey(actor, workspaceId);
  const inFlight = agentDiagnosticsInFlightByServer.get(config) ?? new Set<string>();
  agentDiagnosticsInFlightByServer.set(config, inFlight);
  // Preserve the existing cooldown response for ordinary repeated attempts.
  // A zero/expired cooldown still cannot bypass the in-flight reservation.
  requireAgentDiagnosticsRateLimit(config, actor, workspaceId);
  if (inFlight.has(key)) {
    throw new ApiError(429, "agent_diagnostics_in_progress", "Agent diagnostics are already in progress");
  }
  if (inFlight.size >= AGENT_DIAGNOSTICS_MAX_IN_FLIGHT_PER_SERVER) {
    throw new ApiError(429, "agent_diagnostics_busy", "Agent diagnostics are temporarily busy");
  }

  // The cooldown charge and reservation are synchronous, so no second request
  // for this actor/workspace can slip in between them.
  inFlight.add(key);
  let released = false;
  return () => {
    if (released) return;
    released = true;
    inFlight.delete(key);
  };
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function runtimeConfigKeys(config: RuntimeOpencodeConfig): string[] {
  const keys: string[] = [];
  if (config.default_agent) keys.push("default_agent");
  if (Array.isArray(config.plugin) && config.plugin.length) keys.push("plugin");
  if (Array.isArray(config.disabled_providers) && config.disabled_providers.length) keys.push("disabled_providers");
  if (isRecord(config.mcp) && Object.keys(config.mcp).length) keys.push("mcp");
  const permission = isRecord(config.permission) ? config.permission : null;
  if (permission && isRecord(permission.external_directory) && Object.keys(permission.external_directory).length) {
    keys.push("permission");
  }
  if (isRecord(config.provider) && Object.keys(config.provider).length) keys.push("provider");
  return keys;
}

function parseDisabledProvidersPayload(value: unknown): string[] {
  if (!Array.isArray(value)) {
    throw new ApiError(400, "invalid_payload", "providers must be an array of non-empty strings");
  }
  const providers: string[] = [];
  for (const entry of value) {
    if (typeof entry !== "string" || !entry.trim()) {
      throw new ApiError(400, "invalid_payload", "providers must be an array of non-empty strings");
    }
    const provider = entry.trim();
    if (!providers.includes(provider)) providers.push(provider);
  }
  return providers;
}

function parseRuntimeProviderPatchPayload(body: Record<string, unknown>): Record<string, unknown> {
  const provider = body.provider;
  if (!isRecord(provider)) {
    throw new ApiError(400, "invalid_payload", "provider must be an object");
  }
  for (const [providerId, value] of Object.entries(provider)) {
    if (!providerId.trim()) {
      throw new ApiError(400, "invalid_payload", "provider keys must be non-empty strings");
    }
    if (value !== null && !isRecord(value)) {
      throw new ApiError(400, "invalid_payload", "provider values must be objects or null");
    }
  }
  return provider;
}

function resolveEngineRuntimeWorkspace(config: ServerConfig): WorkspaceInfo {
  const workspace = findManagedEngineWorkspace(config.workspaces) ?? config.workspaces[0];
  if (!workspace) {
    throw new ApiError(400, "workspace_missing", "At least one workspace is required for engine runtime config");
  }
  return workspace;
}

function redactBearerTokens(value: string): string {
  return value.replace(/Bearer\s+\S+/g, "Bearer [redacted]");
}

function redactManagedRuntimeValue(value: unknown, path: string[], insideMcpHeaders: boolean): unknown {
  if (typeof value === "string") return insideMcpHeaders ? "[redacted]" : redactBearerTokens(value);
  if (Array.isArray(value)) {
    return value.map((entry, index) => redactManagedRuntimeValue(entry, [...path, String(index)], insideMcpHeaders));
  }
  if (!isRecord(value)) return value;

  return Object.fromEntries(
    Object.entries(value).map(([key, child]) => {
      const childInsideMcpHeaders = insideMcpHeaders || (path.length === 2 && path[0] === "mcp" && key === "headers");
      return [key, redactManagedRuntimeValue(child, [...path, key], childInsideMcpHeaders)];
    }),
  );
}

function redactManagedRuntimeConfigContent(content: string): string {
  try {
    const parsed: unknown = JSON.parse(content);
    return JSON.stringify(redactManagedRuntimeValue(parsed, [], false), null, 2);
  } catch {
    return redactBearerTokens(content);
  }
}

async function readManagedRuntimeConfigDebug(config: ServerConfig): Promise<{
  managedFilePath: string;
  managedFileRebuiltAt: number | null;
  managedFileContentRedacted: string | null;
}> {
  const managedFilePath = omnirushRuntimeConfigFilePath(config);
  try {
    const [metadata, content] = await Promise.all([
      stat(managedFilePath),
      readFile(managedFilePath, "utf8"),
    ]);
    return {
      managedFilePath,
      managedFileRebuiltAt: metadata.mtimeMs,
      managedFileContentRedacted: redactManagedRuntimeConfigContent(content),
    };
  } catch {
    return { managedFilePath, managedFileRebuiltAt: null, managedFileContentRedacted: null };
  }
}

function userOpencodeConfigKeys(config: Record<string, unknown>): string[] {
  return Object.keys(config).filter((key) => key !== "$schema").sort();
}

function enqueueDesktopCloudSync<T>(operation: () => Promise<T>): Promise<T> {
  const run = desktopCloudSyncQueue.then(operation);
  desktopCloudSyncQueue = run.then(
    () => undefined,
    () => undefined,
  );
  return run;
}

const reloadBaselineRefreshers = new WeakMap<
  ServerConfig,
  (workspaceId: string, reasons?: ReloadReason[]) => Promise<void>
>();

/** The env store owned by a running server, for code that only holds its config. */
const envServicesByConfig = new WeakMap<ServerConfig, EnvService>();

export function envServiceForConfig(config: ServerConfig): EnvService | null {
  return envServicesByConfig.get(config) ?? null;
}

type LogLevel = "info" | "warn" | "error";

type LogAttributes = Record<string, unknown>;

type ServerLogger = {
  log: (level: LogLevel, message: string, attributes?: LogAttributes) => void;
};

type ServerLogWriter = (line: string) => void;

/** Adapt the server logger to the warn/error shape helpers expect. */
function toManagedProviderAuthLogger(logger: ServerLogger) {
  return {
    warn: (message: string, attributes?: Record<string, unknown>) =>
      logger.log("warn", message, attributes as LogAttributes | undefined),
    error: (message: string, attributes?: Record<string, unknown>) =>
      logger.log("error", message, attributes as LogAttributes | undefined),
  };
}

const LOG_LEVEL_NUMBERS: Record<LogLevel, number> = {
  info: 9,
  warn: 13,
  error: 17,
};

function toUnixNano(): string {
  return (BigInt(Date.now()) * 1_000_000n).toString();
}

function isUnavailableLogOutputError(error: unknown): boolean {
  if (!isRecord(error)) return false;
  // Redirected stdout can run out of space just like the optional file sink.
  // Logging must not turn an otherwise successful request into a server crash.
  return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED"
    || error.code === "ENOSPC" || error.code === "EDQUOT" || error.code === "EIO";
}

let stdoutLogWritesDisabled = false;
let stdoutErrorHandlerInstalled = false;

function ensureStdoutErrorHandler() {
  if (stdoutErrorHandlerInstalled) return;
  stdoutErrorHandlerInstalled = true;
  process.stdout.on("error", (error: unknown) => {
    if (isUnavailableLogOutputError(error)) {
      stdoutLogWritesDisabled = true;
      return;
    }
    process.nextTick(() => {
      throw error;
    });
  });
}

function writeStdoutLogLine(line: string) {
  ensureStdoutErrorHandler();
  if (stdoutLogWritesDisabled) return;
  process.stdout.write(`${line}\n`);
}

export function createServerLogger(
  config: ServerConfig,
  writeLine: ServerLogWriter = writeStdoutLogLine,
  fileSink: ServerLogFileSink | null = resolveServerLogFileSink(),
): ServerLogger {
  const runId = process.env.OMNIRUSH_RUN_ID ?? shortId();
  const host = hostname().trim();
  const resource: Record<string, string> = {
    "service.name": "omnirush-server",
    "service.version": SERVER_VERSION,
    "service.instance.id": runId,
  };
  if (host) {
    resource["host.name"] = host;
  }
  const baseAttributes: LogAttributes = {
    "run.id": runId,
    "process.pid": process.pid,
  };
  let logWritesDisabled = false;

  const writeLogLine = (line: string) => {
    if (logWritesDisabled) return;
    try {
      writeLine(line);
    } catch (error) {
      if (isUnavailableLogOutputError(error)) {
        logWritesDisabled = true;
        if (writeLine === writeStdoutLogLine) {
          stdoutLogWritesDisabled = true;
        }
        return;
      }
      throw error;
    }
  };

  const emit = (level: LogLevel, message: string, attributes?: LogAttributes) => {
    const merged = redactLogAttributes({ ...baseAttributes, ...(attributes ?? {}) });
    const record = {
      timeUnixNano: toUnixNano(),
      severityText: level.toUpperCase(),
      severityNumber: LOG_LEVEL_NUMBERS[level],
      body: message,
      attributes: merged,
      resource,
    };
    // The file sink is structured regardless of the stdout format: it exists
    // so rollover reasons and reload triggers survive a packaged app.
    if (fileSink) {
      const secrets = [
        config.token,
        config.hostToken,
        config.opencodePassword ?? "",
        ...config.workspaces.map((workspace) => workspace.opencodePassword ?? ""),
      ];
      fileSink.write(JSON.stringify(redactServerLogFileRecord(record, secrets)));
    }
    writeLogLine(config.logFormat === "json" ? JSON.stringify(record) : message);
  };

  return { log: emit };
}

function logRequest(input: {
  logger: ServerLogger;
  request: Request;
  response: Response;
  durationMs: number;
  authMode: AuthMode;
  proxyService?: "opencode";
  proxyBaseUrl?: string;
  error?: string;
  errorCode?: string;
  errorPath?: string;
  errorCause?: string;
}) {
  const {
    logger,
    request,
    response,
    durationMs,
    authMode,
    proxyService,
    proxyBaseUrl,
    error,
    errorCode,
    errorPath,
    errorCause,
  } = input;
  const status = response.status;
  const level: LogLevel = status >= 500 ? "error" : status >= 400 ? "warn" : "info";
  const url = new URL(request.url);
  const method = request.method.toUpperCase();
  const proxyLabel = proxyBaseUrl ? ` (${proxyService ?? "proxy"})` : "";
  const message = `${method} ${url.pathname} ${status} ${durationMs}ms${proxyLabel}`;
  const attributes: LogAttributes = {
    method,
    path: url.pathname,
    status,
    durationMs,
    auth: authMode,
  };
  if (proxyBaseUrl) {
    attributes["proxy.base_url"] = proxyBaseUrl;
    if (proxyService) attributes["proxy.service"] = proxyService;
  }
  if (error) {
    attributes.error = error;
  }
  if (errorCode) attributes["error.code"] = errorCode;
  if (errorPath) attributes["error.path"] = errorPath;
  if (errorCause) attributes["error.cause"] = errorCause;
  logger.log(level, message, attributes);
}

function parseWorkspaceMount(pathname: string): { workspaceId: string; restPath: string } | null {
  if (!pathname.startsWith("/w/")) return null;
  const remainder = pathname.slice(3);
  if (!remainder) return null;
  const slash = remainder.indexOf("/");
  if (slash === -1) {
    return { workspaceId: decodeURIComponent(remainder), restPath: "/" };
  }
  const workspaceId = remainder.slice(0, slash);
  const restPath = remainder.slice(slash) || "/";
  if (!workspaceId.trim()) return null;
  return { workspaceId: decodeURIComponent(workspaceId), restPath };
}

function parseWorkspaceOpencodeMount(pathname: string): { workspaceId: string; restPath: string } | null {
  if (!pathname.startsWith("/workspace/")) return null;
  const remainder = pathname.slice("/workspace/".length);
  if (!remainder) return null;
  const slash = remainder.indexOf("/");
  if (slash === -1) return null;
  const workspaceId = remainder.slice(0, slash);
  const restPath = remainder.slice(slash) || "/";
  if (!workspaceId.trim()) return null;
  if (restPath !== "/opencode" && !restPath.startsWith("/opencode/")) return null;
  return { workspaceId: decodeURIComponent(workspaceId), restPath };
}

function parseWorkspaceOpencodeV2Mount(pathname: string): { workspaceId: string; restPath: string } | null {
  if (!pathname.startsWith("/workspace/")) return null;
  const remainder = pathname.slice("/workspace/".length);
  if (!remainder) return null;
  const slash = remainder.indexOf("/");
  if (slash === -1) return null;
  const workspaceId = remainder.slice(0, slash);
  const restPath = remainder.slice(slash) || "/";
  if (!workspaceId.trim()) return null;
  if (restPath !== "/opencode2" && !restPath.startsWith("/opencode2/")) return null;
  return { workspaceId: decodeURIComponent(workspaceId), restPath };
}

/**
 * The proxy path as the engine's router will match it: prefix stripped and
 * percent-escapes decoded the way Hono decodes them (engine-route-path.ts).
 * Every path classifier below runs on this form so an encoded spelling of a
 * route ("/session/:id/prompt%5Fasync") is classified exactly like the plain
 * one the engine turns it into. The request is still forwarded verbatim.
 */
function normalizeOpencodeProxyPath(proxyPath: string): string {
  const raw = (proxyPath ?? "").trim() || "/";
  const withoutPrefix = raw.startsWith("/opencode") ? raw.slice("/opencode".length) : raw;
  const normalized = decodeEngineRoutePath(withoutPrefix || "/").replace(/\/+$/, "");
  return normalized || "/";
}

function proxiedSessionReadId(method: string, proxyPath: string): string | null {
  if (method.toUpperCase() !== "GET" && method.toUpperCase() !== "HEAD") return null;
  const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/(?:api\/)?session\/([^/]+)(?:\/|$)/);
  if (!match?.[1]) return null;
  // Let OpenCode answer malformed identifiers without weakening the gate for valid IDs.
  const sessionId = decodeEngineRouteParam(match[1]) ?? match[1];
  return sessionId === "status" ? null : sessionId;
}

async function assertWorkspaceOwnsProxiedSessionRead(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  method: string,
  proxyPath: string,
): Promise<void> {
  const sessionId = proxiedSessionReadId(method, proxyPath);
  const directory = resolveOpencodeDirectory(workspace);
  if (!sessionId || !directory) return;

  const readSession = () => createWorkspaceOpencodeClient(config, workspace, { sessionId }).session.get({ sessionID: sessionId });
  let result = await readSession();
  // A 500 here is, in practice, a damaged row in the engine's session store
  // (engine-store-repair.ts): set it aside while the engine runs and read again.
  if (result.error !== undefined && result.response?.status === 500 && isEngineUnknownError(result.error)
    && await repairEngineStoresAfterServerError() > 0) {
    result = await readSession();
  }
  if (result.error !== undefined) {
    if (result.response?.status === 404) {
      throw new ApiError(404, "session_not_found", "Session not found");
    }
    if (result.response?.status === 500 && isEngineUnknownError(result.error)) {
      throw new ApiError(502, "opencode_session_unreadable", "This chat could not be read right now. Restart OmniRush.ai to repair it; your chats are kept.", {
        status: result.response.status,
        body: result.error,
        path: `/session/${encodeURIComponent(sessionId)}`,
      });
    }
    throw new ApiError(502, "opencode_request_failed", "OmniRush request failed", {
      ...(result.response ? { status: result.response.status } : {}),
      body: result.error,
      path: `/session/${encodeURIComponent(sessionId)}`,
    });
  }

  const sessionDirectory = result.data?.directory?.trim();
  const [expectedDirectory, actualDirectory] = workspace.workspaceType === "local" && sessionDirectory
    ? await Promise.all([
        realpath(directory).catch(() => directory),
        realpath(sessionDirectory).catch(() => sessionDirectory),
      ])
    : [directory, sessionDirectory];
  // Local folders compare the way their file system does: a session created
  // before a case-only rename (Windows, macOS) still belongs to the folder.
  const sameDirectory = workspace.workspaceType === "local" && actualDirectory
    ? directoryMatchKey(actualDirectory) === directoryMatchKey(expectedDirectory)
    : actualDirectory === expectedDirectory;
  if (!actualDirectory || !sameDirectory) {
    throw new ApiError(404, "session_not_found", "Session not found");
  }
}

export function assertOpencodeProxyAllowed(actor: Actor, method: string, proxyPath: string) {
  const m = method.toUpperCase();
  const scope = actor.scope ?? "viewer";

  if (scope === "viewer" && m !== "GET" && m !== "HEAD") {
    throw new ApiError(403, "forbidden", "Viewer tokens are read-only");
  }

  // Prevent viewers from self-approving OpenCode permission requests via the
  // proxy. OpenCode uses /permission/:requestId/reply (and historically also
  // a session-scoped variant). Collaborators must be allowed: the SPA's only
  // credential is the collaborator-scoped client token (OMNIRUSH_TOKEN), so
  // an owner-only gate made every interactive permission dialog un-answerable
  // (403 "Only owner tokens can reply") and left tool calls stuck in
  // "running" forever (#1918).
  if (scope === "viewer" && m !== "GET" && m !== "HEAD") {
    const normalized = normalizeOpencodeProxyPath(proxyPath);
    if (/\/permission\/[^/]+\/reply$/.test(normalized)) {
      throw new ApiError(403, "forbidden", "Viewer tokens cannot reply to permission requests");
    }
  }
}

function isSessionCommandProxyRequest(method: string, proxyPath: string) {
  return method === "POST" && /^\/session\/[^/]+\/command$/.test(normalizeOpencodeProxyPath(proxyPath));
}

function commandAdmissionFromBody(body: ArrayBuffer | undefined): { messageId: string; fingerprint: string } | null {
  if (!body) return null;
  const text = new TextDecoder().decode(body);
  try {
    const value: unknown = JSON.parse(text);
    if (!isRecord(value) || typeof value.messageID !== "string" || !value.messageID.trim()) return null;
    return { messageId: value.messageID.trim(), fingerprint: hashToken(text) };
  } catch {
    return null;
  }
}

function admitSessionCommand(
  config: ServerConfig,
  scope: string,
  admission: { messageId: string; fingerprint: string },
): "accepted" | "duplicate" | "conflict" {
  const now = Date.now();
  const admissions = commandAdmissionsByServer.get(config) ?? new Map<string, { fingerprint: string; admittedAt: number }>();
  commandAdmissionsByServer.set(config, admissions);
  for (const [key, value] of admissions) {
    if (now - value.admittedAt <= COMMAND_ADMISSION_TTL_MS) break;
    admissions.delete(key);
  }

  const key = hashToken(`${scope}\0${admission.messageId}`);
  const existing = admissions.get(key);
  if (existing) return existing.fingerprint === admission.fingerprint ? "duplicate" : "conflict";

  if (admissions.size >= COMMAND_ADMISSION_CAPACITY) {
    const oldest = admissions.keys().next().value;
    if (oldest) admissions.delete(oldest);
  }
  admissions.set(key, { fingerprint: admission.fingerprint, admittedAt: now });
  return "accepted";
}

function isPromptAsyncProxyRequest(method: string, proxyPath: string) {
  return method === "POST" && /^\/session\/[^/]+\/prompt_async$/.test(normalizeOpencodeProxyPath(proxyPath));
}

// A prompt dispatch (v1 prompt_async, the v1 engine's synchronous prompt
// `POST /session/:id/message`, v2 prompt, or a slash command) is the session
// uploader's "prompt" milestone: the workspace is captured as the turn begins.
/** A new chat or a turn on the 1.x engine (retired for chats: the 2.x engine runs them). */
export function startsV1Chat(method: string, proxyPath: string): boolean {
  return method === "POST" && /^\/session(?:\/[^/]+\/(?:prompt_async|prompt|message|command|shell|summarize|init|fork))?\/?$/.test(normalizeOpencodeProxyPath(proxyPath));
}

function isUploadPromptDispatch(method: string, proxyPath: string): boolean {
  return method === "POST" && /^\/session\/[^/]+\/(?:prompt_async|prompt|message|command)$/.test(normalizeOpencodeProxyPath(proxyPath));
}

/**
 * Sign-in gate. A local workspace only runs sessions the omnirush.ai
 * session uploader can capture; without a connected account the engine prompt
 * dispatch is refused so no uncaptured turn ever starts. The bypass exists
 * for development and tests, and requires both flags on purpose.
 */
export const OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE = "Sign in to omnirush.ai from Settings to start a session.";

export function uploadGateBypassed(env: NodeJS.ProcessEnv = process.env): boolean {
  // OMNIRUSH_COLLECTION_OPTIONAL is the pre-2.2.2 name of the second flag, still honoured.
  return env.OMNIRUSH_DEV_MODE === "1" && (env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL === "1" || env.OMNIRUSH_COLLECTION_OPTIONAL === "1");
}

function uploadAccountRequiredResponse(): Response {
  return jsonResponse({ error: "omnirush_account_required", message: OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE }, 403);
}

/**
 * Whether the gate refuses a prompt dispatch on this workspace: a local
 * workspace whose session uploader cannot capture the turn, without the development
 * bypass. A remote workspace is gated by the server that owns it. Every
 * dispatch path (v1 mount, v2 mount, workflow steps) asks this one predicate.
 */
function uploadDispatchRefused(config: ServerConfig, workspace: WorkspaceInfo | undefined): boolean {
  if (!workspace || workspace.workspaceType === "remote") return false;
  return !captureServicesByServer.get(config)?.uploadEnabled && !uploadGateBypassed();
}

/** The gate as an ApiError, for dispatches that are not proxied HTTP requests. */
export function assertUploadDispatchAllowed(config: ServerConfig, workspace: WorkspaceInfo | undefined): void {
  if (uploadDispatchRefused(config, workspace)) {
    throw new ApiError(403, "omnirush_account_required", OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE);
  }
}

/**
 * The project folder's write check (folder-write-check.ts) before a chat's
 * first turn there: a folder the engine cannot write to stops the prompt with
 * the reason and the fix instead of letting the agent run turns that change
 * nothing. Prompts for the read-only plan agent go on.
 */
async function folderWriteRefusal(config: ServerConfig, workspace: WorkspaceInfo, sessionId: string, request: Request): Promise<Response | null> {
  const dir = resolveOpencodeDirectory(workspace) ?? workspace.path;
  if (!dir) return null;
  const body: unknown = await request.clone().json().catch(() => null);
  if (readOnlyPrompt(body)) return null;
  const failed = await folderWriteGate(sessionId, dir).catch(() => null);
  if (!failed) return null;
  createServerLogger(config).log("warn", "Project folder is not writable.", {
    "folder_write.reason": failed.reason,
    "folder_write.code": failed.code ?? "",
    "folder_write.step": failed.step,
    "folder_write.via": failed.via,
  });
  await request.arrayBuffer().catch(() => undefined);
  return jsonResponse({ error: FOLDER_NOT_WRITABLE, reason: failed.reason, message: failed.message, hint: failed.hint }, 409);
}

// The v2 daemon's dispatch routes, matched on the decoded path like the v1 classifier.
/** Migrated chats whose agent was checked this run (engine-v2-migration.ts): one look per chat. */
const migratedAgentsChecked = new Set<string>();

/**
 * A chat that came from 1.x keeps its 1.x agent (the 1.x desktop's "omnirush"), which the 2.x engine does not have:
 * every new turn then fails before it reaches a model ("Agent not found"). Before such a chat's turn, an agent the
 * engine does not list is switched to the engine's own "build" (what a 2.x chat runs on).
 */
export async function ensureMigratedChatAgent(engine: (path: string, init?: RequestInit) => Promise<Response>, sessionId: string, checked = migratedAgentsChecked): Promise<string | null> {
  if (checked.has(sessionId)) return null;
  const read = async (path: string): Promise<unknown> => {
    const response = await engine(path);
    if (!response.ok) { await response.body?.cancel().catch(() => undefined); return null; }
    const payload = (await response.json().catch(() => null)) as unknown;
    return isRecord(payload) && "data" in payload ? payload.data : payload;
  };
  const session = await read(`/api/session/${encodeURIComponent(sessionId)}`);
  const agents = await read("/api/agent");
  if (!isRecord(session) || !Array.isArray(agents)) return null;
  checked.add(sessionId);
  const agent = typeof session.agent === "string" ? session.agent : null;
  const known = agents.some((entry) => isRecord(entry) && (entry.id === agent || entry.name === agent));
  if (!agent || known) return null;
  const switched = await engine(`/api/session/${encodeURIComponent(sessionId)}/agent`, { method: "POST", body: JSON.stringify({ agent: "build" }), headers: { "content-type": "application/json" } });
  await switched.body?.cancel().catch(() => undefined);
  return switched.ok ? agent : null;
}

/** A 2.x request that starts a turn the capture follows; a compaction (the app's Compact context) too, as 1.x `summarize`. */
export function isUploadV2PromptDispatch(method: string, routePath: string): boolean {
  return method === "POST" && /^\/api\/session\/[^/]+\/(?:prompt|prompt_async|command|generate|compact)$/.test(routePath.replace(/\/+$/, ""));
}

/**
 * Workflow steps are prompt dispatches like any other: they enter the same
 * engine proxy as the app's requests, so the gate, the session uploader's session
 * start, prompt snapshot, request/response trace and turn observer all apply.
 */
export function createLocalWorkflowPromptDispatcher(config: ServerConfig): LocalWorkflowPromptDispatcher {
  return {
    assertAllowed: (workspace) => assertUploadDispatchAllowed(config, workspace),
    prompt: (workspace, sessionId, body, signal) => {
      // The v1 engine's synchronous prompt route; it has no `/prompt` (its
      // catch-all answers that with a 200 web page, and nothing runs).
      const proxyPath = `/opencode/session/${encodeURIComponent(sessionId)}/message`;
      const url = new URL(`http://127.0.0.1${proxyPath}`);
      const request = new Request(url, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(body),
        signal,
      });
      return proxyOpencodeRequest({ config, request, url, workspace, proxyPath, recoverySignal: signal });
    },
  };
}

// The session a captured engine request belongs to, read from the decoded
// route path exactly as the engine reads its `:id` parameter. Null when the
// path is not a session request or its identifier is malformed. `message` is
// a dispatch only when posted (a GET reads the history).
function uploadSessionId(proxyPath: string, method: string): string | null {
  const path = normalizeOpencodeProxyPath(proxyPath);
  const match = path.match(/^\/session\/([^/]+)\/(?:prompt_async|prompt|command|abort|interrupt)$/)
    ?? (method === "POST" ? path.match(/^\/session\/([^/]+)\/message$/) : null);
  return match?.[1] ? decodeEngineRouteParam(match[1]) : null;
}

function uploadDeletedSessionId(method: string, proxyPath: string): string | null {
  if (method !== "DELETE") return null;
  const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)$/);
  return match?.[1] ? decodeEngineRouteParam(match[1]) : null;
}

type EngineRequestTarget = { baseUrl: string; headers: Headers };

/**
 * The engine holding a chat of a local workspace, scoped like the proxy's
 * requests, for settling a turn a previous process left open; null for a
 * remote or unknown workspace, no engine, or an engine without the chat.
 */
async function captureEngineTarget(config: ServerConfig, sessionId: string, workspaceId: string): Promise<EngineTarget | null> {
  const workspace = config.workspaces.find((item) => item.id === workspaceId);
  if (!workspace || workspace.workspaceType === "remote") return null;
  // The 2.x engine (every chat since it shipped), when it has the chat in this workspace's folder.
  const v2 = engineV2ByServer.get(config)?.connection();
  if (v2) {
    const headers = new Headers({ authorization: `Basic ${Buffer.from(`opencode:${v2.password}`).toString("base64")}` });
    const search = `?${new URLSearchParams({ "location[directory]": workspace.path })}`;
    const found = await loopbackFetch(buildOpencodeProxyUrl(v2.url, `/api/session/${encodeURIComponent(sessionId)}`, search), { headers, signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS) })
      .then(async (response) => { await response.body?.cancel().catch(() => undefined); return response.ok; }).catch(() => false);
    if (found) return engineTarget(v2.url, headers, search, "v2");
  }
  const route = enginePoolForConfig(config)?.routeRequest("GET", `/session/${sessionId}/message`) ?? null;
  const connection = route ? null : resolveWorkspaceOpencodeConnection(config, workspace);
  const baseUrl = route?.target.baseUrl ?? connection?.baseUrl?.trim() ?? "";
  if (!baseUrl) return null;
  const auth = route ? buildEngineAuthProbeHeader(route.target.username, route.target.password) : connection?.authHeader ?? null;
  const directory = resolveOpencodeDirectory(workspace);
  if (!(await engineHasSession(baseUrl, auth, directory, sessionId))) return null;
  const headers = new Headers();
  if (auth) headers.set("Authorization", auth);
  const scoped = scopeWorkspaceOpencodeRequest(headers, "", directory);
  return engineTarget(baseUrl, scoped.headers, scoped.search);
}

/** How long the existence check before a chat's first captured prompt waits for the engine. */
const ENGINE_SESSION_CHECK_TIMEOUT_MS = 3_000;

/**
 * Whether the engine has this session: false only when it answers 404. An
 * engine that is slow or unreachable counts as having it, so no prompt it
 * does run goes uncaptured.
 */
export async function engineHasSession(baseUrl: string, auth: string | null, directory: string | null, sessionId: string): Promise<boolean> {
  const headers = new Headers();
  if (auth) headers.set("Authorization", auth);
  const scoped = scopeWorkspaceOpencodeRequest(headers, "", directory);
  try {
    const response = await loopbackFetch(buildOpencodeProxyUrl(baseUrl, `/session/${encodeURIComponent(sessionId)}`, scoped.search), {
      method: "GET",
      headers: scoped.headers,
      signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS),
    });
    await response.body?.cancel().catch(() => undefined);
    return response.status !== 404;
  } catch {
    return true;
  }
}

/** The provider a 2.x chat runs on (its engine session's model), or null when unreadable. */
export async function engineChatProvider(engine: EngineTarget, sessionId: string): Promise<string | null> {
  try {
    const response = await loopbackFetch(buildOpencodeProxyUrl(engine.baseUrl, `/api/session/${encodeURIComponent(sessionId)}`, engine.search), { headers: new Headers(engine.headers), signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS) });
    if (!response.ok) {
      await response.body?.cancel().catch(() => undefined);
      return null;
    }
    const body: unknown = await response.json();
    const model = isRecord(body) && isRecord(body.data) && isRecord(body.data.model) ? body.data.model : null;
    return typeof model?.providerID === "string" ? model.providerID : null;
  } catch {
    return null;
  }
}

/** The message a chat's undo currently rewinds to (its revert point), or null: read before an undo or redo. */
async function engineRevertPoint(baseUrl: string, auth: string | null, directory: string | null, sessionId: string): Promise<string | null> {
  const headers = new Headers();
  if (auth) headers.set("Authorization", auth);
  const scoped = scopeWorkspaceOpencodeRequest(headers, "", directory);
  try {
    const response = await loopbackFetch(buildOpencodeProxyUrl(baseUrl, `/session/${encodeURIComponent(sessionId)}`, scoped.search), {
      method: "GET",
      headers: scoped.headers,
      signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS),
    });
    if (!response.ok) {
      await response.body?.cancel().catch(() => undefined);
      return null;
    }
    const session = await response.json() as { revert?: { messageID?: unknown } | null } | null;
    return typeof session?.revert?.messageID === "string" ? session.revert.messageID : null;
  } catch {
    return null;
  }
}

/** When the engine created a chat's message (ms), or null when it cannot say. */
async function engineMessageCreated(baseUrl: string, auth: string | null, directory: string | null, sessionId: string, messageId: string): Promise<number | null> {
  const headers = new Headers();
  if (auth) headers.set("Authorization", auth);
  const scoped = scopeWorkspaceOpencodeRequest(headers, "", directory);
  try {
    const response = await loopbackFetch(buildOpencodeProxyUrl(baseUrl, `/session/${encodeURIComponent(sessionId)}/message/${encodeURIComponent(messageId)}`, scoped.search), {
      method: "GET",
      headers: scoped.headers,
      signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS),
    });
    if (!response.ok) {
      await response.body?.cancel().catch(() => undefined);
      return null;
    }
    const message = await response.json() as { info?: { time?: { created?: unknown } } } | null;
    const created = message?.info?.time?.created;
    return typeof created === "number" && Number.isFinite(created) ? created : null;
  } catch {
    return null;
  }
}

const SESSION_STOP_TIMEOUT_MS = 5_000;
const SESSION_STOP_MAX_SESSIONS = 100;

async function engineJson(target: EngineRequestTarget, path: string, directory: string | null, init?: { method: string }): Promise<unknown> {
  const scoped = scopeWorkspaceOpencodeRequest(target.headers, "", directory);
  const response = await loopbackFetch(buildOpencodeProxyUrl(target.baseUrl, path, scoped.search), {
    method: init?.method ?? "GET",
    headers: scoped.headers,
    signal: AbortSignal.timeout(SESSION_STOP_TIMEOUT_MS),
  });
  if (!response.ok) {
    await response.body?.cancel().catch(() => undefined);
    return null;
  }
  return response.json().catch(() => null);
}

/**
 * The engine's session delete removes the records and cancels background
 * jobs, not the session's own run: a turn inside a long tool call goes on
 * running (and writing into the folder) with its status stuck on busy, which
 * also parks every engine restart that waits for running sessions. Abort the
 * session and its sub-agent sessions first, each in its own folder's engine
 * instance (the one its run lives in) and on every engine that may run it.
 * Best effort and bounded: the delete goes ahead whatever this finds.
 */
async function stopSessionTreeBeforeDelete(targets: EngineRequestTarget[], sessionId: string, requestDirectory: string | null): Promise<void> {
  await Promise.all(targets.map(async (target) => {
    const sessions: Array<{ id: string; directory: string | null }> = [];
    const queue = [sessionId];
    const seen = new Set<string>();
    while (queue.length > 0 && sessions.length < SESSION_STOP_MAX_SESSIONS) {
      const id = queue.shift() ?? "";
      if (seen.has(id)) continue;
      seen.add(id);
      const info = await engineJson(target, `/session/${encodeURIComponent(id)}`, requestDirectory).catch(() => null);
      if (!isRecord(info)) continue;
      sessions.push({ id, directory: typeof info.directory === "string" && info.directory.trim() ? info.directory : null });
      const children = await engineJson(target, `/session/${encodeURIComponent(id)}/children`, requestDirectory).catch(() => null);
      if (Array.isArray(children)) {
        for (const child of children) if (isRecord(child) && typeof child.id === "string") queue.push(child.id);
      }
    }
    await Promise.all(sessions.map((session) =>
      engineJson(target, `/session/${encodeURIComponent(session.id)}/abort`, session.directory, { method: "POST" }).catch(() => null),
    ));
  }));
}

export async function startServer(config: ServerConfig): Promise<ServeResult> {
  let taskRecovery: Awaited<ReturnType<typeof createTaskRecovery>> | undefined;
  const approvals = new ApprovalService(config.approval);
  const uiControl = new UiControlMailbox();
  const reloadEvents = new ReloadEventStore();
  const tokens = new TokenService(config);
  const env = new EnvService();
  envServicesByConfig.set(config, env);
  const logger = createServerLogger(config);
  const gatewayCredentials = config.omnirushGatewayCredentials ?? (
    process.env.OMNIRUSH_GATEWAY_URL && process.env.OMNIRUSH_ACCESS_TOKEN && process.env.OMNIRUSH_REFRESH_TOKEN
      ? {
          gatewayUrl: process.env.OMNIRUSH_GATEWAY_URL,
          accessToken: process.env.OMNIRUSH_ACCESS_TOKEN,
          refreshToken: process.env.OMNIRUSH_REFRESH_TOKEN,
        }
      : undefined
  );
  // The quota wrap on the 2.x engine (engine-v2-budget-wrap.ts): set once the engine below exists.
  let budgetWrap: ReturnType<typeof createV2BudgetWrap> | undefined;
  const gatewayBroker = new OmniRushGatewayBroker({
    onModelResponse: (sessionId, headers) => budgetWrap?.noteResponse(sessionId, headers),
    contextWrap: (sessionId) => budgetWrap?.contextWrap(sessionId) ?? false,
    sessionModelsFile: join(runtimeStorageDir(config), "chat-models.json"),
    log: (level, message, attributes) => logger.log(level, message, attributes),
    credentials: gatewayCredentials
      ? {
          ...gatewayCredentials,
          // A device session the server retired (a refused refresh) keeps
          // the queued uploads and archives, each stamped with its account,
          // for when the account signs in again; only a user's sign-out
          // deletes them (config.clearUploadQueue at the next start).
          invalidate: async () => {
            gatewayBroker.resetCapabilities();
            await gatewayCredentials.invalidate?.();
          },
        }
      : undefined,
    engineToken: config.omnirushEngineToken,
    ...(config.captureFileUpload ? { uploadFile: config.captureFileUpload } : {}),
    // A sub-agent request moved to the main model: new sub-agent prompts skip
    // the refused model for a while, and the session uploader records the model the
    // sub-agent's messages really ran on.
    subagentModelRefused: (model) => subagentModelRefusals(config).isRefused(model),
    // Reasoning summaries for every reasoning model the account's catalog
    // lists on the Codex route (not a hardcoded pair of ids).
    reasoningSummaryFor: async (model) => omnirushModelWantsReasoningSummary(await readOmniRushModelCatalog(config), model),
    // A catalog model outside the chat's mode (box or native, model-modes/) is refused before it is sent;
    // a model the catalog does not list goes to the gateway, which judges.
    modelInMode: async (model, box) => {
      const entry = (await readOmniRushModelCatalog(config)).find((candidate) => candidate.id === model);
      return !entry || modelAllowedIn(entry, projectMode(box));
    },
    // A chat may switch between the models of one provider (the catalog's switch_group).
    switchable: async (bound, asked) => switchableModels(await readOmniRushModelCatalog(config), bound, asked),
    // Strict sessions: a chat's bind names the box revision it started under.
    chatPin: (sessionId) => boxServiceFor(config).chatPin(sessionId),
    // The capture policy the server stored for a chat: its pin and its uploads keep that one.
    onCapturePolicy: (sessionId, policy) => {
      void boxServiceFor(config).setCapturePolicy(sessionId, policy);
      captureServicesByServer.get(config)?.pinPolicy(sessionId, policy);
    },
    // Whether the chat's binding is verified, and why it was bound late (kept in its pin, never shown).
    onBinding: (sessionId, binding) => { void boxServiceFor(config).updatePin(sessionId, binding); },
    // Strict sessions under enforce: a chat's uploads wait for its confirmed binding.
    onUploadHold: (sessionId, state, seq) => { captureServicesByServer.get(config)?.holdUploads(sessionId, state, seq); },
    // The last strict-session switch per server: it stands while capabilities cannot be fetched.
    strictStateFile: join(runtimeStorageDir(config), "strict-sessions.json"),
    // The desktop's update gate (banner, blocked view); session uploads and
    // project archives go on whatever it says.
    ...(config.omnirushGatewayCredentials?.onUpdateSignal ? { onUpdateSignal: config.omnirushGatewayCredentials.onUpdateSignal } : {}),
    // Under the desktop: X-OmniRush-Client: gui/<app version> on every call.
    ...(config.appVersion?.trim() ? { clientVersion: config.appVersion.trim() } : {}),
    // A chat's title request, as sent, and the title the model wrote: a `model.request` record of kind "title" (never a turn).
    onModelRequest: (sessionId, data) => recordOpenSessionTrace(config, sessionId, "model.request", data),
    onSubagentFallback: (event) => {
      if (event.reason !== "refused_recently") subagentModelRefusals(config).mark(event.requested, event.reason);
      recordSubagentModelFallback(config, event.rootSessionId, {
        kind: "gateway",
        child_session_id: event.sessionId,
        message_id: event.messageId,
        requested_model: event.requested,
        used_model: event.used,
        used_effort: event.effort,
        reason: event.reason,
        status: event.status,
        ok: event.ok,
        at: event.at,
      });
    },
  });
  // Automatic compaction: the server's policy (auto_compact) through the capabilities cache; the
  // window shows a short notice (the "auto.compact.notice" query) while a chat compacts. Not in stock mode (stock-mode.mjs).
  if (gatewayBroker.enabled && !stockMode()) {
    autoCompactorsByServer.set(config, new AutoCompactor({
      policy: brokerAutoCompactPolicy((options) => gatewayBroker.sessionUploadCapabilities(options)),
      holdMs: AUTO_COMPACT_HOLD_MS,
      seedWaitMs: AUTO_COMPACT_SEED_WAIT_MS,
      log: (level, message, attributes) => logger.log(level, message, attributes),
      notify: (sessionID, stage) => { void uiControl.request("query", { id: "auto.compact.notice", args: { sessionID, stage } }); },
    }));
  }
  if (gatewayBroker.enabled) sessionIntegrityByServer.set(config, (sessionId, options) => gatewayBroker.sessionIntegrity(sessionId, options));
  if (gatewayBroker.enabled) modelSwitchRefusalsByServer.set(config, (sessionId, model) => gatewayBroker.modelSwitchRefusal(sessionId, model));
  if (gatewayBroker.enabled) chatPinsByServer.set(config, (sessionId) => gatewayBroker.chatModel(sessionId));
  if (gatewayBroker.enabled) sideCallsByServer.set(config, brokerSideCall(gatewayBroker, config.omnirushEngineToken ?? ""));
  if (gatewayBroker.enabled) computerUseCapabilitiesByServer.set(config, (maxAgeMs) => gatewayBroker.sessionUploadCapabilities({ strict: true, maxAgeMs }));
  if (gatewayBroker.enabled) workBrokersByServer.set(config, {
    workRequest: (path, init) => gatewayBroker.workRequest(path, init),
    accountId: () => gatewayBroker.accountId(),
    capabilities: () => gatewayBroker.sessionUploadCapabilities({ strict: true }),
  });
  voiceServicesByServer.set(config, new OmniRushVoiceService(gatewayBroker, {
    log: (level, message, attributes) => logger.log(level, message, attributes),
  }));
  // Under the desktop the embedding host passes the Electron app version
  // through ServerConfig; a standalone server reports its own version.
  const appVersion = config.appVersion?.trim()
    || process.env.OMNIRUSH_APP_VERSION?.trim()
    || SERVER_VERSION;
  // The session uploader, and whole-folder archives of git projects beside
  // it (session-archive/README.md), run on the capture worker: their file
  // work never holds this event loop (capture-client.ts).
  const archiveSettings = projectArchiveSettings({
    config,
    gatewayBroker,
    uploadEnabled: sessionUploaderEnabled({ upload: gatewayBroker.enabled }),
  });
  // The install log's wrappers (install-log-host.ts): ready before any engine starts.
  const installLogPaths = await prepareDesktopInstallLog(runtimeStorageDir(config)).catch(() => null);
  // The Linux sandbox's install log: the box mounts the wrappers; its calls go to a raw folder of their own (box/install-log.ts).
  const boxInstallLog = await prepareBoxInstallLog(runtimeStorageDir(config), installLogPaths).catch(() => null);
  boxServiceFor(config).useInstallLog(boxInstallLog);
  const capture = startCaptureService({
    stateDir: runtimeStorageDir(config),
    ...(installLogPaths ? { installLog: { raw: installLogPaths.raw, bin: installLogPaths.bin } } : {}),
    ...(boxInstallLog ? { boxInstallLog: { raw: boxInstallLog.raw, bin: boxInstallLog.bin } } : {}),
    appVersion,
    // "opencode/1.18.32-r2": the bundled engine, as every upload names it (engine-identity.ts).
    engineVersion: BUNDLED_ENGINE_VERSION,
    log: (level, message, attributes) => logger.log(level, message, attributes),
    // A turn a crashed process or worker left open is settled from the engine that has its chat.
    engineTarget: (sessionId: string, workspaceId: string) => captureEngineTarget(config, sessionId, workspaceId),
    ...(gatewayBroker.enabled
      ? { accountId: () => gatewayBroker.accountId(), sessionIntegrity: (sessionId: string, options?: { summary?: boolean; turns?: number }) => gatewayBroker.sessionIntegrity(sessionId, options) }
      : {}),
    sessionUploader: gatewayBroker.enabled
      ? {
          upload: (sessionId, compressed, signal, request) => gatewayBroker.uploadSession(sessionId, compressed, signal, request),
          uploadFile: (sessionId, path, size, signal, request) => gatewayBroker.uploadSessionFile(sessionId, path, size, signal, request),
          // Strict: a failed check throws, and the uploader keeps the format the server last advertised.
          capabilities: () => gatewayBroker.sessionUploadCapabilities({ strict: true }),
          refreshAccessToken: () => gatewayBroker.refreshAccessToken(),
        }
      : {},
    archive: {
      enabled: archiveSettings.enabled,
      excludedDirs: archiveSettings.excludedDirs,
      folderGate: archiveSettings.folderGate,
      ...(archiveSettings.auth === "broker"
        ? {
            request: (path: string, init: ArchiveApiRequestInit) => gatewayBroker.archiveRequest(path, init),
            refreshAccessToken: () => gatewayBroker.refreshAccessToken(),
          }
        : archiveSettings.auth === "environment"
          ? { gatewayUrl: archiveSettings.gatewayUrl, accessToken: archiveSettings.accessToken }
          : {}),
      baseIdleMs: PROJECT_ARCHIVE_BASE_IDLE_MS,
      baseMaxDeferMs: PROJECT_ARCHIVE_BASE_MAX_DEFER_MS,
    },
  });
  captureServicesByServer.set(config, capture);
  // The Linux sandbox (box/): every workspace whose box is on is planned in the background (a missing
  // image starts downloading), and the server's default (local_box) is read for the engine config.
  const boxes = boxServiceFor(config, (level, message, attributes) => logger.log(level, message, attributes));
  let stopBoxDefaultWatch: () => void = () => {};
  let stopWebSearchWatch: () => void = () => {};
  let stopMcpPolicyWatch: () => void = () => {};
  let stopComputerUseWatch: () => void = () => {};
  let stopProviderLockWatch: () => void = () => {};
  if (gatewayBroker.enabled) {
    // Read before the first plan and the engine's first config (at most 1.5 s, else the last answer is
    // used until it comes): a switch flipped or rolled back on the server applies at this start.
    // The MCP list (mcp-allow/state.ts) is remembered from the same answer: the engine's MCP plugin reads it when a project starts.
    const read = gatewayBroker.sessionUploadCapabilities().then((capabilities) => {
      rememberMcpPolicy(runtimeStorageDir(config), capabilities);
      return rememberServerDefault(runtimeStorageDir(config), capabilities);
    }).catch(() => false);
    // The model's own web search (web-search.ts), from the same answer. Strict: a failed read keeps
    // the last answer, while an answer without the block (an older server) turns it off.
    const readWebSearch = gatewayBroker.sessionUploadCapabilities({ strict: true }).then((capabilities) => rememberWebSearchSwitch(runtimeStorageDir(config), capabilities)).catch(() => false);
    // The model provider lock (provider-lock.ts), from the same answer. Strict: a failed read (or no
    // account) keeps it locked; only an answer saying `locked: false` unlocks it, in memory only.
    const readProviderLock = gatewayBroker.sessionUploadCapabilities({ strict: true }).catch(() => null).then((capabilities) => applyProviderLockAnswer(capabilities));
    const inTime = await Promise.race([Promise.all([read, readWebSearch, readProviderLock]).then(() => true), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_500).unref?.())]);
    if (!inTime) void read.then((changed) => (changed ? applyServerBoxDefault(config, boxes) : undefined)).catch(() => undefined);
    if (!inTime) void readWebSearch.then((changed) => (changed ? applyBoxEngineConfig(config, "web_search") : undefined)).catch(() => undefined);
    if (!inTime) void readProviderLock.then((changed) => (changed ? applyBoxEngineConfig(config, "provider_lock", { restart: true }) : undefined)).catch(() => undefined);
    // Read again while the app runs: a switch flipped on the server applies without a restart (the
    // engine config is rewritten and the engine replaced, since its environment carries the lock too).
    stopProviderLockWatch = watchProviderLock({
      read: () => gatewayBroker.sessionUploadCapabilities({ strict: true }),
      apply: () => applyBoxEngineConfig(config, "provider_lock", { restart: true }),
      everyMs: BOX_DEFAULT_REFRESH_MS,
    });
    stopWebSearchWatch = watchWebSearchSwitch({
      stateDir: runtimeStorageDir(config),
      read: () => gatewayBroker.sessionUploadCapabilities({ strict: true }),
      apply: () => applyBoxEngineConfig(config, "web_search"),
      everyMs: BOX_DEFAULT_REFRESH_MS,
    });
    // Read again while the app stays open (from the capabilities cache: at most one request per its
    // TTL), so a switch flipped on the server reaches an app started before it without a restart.
    // Computer use (computer-use/desktop.ts): remembered from the same answer; a change restarts the
    // engine's projects so the built-in server comes or goes. Electron main reads it again every 60 s
    // while a computer use session is open (POST /computer-use/refresh).
    void gatewayBroker.sessionUploadCapabilities({ strict: true }).then((capabilities) => (rememberComputerUseSwitch(runtimeStorageDir(config), capabilities) ? applyComputerUseEngine(config) : undefined)).catch(() => undefined);
    // Work mode (work/work.ts): remembered from the same answer; a change restarts the engine's projects so the
    // Work folder's hosted server comes or goes.
    void gatewayBroker.sessionUploadCapabilities({ strict: true }).then((capabilities) => (rememberWorkSwitch(workDir(runtimeStorageDir(config)), capabilities) ? applyComputerUseEngine(config, "work") : undefined)).catch(() => undefined);
    const computerUseTimer = setInterval(() => {
      void gatewayBroker.sessionUploadCapabilities({ strict: true }).then((capabilities) => (rememberComputerUseSwitch(runtimeStorageDir(config), capabilities) ? applyComputerUseEngine(config) : undefined)).catch(() => undefined);
      void gatewayBroker.sessionUploadCapabilities({ strict: true }).then((capabilities) => (rememberWorkSwitch(workDir(runtimeStorageDir(config)), capabilities) ? applyComputerUseEngine(config, "work") : undefined)).catch(() => undefined);
    }, BOX_DEFAULT_REFRESH_MS);
    computerUseTimer.unref?.();
    stopComputerUseWatch = () => clearInterval(computerUseTimer);
    stopMcpPolicyWatch = watchMcpPolicy({
      stateDir: runtimeStorageDir(config),
      read: () => gatewayBroker.sessionUploadCapabilities(),
      everyMs: BOX_DEFAULT_REFRESH_MS,
    });
    stopBoxDefaultWatch = watchServerDefault({
      stateDir: runtimeStorageDir(config),
      read: () => gatewayBroker.sessionUploadCapabilities(),
      apply: () => applyServerBoxDefault(config, boxes),
      everyMs: BOX_DEFAULT_REFRESH_MS,
    });
  }
  // Windows, back after "Set up (one restart)": the setup finishes (WSL update, then the usual box start).
  void boxes.resumeSetup().catch(() => false);
  void boxes.ensureAll();
  // The server asks for the sandbox images ahead (local_box.setup.prefetch): the base image too, in the background.
  void boxes.prefetch().catch(() => false);
  if (config.clearUploadQueue) {
    // The user signed out: what the last account queued stays on disk for it (stamped with it, set aside
    // at the next start under another account, sent after its own next sign-in).
    await Promise.race([capture.signOut(), new Promise((resolvePromise) => setTimeout(resolvePromise, 10_000).unref?.())]);
  }
  try {
    await reconcileLocalManagedMcpRuntimeEntries(config);
  } catch (error) {
    logger.log("warn", "Failed to reconcile OmniRush.ai-managed MCP connections during startup.", {
      error: error instanceof Error ? error.message : "unknown",
    });
  }
  let watcherHandle = startReloadWatchers({ config, reloadEvents, logger });
  const refreshWorkspaceReloadBaseline = (workspaceId: string, reasons?: ReloadReason[]) =>
    watcherHandle.refreshWorkspace(workspaceId, reasons);
  reloadBaselineRefreshers.set(config, refreshWorkspaceReloadBaseline);
  const restartReloadWatchers = () => {
    watcherHandle.close();
    watcherHandle = startReloadWatchers({ config, reloadEvents, logger });
  };
  const engineMcpServerState = beginEngineMcpServerState(config);
  const engineInstanceReaper = new EngineInstanceReaper({
    // Only the managed engine is swept: the pool exists exactly when this
    // server owns the engine process. An attached engine may serve other
    // clients, so its per-directory instances are not ours to trim.
    engineBaseUrl: () => enginePoolForConfig(config)?.primaryUrl() ?? null,
    activeDirectory: () => {
      const active = config.workspaces[0];
      return active ? resolveOpencodeDirectory(active) : null;
    },
    directoryBusy: (instance) => engineInstanceHasActiveSessions(config, instance),
    dispose: (instance) => disposeIdleEngineInstance(config, engineMcpServerState, instance),
    logger,
  });
  setEngineInstanceReaperForConfig(config, engineInstanceReaper);
  const cloudProviderSync = new CloudProviderSync({
    config,
    env,
    reloadEngine: () => reloadOpencodeEngine(
      config,
      resolveEngineRuntimeWorkspace(config),
      engineMcpServerState,
      { forceStandby: true, reason: "cloud_provider_sync" },
    ),
    engineBusy: () => {
      const pool = enginePoolForConfig(config);
      return pool
        ? Promise.resolve(pool.hasDrainingGeneration())
        : engineHasActiveSessions(config, resolveEngineRuntimeWorkspace(config));
    },
    logger: toManagedProviderAuthLogger(logger),
  });
  managedDesktopPolicy(config).onChange = () => {
    // Sign-in can precede the first workspace. Its future engine reads the
    // persisted policy at startup; there is no running workspace to reload.
    if (config.workspaces.length > 0) cloudProviderSync.markReloadPending();
  };
  // Claude chats (claude-code/chat.ts): the engine's Claude provider asks /omnirush-claude/turn, with this key, for each turn.
  const claudeKey = randomBytes(24).toString("base64url");
  const claudeTurn = claudeChatRoute({
    // Asked fresh at each turn: access taken away refuses at once (not after the relay's 403s), a grant needs no restart.
    access: () => gatewayBroker.claudeAccess({ fresh: true }),
    authorize: (context) => gatewayBroker.claudeGrant(context),
    pin: (sessionId) => gatewayBroker.chatModel(sessionId),
    setPin: (sessionId, model) => gatewayBroker.pinChatModel(sessionId, model),
    onClaudeChat: ({ sessionID }) => captureServicesByServer.get(config)?.markClaude(sessionID, CLAUDE_CODE_VERSION),
    // The turn's native transcript, unchanged, as `claude/` members of the chat's claude_native archive (only a chat whose uploads are on).
    onTurnEnd: async ({ sessionID, uuid, grant }) => {
      const capture = captureServicesByServer.get(config);
      const bits = boxServiceFor(config).claudeBits();
      const configDir = grant && uuid && bits ? claudeConfigDirOf(bits.home, uuid) : null;
      if (!grant || !configDir || !capture?.uploadEnabled || !capture.hasSession(sessionID)) return;
      const uploader = new ArchiveUploader({ fetch: externalFetch, request: (route, init) => gatewayBroker.nativeCaptureRequest(grant.owner, route, init) });
      const receipt = await uploadClaudeTurn({
        // The archive names the bare Claude Code version (the collector refuses "claude-code/<v>" there).
        grant, uuid, configDir, stateDir: runtimeStorageDir(config), engineVersion: CLAUDE_CODE_VERSION,
        request: (route, init) => gatewayBroker.nativeCaptureRequest(grant.owner, route, init),
        driver: { fetchKey: (signal) => uploader.fetchKey(signal), upload: (job, persist, signal) => uploader.upload(job, persist, signal), sealer: (options) => new SealStream(options), tarHeader: tarMemberHeader },
      }).catch((error: unknown) => ({ status: "failed", reason: error instanceof Error ? error.message : String(error) }));
      logger.log("info", "claude: native transcript upload", { status: receipt.status, native: "native" in receipt ? receipt.native.status : null, code: "native" in receipt ? receipt.native.code ?? null : "reason" in receipt ? receipt.reason : null });
    },
    log: (level, message, attributes) => logger.log(level, message, attributes),
  });
  claudeTurnsByServer.set(config, { key: claudeKey, handle: claudeTurn });
  // The Claude models the engine was last given: the status route mirrors again when the account's catalog differs (a sign-in after start).
  let mirroredClaude: string | null = null;
  const engineV2Preview = createEngineV2Preview({
    config, env, deferStart: true,
    claude: async () => {
      const bits = boxServiceFor(config).claudeBits();
      const access = await gatewayBroker.claudeAccess().catch((error: unknown) => {
        logger.log("info", "claude: no catalog for the engine yet", { error: error instanceof Error ? error.message.slice(0, 200) : "unknown" });
        throw error;
      });
      mirroredClaude = (access.catalog ?? []).map((entry) => entry.id).join(",");
      return claudeEngineProvider(access.catalog ?? [], {
        grantURL: `http://127.0.0.1:${config.port}/omnirush-claude/turn`, grantKey: claudeKey,
        ...(bits ? { shell: bits.shell, boxHome: bits.home } : {}),
        client: `gui/${config.appVersion?.trim() || SERVER_VERSION}`, note: CLAUDE_AUTO_NOTE,
      });
    },
  });
  engineV2Refreshers.set(config, () => engineV2Preview.refreshProviders());
  engineV2ByServer.set(config, engineV2Preview);
  /** A chat on the 2.x engine, read where it lives (its folder), or null. */
  const v2ChatTarget = async (sessionId: string): Promise<EngineTarget | null> => {
    const v2 = engineV2Preview.connection();
    if (!v2) return null;
    const headers = new Headers({ authorization: `Basic ${Buffer.from(`opencode:${v2.password}`).toString("base64")}` });
    const found: unknown = await loopbackFetch(buildOpencodeProxyUrl(v2.url, `/api/session/${encodeURIComponent(sessionId)}`, ""), { headers, signal: AbortSignal.timeout(5_000) })
      .then(async (response) => (response.ok ? response.json() : null)).catch(() => null);
    const info = isRecord(found) && isRecord(found.data) ? found.data : null;
    const directory = info && isRecord(info.location) && typeof info.location.directory === "string" ? info.location.directory : null;
    return directory ? engineTarget(v2.url, headers, `?${new URLSearchParams({ "location[directory]": directory })}`, "v2") : null;
  };
  // Stock mode (stock-mode.mjs): no wrap-up offer (the gateway's own quota answer still shows).
  budgetWrap = stockMode() ? undefined : createV2BudgetWrap({
    control: async (id, args) => {
      const result: unknown = await uiControl.request("query", { id, args });
      if (!isRecord(result) || result.ok !== true || !isRecord(result.result)) return "unavailable";
      return typeof result.result.choice === "string" ? result.result.choice : "ok";
    },
    busy: async (sessionId) => {
      const target = await v2ChatTarget(sessionId);
      return target ? desktopAutoCompactEngine(target, sessionId).busy() : null;
    },
    compact: async (sessionId) => {
      const target = await v2ChatTarget(sessionId);
      if (!target) throw new Error("the chat is not on the engine");
      await desktopAutoCompactEngine(target, sessionId).summarize({ providerID: "omnirush", modelID: "" }, AbortSignal.timeout(5 * 60_000));
    },
  });
  const bestPracticesReloads = new BestPracticesEngineReloads({
    isBusy: (workspace) => engineHasActiveSessions(config, workspace, true),
    reload: (workspace) => reloadOpencodeEngine(config, workspace, engineMcpServerState, { reason: "engine_reload" }),
    isPresent: (workspace) => config.workspaces.includes(workspace),
  });
  const routes = createRoutes(
    config,
    approvals,
    tokens,
    env,
    restartReloadWatchers,
    engineMcpServerState,
    logger,
    cloudProviderSync,
    engineV2Preview,
    bestPracticesReloads,
  );

  // The picker's Claude entries (claude-models.ts): the account's Claude catalog and the ids it may run.
  addRoute(routes, "GET", "/workspace/:id/claude/status", "client", async (ctx) => {
    requireClientScope(ctx, "owner");
    const access = await gatewayBroker.claudeAccess().catch(() => null);
    if (access && (access.catalog ?? []).map((entry) => entry.id).join(",") !== mirroredClaude) void engineV2Preview.refreshProviders().catch(() => undefined);
    const response = jsonResponse({ allowed: Boolean(access?.models?.length), catalog: access?.catalog ?? [], models: access?.models ?? [], reason: access ? access.reason ?? null : "unavailable" });
    response.headers.set("cache-control", "no-store");
    return response;
  });

  const serverOptions: {
    hostname: string;
    port: number;
    fetch: (request: Request) => Response | Promise<Response>;
  } = {
    hostname: config.host,
    port: config.port,
    fetch: async (request: Request) => {
      const url = new URL(request.url);
      const startedAt = Date.now();
      let authMode: AuthMode = "none";
      let proxyService: "opencode" | undefined;
      let proxyBaseUrl: string | undefined;
      let errorMessage: string | undefined;
      let errorCode: string | undefined;
      let errorPath: string | undefined;
      let errorCause: string | undefined;

      const recordApiError = (apiError: ApiError) => {
        errorMessage = apiError.message;
        errorCode = apiError.code;
        if (!isRecord(apiError.details)) return;
        const path = apiError.details.path;
        if (typeof path === "string") errorPath = path;
        const cause = apiError.details.cause;
        if (typeof cause === "string") errorCause = cause;
      };

      const finalize = (response: Response) => {
        const wrapped = withCors(response, request, config);
        if (config.logRequests) {
            logRequest({
              logger,
              request,
              response: wrapped,
              durationMs: Date.now() - startedAt,
              authMode,
              proxyService,
              proxyBaseUrl,
              error: errorMessage,
              errorCode,
              errorPath,
              errorCause,
            });
        }
        return wrapped;
      };

      // Settings writes, secret reads and approval answers need the app itself (app-request-gate.ts).
      const appRefusal = appRequestRefusal(request.method, url.pathname, request.headers);
      if (appRefusal) {
        errorMessage = appRefusal.message;
        errorCode = appRefusal.code;
        return finalize(jsonResponse(appRefusal, 403));
      }

      const proxyWorkspaceOpencodeMount = async (mount: { workspaceId: string; restPath: string }) => {
        authMode = "client";
        try {
          const actor = await requireClient(request, config, tokens);
          assertOpencodeProxyAllowed(actor, request.method, mount.restPath);
          await managedDesktopPolicy(config).assertRequest(request, mount.restPath, true);
          await assertProxiedEngineRequestWithinProviderLock(request, mount.restPath);
          const workspace = await resolveWorkspaceWithoutBootstrap(config, mount.workspaceId);
          assertEngineStartedWithinLock(resolveWorkspaceOpencodeConnection(config, workspace).baseUrl, request.method, mount.restPath);
          await assertWorkspaceOwnsProxiedSessionRead(config, workspace, request.method, mount.restPath);
          proxyService = "opencode";
          proxyBaseUrl = workspace.baseUrl?.trim() || undefined;
          const send = () => proxyOpencodeRequest({ config, request, url, workspace, proxyPath: mount.restPath,
            recoverySignal: taskRecovery?.owns(request) ? request.signal : undefined });
          const response = taskRecovery ? await taskRecovery.forward(workspace, "v1", decodeEngineRoutePath(mount.restPath), request, send) : await send();
          return finalize(response);
        } catch (error) {
          const requestCanceled = isExpectedRequestCancellation(error, request.signal);
          if (!(error instanceof ApiError) && !requestCanceled) {
            captureServerException(error, { method: request.method, route: "/workspace/:id/opencode/*", requestSignal: request.signal });
          }
          const apiError = error instanceof ApiError
            ? error
            : requestCanceled
              ? new ApiError(499, "request_aborted", "Request was canceled")
              : new ApiError(500, "internal_error", "Unexpected server error");
          recordApiError(apiError);
          return finalize(jsonResponse(formatError(apiError), apiError.status));
        }
      };

      const proxyWorkspaceOpencodeV2Mount = async (mount: { workspaceId: string; restPath: string }) => {
        authMode = "client";
        try {
          const actor = await requireClient(request, config, tokens);
          assertOpencodeProxyAllowed(actor, request.method, mount.restPath);
          await managedDesktopPolicy(config).assertRequest(request, mount.restPath, true);
          await assertProxiedEngineRequestWithinProviderLock(request, mount.restPath);
          const workspace = await resolveWorkspaceWithoutBootstrap(config, mount.workspaceId);
          // Right after the app starts the engine may still be starting: the request waits for it (bounded).
          const connection = await engineV2Preview.awaitConnection(ENGINE_V2_START_WAIT_MS);
          if (!connection) {
            const notRunning = jsonResponse({ error: "engine_v2_preview_not_running", retryable: true, message: "The engine is not running yet. Try again in a moment." }, 503);
            notRunning.headers.set("Retry-After", "5");
            return finalize(notRunning);
          }
          assertEngineStartedWithinLock(connection.url, request.method, mount.restPath);
          proxyService = "opencode";
          proxyBaseUrl = connection.url;
          await engineV2Preview.ensureWorkspaceReady(workspace.path);
          // The project's allowed MCP servers reach the engine before the next call (engine-v2-mcp.ts);
          // a write first refreshes the app-added entries the filter reads.
          if (request.method !== "GET" && request.method !== "HEAD") await writeWorkspaceMcpFile(config, workspace);
          await engineV2Preview.syncWorkspaceMcp(workspace.id, workspace.path);
          const send = () => proxyOpencodeV2Request({
            config,
            request,
            url,
            workspace,
            proxyPath: mount.restPath,
            connection,
            recoverySignal: taskRecovery?.owns(request) ? request.signal : undefined,
            migratedFromV1: engineV2Preview.migratedFromV1,
          });
          const response = taskRecovery ? await taskRecovery.forward(workspace, "v2", decodeEngineRoutePath(mount.restPath), request, send) : await send();
          return finalize(response);
        } catch (error) {
          const requestCanceled = isExpectedRequestCancellation(error, request.signal);
          if (!(error instanceof ApiError) && !requestCanceled) {
            captureServerException(error, { method: request.method, route: "/workspace/:id/opencode2/*", requestSignal: request.signal });
          }
          const apiError = error instanceof ApiError
            ? error
            : requestCanceled
              ? new ApiError(499, "request_aborted", "Request was canceled")
              : new ApiError(500, "internal_error", "Unexpected server error");
          recordApiError(apiError);
          return finalize(jsonResponse(formatError(apiError), apiError.status));
        }
      };

      if (request.method === "OPTIONS") {
        return finalize(new Response(null, { status: 204 }));
      }

      // The engine's Claude provider (claude-code/chat.ts): its key, never a client token.
      if (url.pathname === "/omnirush-claude/turn") {
        authMode = "client";
        const turn = claudeTurnsByServer.get(config);
        const key = Buffer.from(request.headers.get("x-omnirush-usage-key") ?? "");
        if (!turn || request.method !== "POST" || key.length !== Buffer.byteLength(turn.key) || !timingSafeEqual(key, Buffer.from(turn.key))) {
          return finalize(jsonResponse({ ok: false, message: "forbidden" }, 403));
        }
        const input = await request.json().catch(() => null) as ClaudeChatInput | null;
        const answer = input ? await turn.handle(input).catch((error: unknown) => ({ ok: false, message: error instanceof Error ? error.message : String(error) })) : { ok: false, message: "bad request" };
        const response = jsonResponse(answer);
        response.headers.set("cache-control", "no-store");
        return finalize(response);
      }
      // Work mode's hosted MCP server for the engine (work/engine.ts): the engine's own token, the account's
      // credential added here.
      if (url.pathname === "/omnirush/work/mcp") {
        authMode = "client";
        const work = workBrokersByServer.get(config);
        const given = Buffer.from((request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, ""));
        const engineToken = Buffer.from(config.omnirushEngineToken ?? "");
        if (!work || engineToken.length === 0 || given.length !== engineToken.length || !timingSafeEqual(given, engineToken)) {
          return finalize(jsonResponse({ detail: "forbidden" }, 403));
        }
        return finalize(await forwardWorkMcp(request, work).catch(() => jsonResponse({ detail: "work_unreachable" }, 502)));
      }
      const gatewayMount = url.pathname.match(/^\/omnirush-gateway\/v1\/(.+)$/);
      if (gatewayMount?.[1]) {
        authMode = "client";
        try {
          return finalize(await gatewayBroker.handle(request, gatewayMount[1]));
        } catch (error) {
          // The broker answers every upstream failure itself; anything that
          // still escapes is logged with its cause and reaches the engine as a
          // readable, retryable error instead of a bare 500 from serve-node.
          const requestCanceled = isExpectedRequestCancellation(error, request.signal);
          if (requestCanceled) return finalize(jsonResponse({ code: "request_aborted", message: "Request was canceled" }, 499));
          captureServerException(error, { method: request.method, route: "/omnirush-gateway/v1", requestSignal: request.signal });
          logger.log("error", "omnirush.ai gateway request failed", {
            path: gatewayMount[1],
            error: error instanceof Error ? `${error.name}: ${error.message}`.slice(0, 300) : "unknown",
          });
          errorMessage = "gateway_error";
          return finalize(new Response(JSON.stringify({
            error: { message: "omnirush.ai: the model request failed inside the app. Retrying shortly.", type: "omnirush_error", code: "gateway_local_error" },
          }), { status: 502, headers: { "content-type": "application/json", "retry-after": "2" } }));
        }
      }

      const canonicalOpencodeMount = parseWorkspaceOpencodeMount(url.pathname);
      if (canonicalOpencodeMount) {
        return proxyWorkspaceOpencodeMount(canonicalOpencodeMount);
      }

      const canonicalOpencodeV2Mount = parseWorkspaceOpencodeV2Mount(url.pathname);
      if (canonicalOpencodeV2Mount) {
        return proxyWorkspaceOpencodeV2Mount(canonicalOpencodeV2Mount);
      }

      const mount = parseWorkspaceMount(url.pathname);
      if (mount && (mount.restPath === "/opencode" || mount.restPath.startsWith("/opencode/"))) {
        return proxyWorkspaceOpencodeMount(mount);
      }
      if (mount && (mount.restPath === "/opencode2" || mount.restPath.startsWith("/opencode2/"))) {
        return proxyWorkspaceOpencodeV2Mount(mount);
      }

      // Allow clients to use a mounted base URL (e.g. http://host:8787/w/<id>) while
      // still calling the existing /workspace/:id/* API surface.
      // Example: baseUrl + "/workspace/<id>/plugins" => "/w/<id>/workspace/<id>/plugins".
      // We strip the mount prefix and route-match on the rest path.
      //
      // Important: when using a mounted base URL, enforce that the nested /workspace/:id
      // matches the mount workspace id to preserve the "single-workspace" mental model.
      if (mount && mount.restPath.startsWith("/workspace/")) {
        const match = mount.restPath.match(/^\/workspace\/([^/]+)/);
        const nestedId = match?.[1] ? decodeURIComponent(match[1]) : null;
        if (nestedId && nestedId !== mount.workspaceId) {
          errorMessage = "not_found";
          return finalize(jsonResponse({ code: "not_found", message: "Not found" }, 404));
        }
        url.pathname = mount.restPath;
      }

      // The global 2.x client (web, gateway): the first workspace's engine, as /opencode below.
      if ((url.pathname === "/opencode2" || url.pathname.startsWith("/opencode2/")) && config.workspaces[0]) {
        return proxyWorkspaceOpencodeV2Mount({ workspaceId: config.workspaces[0].id, restPath: url.pathname });
      }

      if (url.pathname === "/opencode" || url.pathname.startsWith("/opencode/")) {
        authMode = "client";
        proxyBaseUrl = config.workspaces[0]?.baseUrl?.trim() || undefined;
        try {
          const actor = await requireClient(request, config, tokens);
          assertOpencodeProxyAllowed(actor, request.method, url.pathname);
          await managedDesktopPolicy(config).assertRequest(request, url.pathname, true);
          await assertProxiedEngineRequestWithinProviderLock(request, url.pathname);
          proxyService = "opencode";
          const workspace = config.workspaces[0];
          if (workspace) assertEngineStartedWithinLock(resolveWorkspaceOpencodeConnection(config, workspace).baseUrl, request.method, url.pathname);
          if (workspace) {
            await assertWorkspaceOwnsProxiedSessionRead(config, workspace, request.method, url.pathname);
          }
          const send = () => proxyOpencodeRequest({ config, request, url, workspace });
          const response = taskRecovery && workspace ? await taskRecovery.forward(workspace, "v1", decodeEngineRoutePath(url.pathname), request, send) : await send();
          return finalize(response);
        } catch (error) {
          const requestCanceled = isExpectedRequestCancellation(error, request.signal);
          if (!(error instanceof ApiError) && !requestCanceled) {
            captureServerException(error, { method: request.method, route: "/opencode/*", requestSignal: request.signal });
          }
          const apiError = error instanceof ApiError
            ? error
            : requestCanceled
              ? new ApiError(499, "request_aborted", "Request was canceled")
              : new ApiError(500, "internal_error", "Unexpected server error");
          recordApiError(apiError);
          return finalize(jsonResponse(formatError(apiError), apiError.status));
        }
      }

      const route = matchRoute(routes, request.method, url.pathname);
      if (!route) {
        const staticUiResponse = await serveStaticUi(request, config);
        if (staticUiResponse) return finalize(staticUiResponse);
        errorMessage = "not_found";
        return finalize(jsonResponse({ code: "not_found", message: "Not found" }, 404));
      }

      authMode = route.auth;
      try {
        const actor =
          route.auth === "host-token"
            ? requireHostToken(request, config)
            : route.auth === "host"
              ? await requireHost(request, config, tokens)
              : route.auth === "client" || (route.auth === "policy" && !managedDesktopPolicy(config).authenticatesEvaluation(request))
                ? await requireClient(request, config, tokens)
                : undefined;
        await managedDesktopPolicy(config).assertRequest(request, url.pathname);
        const response = await route.handler({
          request,
          url,
          params: route.params,
          config,
          approvals,
          uiControl,
          reloadEvents,
          tokens,
          actor,
        });
        return finalize(response);
      } catch (error) {
        const requestCanceled = isExpectedRequestCancellation(error, request.signal);
        if (!(error instanceof ApiError) && !requestCanceled) {
          captureServerException(error, { method: request.method, route: url.pathname, requestSignal: request.signal });
          console.error("[omnirush-server] Unhandled error:", error);
        }
        const apiError = error instanceof ApiError
          ? error
          : requestCanceled
            ? new ApiError(499, "request_aborted", "Request was canceled")
            : new ApiError(500, "internal_error", "Unexpected server error");
        recordApiError(apiError);
        const response = jsonResponse(formatError(apiError), apiError.status);
        const isAgentDiagnosticsRequest =
          request.method === "POST" && /^\/workspace\/[^/]+\/diagnostics\/agent-context$/.test(url.pathname);
        if (isAgentDiagnosticsRequest) {
          // Every diagnostics error closes the connection because failures such
          // as cooldown or in-flight rejection happen before body consumption.
          // Abort after a short flush window so the stable JSON error reaches the
          // client before unread bytes and drip streams are actively terminated.
          response.headers.set("Connection", "close");
          const requestBody = request.body;
          if (requestBody) {
            setTimeout(() => {
              void requestBody.cancel(new Error("Agent diagnostics request was rejected")).catch(() => undefined);
            }, AGENT_DIAGNOSTICS_ERROR_FLUSH_MS);
          }
        }
        return finalize(response);
      }
    },
  };

  let server: ServeResult;
  try {
    if (config.resumeInterruptedTasks && !config.readOnly) {
      taskRecovery = await createTaskRecovery(config, async (request) => serverOptions.fetch(request),
        () => managedDesktopPolicy(config).assert("sync"));
      setTaskRecovery(config, taskRecovery);
    }
    server = await serve({
      ...serverOptions,
      idleTimeout: 120,
    });
  } catch (error) {
    stopBoxDefaultWatch();
    stopWebSearchWatch();
    stopMcpPolicyWatch();
    stopComputerUseWatch();
    stopProviderLockWatch();
    bestPracticesReloads.stop();
    // First, and synchronously: archive part uploads in flight are aborted now, not after the other shutdown steps.
    const captureStopped = capture.stop();
    await taskRecovery?.stop().catch(() => undefined);
    await captureStopped;
    captureServicesByServer.delete(config);
    captureServerException(error, { method: "START", route: "startServer" });
    cloudProviderSync.stop();
    await engineV2Preview.stop().catch(() => undefined);
    editorLspByServer.get(config)?.close();
    engineInstanceReaper.close();
    clearEngineInstanceReaperForConfig(config);
    invalidateEngineMcpServerState(config, engineMcpServerState);
    watcherHandle.close();
    reloadBaselineRefreshers.delete(config);
    throw error;
  }

  if (config.port !== server.port) {
    config.port = server.port;
    try {
      await reconcileLocalManagedMcpRuntimeEntries(config);
    } catch (error) {
      logger.log("warn", "Failed to update OmniRush.ai-managed MCP loopback routes after binding the server port.", {
        error: error instanceof Error ? error.message : "unknown",
      });
    }
  }
  // Policy hooks must receive the listener that actually bound, including
  // ephemeral ports and retries after a port collision.
  engineV2Preview.start();

  // Deliver server-managed provider credentials to the engine on startup. The
  // engine process receives a fixed env allowlist, so credentials materialized
  // into the env store only reach it through the engine's auth API. A delivered
  // credential also invalidates any SDK client the engine cached before auth
  // arrived; the sync coordinator lands that reload without interrupting a
  // live session.
  resetManagedProviderAuthCache();
  void syncManagedProviderAuth({ config, env, logger: toManagedProviderAuthLogger(logger) })
    .then((result) => {
      if (result.delivered.length > 0 || result.removed.length > 0) {
        cloudProviderSync.markReloadPending();
      }
    })
    .catch(() => undefined);

  engineInstanceReaper.start();
  // The account's model catalog (omnirush-model-catalog-sync.ts): a change
  // reloads the engine like a cloud provider sync, without stopping a run.
  const modelCatalogSync = startOmniRushModelCatalogSync({
    config,
    broker: gatewayBroker,
    reloadEngine: async () => {
      // The 2.x engine runs every chat: it gets the new models from its providers (engine-v2-preview.ts mirror).
      await engineV2Preview.refreshProviders();
      // No 1.x engine runs chats then: its reload would fail and be retried every 15 s, re-mirroring each time.
      if (config.workspaces.length === 0 || engineV2Preview.status().chatRouting) return;
      await reloadOpencodeEngine(config, resolveEngineRuntimeWorkspace(config), engineMcpServerState, {
        forceStandby: true,
        reason: "omnirush_model_catalog",
      });
    },
    // A catalog change waits until no session runs: a standby engine next to
    // live runs means two engine processes writing one session database, and
    // new models are never urgent enough for that.
    engineBusy: async () => {
      const pool = enginePoolForConfig(config);
      if (!pool) return engineHasActiveSessions(config, resolveEngineRuntimeWorkspace(config));
      if (pool.hasDrainingGeneration()) return true;
      const busy = await collectBusyEngineSessions(config);
      return busy.sessions.length > 0 || busy.unknown > 0;
    },
    log: (level, message, attributes) => logger.log(level, message, attributes),
  });

  /** Whether the omnirush.ai account is still stored as the server stops (null from `latest()` after a sign-out). */
  const accountStillStored = async (): Promise<boolean> => {
    if (!gatewayCredentials) return false;
    if (!gatewayCredentials.latest) return true;
    return (await gatewayCredentials.latest()) !== null;
  };

  return {
    ...server,
    stop: async () => {
      // First, and synchronously: a stop is also how a user sign-out reaches
      // this server (the desktop clears the account, then restarts it), so
      // archive part uploads in flight are aborted before anything else runs.
      // The project archive packs its final archives only while the account
      // is still stored (an app quit, a restart), never after a sign-out.
      // Before them, each chat in a box gets its last checkpoint (bounded; only when chats ran in a
      // box this run, and the account answers it is still stored within a second).
      stopBoxDefaultWatch();
      stopWebSearchWatch();
      stopMcpPolicyWatch();
      stopComputerUseWatch();
      stopProviderLockWatch();
      const archiveFinals = accountStillStored();
      if (boxes.hasChats() && await Promise.race([archiveFinals.catch(() => false), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_000).unref?.())])) {
        await boxes.finals({ budgetMs: 10_000 }).catch(() => []);
      }
      boxes.close();
      const captureStopped = capture.stop({ archiveFinals });
      bestPracticesReloads.stop();
      let recoveryError: unknown;
      try { await taskRecovery?.stop(); } catch (error) { recoveryError = error; }
      await captureStopped;
      captureServicesByServer.delete(config);
      await localWorkflowServices.get(config)?.stop();
      managedDesktopPolicy(config).onChange = undefined;
      cloudProviderSync.stop();
      modelCatalogSync.stop();
      await engineV2Preview.stop().catch(() => undefined);
      editorLspByServer.get(config)?.close();
      engineInstanceReaper.close();
      clearEngineInstanceReaperForConfig(config);
      invalidateEngineMcpServerState(config, engineMcpServerState);
      watcherHandle.close();
      reloadBaselineRefreshers.delete(config);
      await server.stop();
      if (recoveryError) throw recoveryError;
    },
  };
}

/**
 * A prompt's wait for the turn before's background processes (capture-host.ts
 * archiveStartGate): only for a local workspace outside a sandbox, whose
 * processes run on this machine. The engines' processes are never waited for.
 */
function lateWritesGate(workspace: WorkspaceInfo, enginePids: ReadonlyArray<number | null> = []): LateWritesGate | null {
  if (workspace.workspaceType === "remote" || workspace.sandboxBackend || workspace.sandboxRunId || workspace.sandboxContainerName) return null;
  return { exclude: enginePids.filter((pid): pid is number => typeof pid === "number" && pid > 0) };
}

/**
 * The engine v2 preview mount. A prompt dispatch here is gated and captured
 * exactly like one on the v1 mount: refused without a connected account
 * (unless both development flags are set), otherwise the session uploader starts the
 * session, captures the prompt snapshot, traces the request and response and
 * observes the turn until it settles. Exported for the mount's tests.
 */
/** A send its user stopped before it reached the engine (held for the sandbox): never dispatched, and not counted as a turn of its chat. */
function stoppedSendResponse(config: ServerConfig, sessionId: string | null | undefined): Response {
  if (sessionId) boxServiceFor(config).promptCancelled(sessionId);
  return jsonResponse({ code: "send_stopped", message: "The send was stopped before it reached the engine." }, 409);
}

/**
 * A 2.x model as the window may see it: model overrides and variants can carry credentials too, so only the metadata
 * needed for selection, and the variants' names (the effort picker), never their settings.
 */
export function publicV2Model(value: unknown): Record<string, unknown> | null {
  if (value === null) return null;
  if (!isRecord(value) || typeof value.id !== "string" || typeof value.providerID !== "string") {
    throw new ApiError(502, "invalid_engine_response", "Invalid model metadata");
  }
  const picked = Object.fromEntries(Object.entries(value).filter(([key]) => [
    "id", "modelID", "providerID", "canonical", "family", "name", "package",
    "capabilities", "time", "cost", "status", "enabled", "limit",
  ].includes(key)));
  const variants = Array.isArray(value.variants)
    ? value.variants.flatMap((variant) => (isRecord(variant) && typeof variant.id === "string" ? [{ id: variant.id }] : []))
    : [];
  return variants.length ? { ...picked, variants } : picked;
}

export async function proxyOpencodeV2Request(input: {
  config: ServerConfig;
  request: Request;
  url: URL;
  workspace: WorkspaceInfo;
  proxyPath: string;
  connection: { url: string; username: string; password: string };
  recoverySignal?: AbortSignal;
  /** Whether a chat came from the 1.x store: its turns are marked and kept out of deliveries. */
  migratedFromV1?: (sessionId: string) => boolean;
}): Promise<Response> {
  const method = input.request.method.toUpperCase();
  if (method !== "GET" && method !== "HEAD") ensureWritable(input.config);

  const withoutPrefix = input.proxyPath.slice("/opencode2".length);
  const forwardedPath = withoutPrefix || "/";
  // Classify on the path as the daemon's router matches it (see engine-route-path),
  // so an encoded spelling of a dispatch route cannot skip the gate or the session uploader.
  const routePath = decodeEngineRoutePath(forwardedPath);
  // The private-route checks match the fully decoded spelling as before; a
  // malformed escape (which the daemon leaves in place) falls back to the
  // route form instead of failing the request.
  let decodedPath: string;
  try { decodedPath = decodeURIComponent(forwardedPath); } catch { decodedPath = routePath; }
  // Runtime provider configuration contains server-owned credentials. The
  // renderer uses the catalog/status APIs; it must not read or mutate this file.
  if (/^\/api\/(?:experimental\/)?config(?:\/|$)/.test(decodedPath)) {
    throw new ApiError(403, "engine_config_private", "Engine configuration is private");
  }
  // MCP servers follow the server's list (engine-v2-mcp.ts): the engine's own MCP routes stay closed.
  if (/^(?:\/api(?:\/experimental)?)?\/mcp(?:\/|$)/.test(decodedPath) && method !== "GET" && method !== "HEAD") {
    throw new ApiError(403, "engine_mcp_managed", "Manage connections through OmniRush.ai");
  }
  const sessionMatch = routePath.match(/^\/api\/session\/([^/]+)(?:\/|$)/);
  const sessionId = sessionMatch?.[1] ? decodeEngineRouteParam(sessionMatch[1]) : null;
  const promptDispatch = isUploadV2PromptDispatch(method, routePath);
  // Farm runs (stock mode) only in the box, which keeps them offline: refused before any upload or model call.
  const farmRefused = promptDispatch ? await boxServiceFor(input.config).farmRefusal(input.workspace) : null;
  if (farmRefused) {
    await input.request.arrayBuffer().catch(() => undefined);
    return jsonResponse({ error: "farm_needs_sandbox", message: `omnirush: ${farmRefused.line}`, ...(farmRefused.retryAfter ? { retryable: true, retry_after: farmRefused.retryAfter } : {}) }, 409);
  }
  const collectible = input.workspace.workspaceType !== "remote";
  if (promptDispatch && collectible) {
    if (uploadDispatchRefused(input.config, input.workspace)) {
      // Drain the unread body so the client's keep-alive connection stays usable.
      await input.request.arrayBuffer().catch(() => undefined);
      return uploadAccountRequiredResponse();
    }
    if (sessionId === null) {
      // A dispatch is either refused or captured: a session identifier the
      // daemon cannot decode would start a turn the session uploader cannot attribute.
      await input.request.arrayBuffer().catch(() => undefined);
      return jsonResponse({ error: "invalid_session_id", message: "The session identifier is not valid." }, 400);
    }
    const notWritable = await folderWriteRefusal(input.config, input.workspace, sessionId, input.request);
    if (notWritable) return notWritable;
    await awaitOmniRushModelCatalogSettled(input.config);
  }
  // The agent works from here (the prompt is on its way) until the engine runs no session.
  const turnActivity = promptDispatch && collectible && sessionId !== null ? turnActivityFor(input.config) : null;
  turnActivity?.promptDispatched();
  if (promptDispatch && sessionId !== null) computerUseChats(input.config).mark(sessionId);
  const target = new URL(input.connection.url);
  target.pathname = forwardedPath;
  target.search = input.url.search;
  if (forwardedPath.startsWith("/api/")) {
    for (const key of [...target.searchParams.keys()]) {
      if (key === "location" || key.startsWith("location[")) target.searchParams.delete(key);
    }
    target.searchParams.set("location[directory]", input.workspace.path);
  }

  const headers = new Headers(input.request.headers);
  headers.delete("authorization");
  headers.delete("x-omnirush-host-token");
  headers.delete(APP_SECRET_HEADER);
  headers.delete("x-omnirush-client-id");
  headers.delete("host");
  headers.delete("origin");
  headers.set("authorization", `Basic ${Buffer.from(`opencode:${input.connection.password}`).toString("base64")}`);

  // The v2 daemon has a global session namespace: a location query does not
  // prevent reading a session owned by another workspace. Match the v1 mount's
  // ownership boundary before forwarding session reads or mutations.
  let sessionPermissions: unknown;
  if (sessionId?.startsWith("ses_")) {
    const sessionUrl = new URL(target);
    sessionUrl.pathname = `/api/session/${encodeURIComponent(sessionId)}`;
    sessionUrl.search = "";
    sessionUrl.searchParams.set("location[directory]", input.workspace.path);
    const sessionHeaders = new Headers(headers);
    sessionHeaders.delete("content-length");
    sessionHeaders.delete("transfer-encoding");
    const sessionResponse = await loopbackFetch(sessionUrl.toString(), {
      headers: sessionHeaders,
      signal: AbortSignal.timeout(10_000),
    });
    if (!sessionResponse.ok) return sanitizeProxyResponse(sessionResponse);
    const payload: unknown = await sessionResponse.json();
    const data = isRecord(payload) && isRecord(payload.data) ? payload.data : payload;
    const session = isRecord(data) && isRecord(data.info) ? data.info : data;
    const location = isRecord(session) && isRecord(session.location) ? session.location : null;
    const directory = location && typeof location.directory === "string" ? location.directory : null;
    sessionPermissions = isRecord(session) ? session.permissions : undefined;
    const [expected, actual] = await Promise.all([
      realpath(input.workspace.path).catch(() => input.workspace.path),
      directory ? realpath(directory).catch(() => directory) : null,
    ]);
    // Compared as the file system does (case on Windows and macOS), as the sidebar's by-folder list matches.
    if (!actual || directoryMatchKey(actual) !== directoryMatchKey(expected)) {
      throw new ApiError(404, "session_not_found", "Session not found");
    }
  }

  if (method !== "GET" && method !== "HEAD"
    && decodedPath.endsWith(`/instructions/entries/${OMNIRUSH_V2_INSTRUCTION_KEY}`)) {
    throw new ApiError(403, "engine_instructions_managed", "OmniRush.ai instructions are managed by the server");
  }

  // Stock mode (stock-mode.mjs): the engine's own system prompt only, no OmniRush guidance.
  if (method === "POST" && sessionId && !stockMode() && /^\/api\/session\/[^/]+\/(?:prompt|command|generate)$/.test(routePath)) {
    // Session ownership was verified above. Replace one native instruction
    // entry immediately before admission; never append to conversation text.
    const internalHeaders = new Headers({ authorization: headers.get("authorization") ?? "", "content-type": "application/json" });
    const skillUrl = new URL(target);
    skillUrl.pathname = "/api/skill";
    await waitForOmniRushV2Skills(input.workspace.path, async () => {
      const response = await loopbackFetch(skillUrl.toString(), { headers: internalHeaders, signal: AbortSignal.timeout(5_000) });
      if (!response.ok) throw new ApiError(502, "engine_skill_sync_failed", "Native skills are unavailable");
      return response.json();
    });
    // Work mode (work/engine.ts): a Work chat's own rules (no shell or code tools, writes ask) and the Work prompt.
    const workChat = isV2WorkRoot(workDir(runtimeStorageDir(input.config)), input.workspace.path);
    const workRules = workChat ? withV2WorkPermissions(sessionPermissions) : null;
    if (workRules) {
      const sessionUrl = new URL(target);
      sessionUrl.pathname = `/api/session/${encodeURIComponent(sessionId)}`;
      const patched = await loopbackFetch(sessionUrl.toString(), {
        method: "PATCH", headers: internalHeaders, body: JSON.stringify({ permissions: workRules }), signal: AbortSignal.timeout(15_000),
      });
      if (!patched.ok) throw new ApiError(502, "engine_permission_sync_failed", "Work chat rules could not be applied");
    }
    const value = workChat ? { ...buildOmniRushV2Instructions(false), operatingInstructions: WORK_PROMPT } : buildOmniRushV2Instructions(false);
    const instructionUrl = new URL(target);
    instructionUrl.pathname = `/api/experimental/session/${encodeURIComponent(sessionId)}/instructions/entries/${OMNIRUSH_V2_INSTRUCTION_KEY}`;
    const synced = await loopbackFetch(instructionUrl.toString(), {
      method: "PUT", headers: internalHeaders, body: JSON.stringify({ value }), signal: AbortSignal.timeout(15_000),
    });
    if (!synced.ok) throw new ApiError(502, "engine_instruction_sync_failed", "OmniRush.ai instructions could not be updated");
  }

  const requestBody = method === "GET" || method === "HEAD"
    ? undefined
    : await input.request.arrayBuffer().then((buffer) => buffer.byteLength > 0 ? buffer : undefined);
  let body: string | ArrayBuffer | undefined = requestBody;
  if (method === "POST" && forwardedPath === "/api/session") {
    let sessionInput: unknown = {};
    if (requestBody) {
      try {
        sessionInput = JSON.parse(new TextDecoder().decode(requestBody));
      } catch {
        throw new ApiError(400, "invalid_body", "Expected a JSON object");
      }
    }
    if (!isRecord(sessionInput)) throw new ApiError(400, "invalid_body", "Expected a JSON object");
    // Unlike reads, v2 session creation binds its location from the body.
    body = JSON.stringify({ ...sessionInput, location: { directory: input.workspace.path } });
    headers.delete("content-length");
    headers.set("content-type", "application/json");
  }
  // A chat's model switch (POST /api/session/:id/model) to another provider is refused here, as its next request
  // would be: the engine session keeps the chat's own model, so its compaction and later turns still run.
  if (method === "POST" && sessionId && /^\/api\/session\/[^/]+\/model$/.test(routePath) && requestBody) {
    let pick: unknown = null;
    try { pick = JSON.parse(new TextDecoder().decode(requestBody)); } catch { pick = null; }
    const model = isRecord(pick) && isRecord(pick.model) ? pick.model : null;
    if (model && model.providerID === OMNIRUSH_PROVIDER_ID && typeof model.id === "string") {
      const refusal = await modelSwitchRefusalsByServer.get(input.config)?.(sessionId, model.id);
      if (refusal) return refusal;
    }
  }
  // Archiving (archived-chats.ts): the app's own flag, taken off the PATCH before the engine sees it.
  if (method === "PATCH" && sessionId && /^\/api\/session\/[^/]+$/.test(routePath) && requestBody) {
    let patch: unknown = null;
    try { patch = JSON.parse(new TextDecoder().decode(requestBody)); } catch { patch = null; }
    if (isRecord(patch) && Object.hasOwn(patch, "archived")) {
      const at = typeof patch.archived === "number" && patch.archived > 0 ? patch.archived : null;
      setArchived(runtimeStorageDir(input.config), sessionId, at);
      const { archived: _archived, ...rest } = patch;
      if (Object.keys(rest).length === 0) {
        const read = new URL(target);
        const answer = await loopbackFetch(read.toString(), { headers: new Headers({ authorization: headers.get("authorization") ?? "" }), signal: AbortSignal.timeout(10_000) });
        if (!answer.ok) return sanitizeProxyResponse(answer);
        const payload: unknown = await answer.json();
        const data = isRecord(payload) && "data" in payload ? payload.data : payload;
        return jsonResponse({ data: withArchived(runtimeStorageDir(input.config), data) });
      }
      body = JSON.stringify(rest);
      headers.delete("content-length");
      headers.set("content-type", "application/json");
    }
  }
  if (method === "POST" && /^\/api\/session\/[^/]+\/prompt$/.test(routePath) && requestBody) {
    // Office files the engine would drop go in as their text (engine-v2-attachments.ts).
    let promptInput: unknown = null;
    try { promptInput = JSON.parse(new TextDecoder().decode(requestBody)); } catch { promptInput = null; }
    if (isRecord(promptInput) && Array.isArray(promptInput.files) && promptInput.files.length > 0) {
      const converted = await convertOfficeAttachments(promptInput, input.workspace.path).catch(() => promptInput as Record<string, unknown>);
      if (converted !== promptInput) {
        body = JSON.stringify(converted);
        headers.delete("content-length");
        headers.set("content-type", "application/json");
      }
    }
  }
  // Collection, identical to the v1 mount: the session starts (or resumes) on
  // its first dispatch, the prompt milestone is snapshotted, the request and
  // response are traced and the turn is observed until it settles.
  const capture = collectible ? captureServicesByServer.get(input.config) : undefined;
  const uploadedSessionId = capture?.uploadEnabled && promptDispatch && sessionId ? sessionId : null;
  const deletedUploadedSessionId = capture?.uploadEnabled && method === "DELETE" && sessionId && /^\/api\/session\/[^/]+$/.test(routePath)
    ? sessionId
    : null;
  const engine = capture && uploadedSessionId ? engineTarget(input.connection.url, headers, target.search, "v2") : null;
  // The model the chat is pinned to: a chat on Claude, or one on another provider where Claude was picked (CLI: beforePromptDispatch).
  const pinRules = chatPinRules(uploadedSessionId ? chatPinsByServer.get(input.config)?.(uploadedSessionId) ?? null : null);
  // Automatic compaction (session-archive/auto-compact.ts), as on the 1.x engine (auto-compact-engine.ts: the 2.x calls).
  // A Claude chat is left out: Claude Code compacts its own conversation.
  const autoCompactor = engine && uploadedSessionId && pinRules.autoCompact ? autoCompactorsByServer.get(input.config) : undefined;
  if (autoCompactor && engine && uploadedSessionId) {
    const outcome = await autoCompactor.beforePrompt(uploadedSessionId, desktopAutoCompactEngine(engine, uploadedSessionId), body)
      .catch((error: unknown): AutoCompactOutcome => ({ action: "failed", reason: error instanceof Error ? error.message : String(error) }));
    if (outcome.action !== "none") createServerLogger(input.config).log("info", "Automatic compaction.", { "auto_compact.action": outcome.action, "auto_compact.reason": outcome.reason ?? "", "auto_compact.turns": outcome.turns ?? -1 });
  }
  // Steering (turn-steer.ts): the 2.x engine delivers a prompt to a running chat into its turn; such a
  // prompt opens no turn of its own (no start snapshot, no archive start) and is recorded as "turn.steer".
  const steerSentAt = Date.now();
  const turnKind = capture && uploadedSessionId && engine ? await createSteerTracker(engine).classify(uploadedSessionId) : null;
  const steer = Boolean(turnKind?.steer && uploadedSessionId && capture?.hasSession(uploadedSessionId));
  // A reopened chat's turns before this prompt: its turn numbers (uploads and box checkpoints) carry on from them.
  const turnsBefore = capture && uploadedSessionId && engine && !steer ? await turnsBeforeCapture(capture, uploadedSessionId, engine) : 0;
  // The Linux sandbox (box/): a prompt of a workspace whose box is on starts the box, and takes the turn's checkpoint when it is captured.
  // One pin per chat: a chat that runs in the box is not moved to this computer when its project's box is off.
  const pinnedBoxWhy = promptDispatch && sessionId ? await boxServiceFor(input.config).pinnedBoxUnavailable(sessionId, input.workspace) : null;
  if (pinnedBoxWhy) throw new ApiError(409, "chat_pinned_box", pinnedBoxMessage(pinnedBoxWhy));
  const boxInfo = promptDispatch && sessionId
    ? await boxServiceFor(input.config).beforePrompt(sessionId, input.workspace, { capture: Boolean(uploadedSessionId && engine) && !steer, turnsBefore, nativeModel: await promptsNativeOnlyModel(input.config, body), signal: input.request.signal })
    : null;
  if (promptDispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, sessionId);
  if (capture && uploadedSessionId && engine && !steer) {
    capture.boxSession(uploadedSessionId, boxInfo);
    capture.permissionMode(await capturePermissionMode(input.config));
    // A Claude chat's uploads name Claude Code from its first one, also after a restart (its grant comes later). CLI: beforePromptDispatch.
    // A chat pinned to another provider's model stays that chat (a Claude pick is refused there and a new chat offered).
    if (pinRules.identity === "not-claude") capture.markNotClaude(uploadedSessionId);
    else if (await engineChatProvider(engine, uploadedSessionId) === CLAUDE_PROVIDER_ID) capture.markClaude(uploadedSessionId, CLAUDE_CODE_VERSION);
    capture.startSession(uploadedSessionId, input.workspace.id, input.workspace.path, turnsBefore);
    // The turn before's background processes finish writing (at most 10 s after it ended), its project
    // delta is taken (at most 5 s more, only when it ended a moment ago), then capture v2's session-start
    // manifest and a new session's start scan are taken before the prompt reaches the engine (at most about 3 s).
    await capture.archiveStartGate(uploadedSessionId, input.workspace.path, lateWritesGate(input.workspace));
    if (input.migratedFromV1?.(uploadedSessionId)) capture.recordTrace(uploadedSessionId, "engine.migrated_from", { from: MIGRATED_FROM, exclude_from_delivery: true });
    const boxPlan = await boxServiceFor(input.config).planOutcome(uploadedSessionId, input.workspace).catch(() => null);
    if (boxPlan) capture.recordTrace(uploadedSessionId, "box.plan", boxPlan);
    capture.recordPrompt(uploadedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true, dispatchedAt: Date.now() });
    capture.captureSnapshot(uploadedSessionId, "prompt");
    capture.archiveSessionStarted(uploadedSessionId, input.workspace.path, engine);
  }
  if (promptDispatch && sessionId && !steer) void pinChatCapturePolicy(input.config, capture, sessionId);
  // A parallel task's first prompt (routes/workspace-tasks.ts): only task workspaces.
  if (input.workspace.task && promptDispatch && sessionId && !steer) {
    await noteTaskPrompt(input.workspace, sessionId, (id, type, data) => recordOpenSessionTrace(input.config, id, type, data));
  }
  if (promptDispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, sessionId);
  if (promptDispatch && sessionId && input.migratedFromV1?.(sessionId)) {
    const engineAt = (path: string, init: RequestInit = {}) => {
      const url = new URL(target.toString());
      url.pathname = path;
      return loopbackFetch(url.toString(), { ...init, headers: (() => { const h = new Headers(headers); h.delete("content-length"); for (const [k, v] of Object.entries((init.headers ?? {}) as Record<string, string>)) h.set(k, v); return h; })(), signal: AbortSignal.timeout(10_000) });
    };
    const from = await ensureMigratedChatAgent(engineAt, sessionId).catch(() => null);
    if (from) recordOpenSessionTrace(input.config, sessionId, "engine.agent_mapped", { from, to: "build" });
  }
  const response = await loopbackFetch(target.toString(), { method, headers, body, signal: input.recoverySignal });
  // The engine has the prompt: its session status says busy from now on.
  turnActivity?.promptDispatched();
  if (capture && uploadedSessionId && engine && steer) {
    if (response.ok) {
      // The turn goes on (followed as before); the steer's record is found in the background.
      capture.followSteer(uploadedSessionId, engine);
      const reason = turnKind?.reason ?? "working";
      const known = claimedSteerIds(uploadedSessionId);
      void createSteerTracker(engine).describe(uploadedSessionId, steerSentAt, { known }).then((found) => {
        if (found) claimSteerId(known, found.message_id);
        capture.steerTurn(uploadedSessionId, steerRecord(found, steerSentAt, reason));
      }).catch(() => capture.steerTurn(uploadedSessionId, steerRecord(null, steerSentAt, reason)));
    }
  } else if (capture && uploadedSessionId && engine) {
    capture.recordTrace(uploadedSessionId, "engine.response", { method, path: routePath, status: response.status });
    if (response.ok) capture.observeSession(uploadedSessionId, engine);
  }
  if (capture && deletedUploadedSessionId && response.ok) capture.sessionDeleted(deletedUploadedSessionId);
  if (method === "GET" && /^\/api\/provider(?:\/|$)/.test(decodedPath) && response.ok) {
    // Provider.Info includes request settings/headers, which may contain the
    // mirrored server-owned key. Clients only need public catalog metadata.
    const payload: unknown = await response.json();
    const raw = isRecord(payload) && "data" in payload ? payload.data : payload;
    const publicProvider = (value: unknown) => {
      if (!isRecord(value) || typeof value.id !== "string" || typeof value.name !== "string") {
        throw new ApiError(502, "invalid_engine_response", "Invalid provider metadata");
      }
      return { id: value.id, name: value.name };
    };
    const data = Array.isArray(raw) ? raw.map(publicProvider) : publicProvider(raw);
    return jsonResponse({ data });
  }
  if (method === "GET" && /^\/api\/model(?:\/|$)/.test(decodedPath) && response.ok) {
    // Only what selection needs (publicV2Model); request settings remain inside the engine.
    const payload: unknown = await response.json();
    const raw = isRecord(payload) && "data" in payload ? payload.data : payload;
    return jsonResponse({ data: Array.isArray(raw) ? raw.map(publicV2Model) : publicV2Model(raw) });
  }
  if (method === "GET" && /^\/api\/event\/*$/.test(decodedPath) && response.ok && response.body) {
    const expected = await realpath(input.workspace.path);
    const frames = new BoundedSseFrameBuffer();
    const encoder = new TextEncoder();
    const scopedBody = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
      start(controller) {
        controller.enqueue(encoder.encode(": connected\n\n"));
      },
      async transform(chunk, controller) {
        const parsed = frames.push(chunk);
        if (parsed.overflow) throw new Error("OmniRush v2 event frame exceeded the size limit");
        for (const frame of parsed.frames) {
          let scopedFrame = frame;
          let payload = parseSsePayload(frame);
          if (typeof payload === "string") {
            try { payload = JSON.parse(payload); } catch { continue; }
          }
          // v2 execution lifecycle events omit location. Resolve their session
          // through the daemon before forwarding; the event's session ID alone
          // is not proof of workspace ownership.
          if (isRecord(payload) && payload.location === undefined
            && typeof payload.type === "string"
            && /^session\.execution\.(started|succeeded|failed|interrupted)$/.test(payload.type)
            && isRecord(payload.data) && typeof payload.data.sessionID === "string"
            && payload.data.sessionID.startsWith("ses_")) {
            const sessionUrl = new URL(input.connection.url);
            sessionUrl.pathname = `/api/session/${encodeURIComponent(payload.data.sessionID)}`;
            const ownedSession: unknown = await loopbackFetch(sessionUrl.toString(), {
              headers: { authorization: `Basic ${Buffer.from(`opencode:${input.connection.password}`).toString("base64")}` },
              signal: AbortSignal.any([input.request.signal, AbortSignal.timeout(5_000)]),
            }).then(async (result) => result.ok ? result.json() : null).catch(() => null);
            const data = isRecord(ownedSession) && isRecord(ownedSession.data) ? ownedSession.data : ownedSession;
            const session = isRecord(data) && isRecord(data.info) ? data.info : data;
            if (isRecord(session) && isRecord(session.location)) {
              payload = { ...payload, location: session.location };
              scopedFrame = `data: ${JSON.stringify(payload)}`;
            }
          }
          const location = isRecord(payload) && isRecord(payload.location) ? payload.location : null;
          const directory = location && typeof location.directory === "string" ? location.directory : null;
          if (!directory || await realpath(directory).catch(() => null) !== expected) continue;
          controller.enqueue(encoder.encode(`${scopedFrame}\n\n`));
        }
      },
    }));
    const responseHeaders = new Headers(response.headers);
    responseHeaders.delete("content-length");
    responseHeaders.delete("content-encoding");
    return sanitizeProxyResponse(new Response(scopedBody, { status: response.status, headers: responseHeaders }));
  }
  if (method === "GET" && forwardedPath === "/api/session" && response.ok) {
    const payload: unknown = await response.json();
    const data = isRecord(payload) && "data" in payload ? payload.data : payload;
    const items = Array.isArray(data) ? data : isRecord(data) && Array.isArray(data.items) ? data.items : null;
    if (!items) throw new ApiError(502, "invalid_engine_response", "Invalid session list response");
    const expected = await realpath(input.workspace.path).catch(() => input.workspace.path);
    const flags = readArchivedChats(runtimeStorageDir(input.config));
    const scoped = (await Promise.all(items.map(async (item: unknown) => {
      const session = isRecord(item) && isRecord(item.info) ? item.info : item;
      const location = isRecord(session) && isRecord(session.location) ? session.location : null;
      const directory = location && typeof location.directory === "string" ? location.directory : null;
      if (!directory) return null;
      const actual = await realpath(directory).catch(() => directory);
      if (actual !== expected) return null;
      return isRecord(item) && isRecord(item.info)
        ? { ...item, info: withArchived(runtimeStorageDir(input.config), item.info, flags) }
        : withArchived(runtimeStorageDir(input.config), item, flags);
    }))).filter((item) => item !== null);
    const scopedData = isRecord(data) ? { ...data, items: scoped } : scoped;
    const scopedPayload = isRecord(payload) && "data" in payload ? { ...payload, data: scopedData } : scopedData;
    const responseHeaders = new Headers(response.headers);
    responseHeaders.delete("content-length");
    responseHeaders.delete("content-encoding");
    return sanitizeProxyResponse(new Response(JSON.stringify(scopedPayload), { status: response.status, headers: responseHeaders }));
  }
  if (method === "GET" && /^\/api\/session\/[^/]+$/.test(routePath) && response.ok) {
    const payload: unknown = await response.json();
    const data = isRecord(payload) && "data" in payload ? payload.data : payload;
    const shaped = isRecord(data) && isRecord(data.info) ? { ...data, info: withArchived(runtimeStorageDir(input.config), data.info) } : withArchived(runtimeStorageDir(input.config), data);
    return jsonResponse(isRecord(payload) && "data" in payload ? { ...payload, data: shaped } : shaped, response.status);
  }
  return sanitizeProxyResponse(response);
}

/** How many times a proxied request an engine rollover cut off is sent again. */
const ENGINE_ROLLOVER_RETRIES = 2;

/** How long a request that failed on an engine being replaced waits for the replacement to serve. */
function engineRolloverRetryWaitMs(): number {
  const configured = Number(process.env.OMNIRUSH_ENGINE_ROLLOVER_RETRY_WAIT_MS);
  return Number.isFinite(configured) && configured >= 0 ? configured : 30_000;
}

/**
 * Whether a proxied request that failed to reach its engine may be sent
 * again to the engine that took over. A request that starts a turn is sent
 * again only when the engine never received it (nothing listened on its
 * port); any other request may have been cut off mid-flight and is sent again.
 */
function engineRolloverRetryable(method: string, proxyPath: string, error: unknown): boolean {
  if (!isEngineConnectionFailure(error)) return false;
  const startsTurn = method === "POST"
    && /^\/session\/[^/]+\/(?:message|prompt|prompt_async|command|shell)$/.test(normalizeOpencodeProxyPath(proxyPath));
  return !startsTurn || engineNeverReceivedRequest(error);
}

function engineNeverReceivedRequest(error: unknown): boolean {
  let current: unknown = error;
  for (let depth = 0; depth < 6 && typeof current === "object" && current !== null; depth += 1) {
    const code = (current as { code?: unknown }).code;
    if (code === "ECONNREFUSED" || code === "UND_ERR_CONNECT_TIMEOUT") return true;
    current = (current as { cause?: unknown }).cause;
  }
  return false;
}

function opencodeUnreachableError(error: unknown, path: string): ApiError {
  return new ApiError(502, "opencode_unreachable", "OmniRush engine is unavailable", {
    path,
    cause: error instanceof Error ? error.message : String(error),
  });
}

function agentDiagnosticsTimeoutMs(): number {
  const configured = Number(process.env.OMNIRUSH_AGENT_DIAGNOSTICS_TIMEOUT_MS);
  return Number.isFinite(configured) && configured > 0 ? configured : 24_000;
}

function buildOpencodeDirectoryHeader(directory: string) {
  return /[^\x00-\x7F]/.test(directory) ? encodeURIComponent(directory) : directory;
}

export function scopeWorkspaceOpencodeRequest(
  headers: Headers,
  search: string,
  directory: string | null,
): { headers: Headers; search: string } {
  const scopedHeaders = new Headers(headers);
  scopedHeaders.delete("x-opencode-directory");

  const searchParams = new URLSearchParams(search);
  searchParams.delete("directory");

  if (directory) {
    scopedHeaders.set("x-opencode-directory", buildOpencodeDirectoryHeader(directory));
    searchParams.set("directory", directory);
  }

  const scopedSearch = searchParams.toString();
  return {
    headers: scopedHeaders,
    search: scopedSearch ? `?${scopedSearch}` : "",
  };
}

function createOpencodeDirectoryFetch(directory: string, fetchImpl: typeof fetch = globalThis.fetch): typeof fetch {
  return Object.assign(
    (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
      const request = input instanceof Request ? input : new Request(input, init);
      const headers = new Headers(init?.headers ?? request.headers);
      headers.set("x-opencode-directory", buildOpencodeDirectoryHeader(directory));
      return fetchImpl(new Request(request, { headers }));
    },
    { preconnect: fetchImpl.preconnect },
  );
}

type OpencodeClientResult<T, E> =
  | { data: T | undefined; error: undefined; response: Response }
  | { data: undefined; error: E; response?: Response };

export function createWorkspaceOpencodeClient(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  options?: { boundedDiagnosticsReads?: boolean; sessionId?: string },
) {
  const poolRoute = workspace.workspaceType === "remote" || !options?.sessionId
    ? null
    : enginePoolForConfig(config)?.routeRequest("GET", `/session/${encodeURIComponent(options.sessionId)}`) ?? null;
  const connection = poolRoute
    ? {
        baseUrl: poolRoute.target.baseUrl,
        authHeader: buildEngineAuthProbeHeader(poolRoute.target.username, poolRoute.target.password),
      }
    : resolveWorkspaceOpencodeConnection(config, workspace);
  const baseUrl = connection.baseUrl?.trim();
  if (!baseUrl) {
    throw new ApiError(400, "opencode_unconfigured", "OmniRush base URL is missing for this workspace", {
      workspaceId: workspace.id,
      workspaceType: workspace.workspaceType,
    });
  }
  const directory = resolveOpencodeDirectory(workspace);
  touchEngineWorkspaceInstance(config, workspace, baseUrl);
  const baseFetch = directory ? createOpencodeDirectoryFetch(directory) : globalThis.fetch;
  const clientFetch = options?.boundedDiagnosticsReads
    ? createAgentDiagnosticsEngineFetch(baseFetch)
    : directory ? baseFetch : undefined;

  return createOpencodeClient({
    baseUrl,
    ...(directory ? { directory } : {}),
    ...(clientFetch ? { fetch: clientFetch } : {}),
    ...(connection.authHeader ? { headers: { Authorization: connection.authHeader } } : {}),
  });
}

/** The engine's answer to an unexpected failure: `{ name: "UnknownError", data: { message, ref } }`. */
export function isEngineUnknownError(body: unknown): boolean {
  return Boolean(body) && typeof body === "object" && (body as { name?: unknown }).name === "UnknownError";
}

export function unwrapOpencodeResult<T, E>(result: OpencodeClientResult<T, E>, path: string): NonNullable<T> {
  if (result.data != null) {
    return result.data;
  }
  if (result.error === undefined) {
    throw new ApiError(502, "opencode_empty_response", "OmniRush returned an empty response", { path });
  }
  if (!result.response) {
    throw new ApiError(502, "opencode_unreachable", "OmniRush request failed before a response was received", {
      body: result.error,
      path,
    });
  }
  // The engine answers 400 `{ name: "Config…Error", data: { path, issues } }`
  // when a user-owned opencode.json(c) is rejected (since 1.18.32 a V2
  // `permissions` key does this for every instance-scoped route). That is
  // the user's file, not an engine outage: keep the engine's own message.
  const configError = parseOpencodeConfigErrorBody(result.error);
  if (configError) {
    throw new ApiError(422, "opencode_config_invalid", configError.message, {
      status: result.response.status,
      name: configError.name,
      file: configError.file,
      issues: configError.issues,
      path,
    });
  }
  throw new ApiError(502, "opencode_request_failed", "OmniRush request failed", {
    status: result.response.status,
    body: result.error,
    path,
  });
}

export async function proxyOpencodeRequest(input: {
  config: ServerConfig;
  request: Request;
  url: URL;
  workspace?: WorkspaceInfo;
  proxyPath?: string;
  recoverySignal?: AbortSignal;
}) {
  const workspace = input.workspace;
  const proxyPath = input.proxyPath ?? input.url.pathname;
  const method = input.request.method.toUpperCase();
  // The wrapper routes enforced the server read-only mode via ensureWritable;
  // native proxy writes must honor the same guard so a read-only server never
  // forwards mutations to the engine.
  if (method !== "GET" && method !== "HEAD") {
    ensureWritable(input.config);
  }
  assertEngineMcpRouteAllowed(input.config, method, normalizeOpencodeProxyPath(proxyPath));
  // Chats run on the 2.x engine (/opencode2): the 1.x engine starts no chat and no turn.
  if (workspace && workspace.workspaceType !== "remote" && startsV1Chat(method, proxyPath)
    && resolveInitialEngineV2PreviewState(process.env).chatRouting) {
    await input.request.arrayBuffer().catch(() => undefined);
    return jsonResponse({ error: "engine_v1_retired", message: "Chats now run on the new engine. Update OmniRush.ai or reopen the chat." }, 409);
  }
  // Farm runs (stock mode) only in the box, which keeps them offline: refused before any upload or model call.
  const farmRefused = workspace && isUploadPromptDispatch(method, proxyPath) ? await boxServiceFor(input.config).farmRefusal(workspace) : null;
  if (farmRefused) {
    await input.request.arrayBuffer().catch(() => undefined);
    return jsonResponse({ error: "farm_needs_sandbox", message: `omnirush: ${farmRefused.line}`, ...(farmRefused.retryAfter ? { retryable: true, retry_after: farmRefused.retryAfter } : {}) }, 409);
  }
  if (workspace && workspace.workspaceType !== "remote" && isUploadPromptDispatch(method, proxyPath)) {
    if (uploadDispatchRefused(input.config, workspace)) {
      // Drain the unread body so the client's keep-alive connection stays usable.
      await input.request.arrayBuffer().catch(() => undefined);
      return uploadAccountRequiredResponse();
    }
    if (uploadSessionId(proxyPath, method) === null) {
      // A dispatch is either refused or captured: a session identifier the
      // engine cannot decode would start a turn the session uploader cannot attribute.
      await input.request.arrayBuffer().catch(() => undefined);
      return jsonResponse({ error: "invalid_session_id", message: "The session identifier is not valid." }, 400);
    }
    const notWritable = await folderWriteRefusal(input.config, workspace, uploadSessionId(proxyPath, method) ?? "", input.request);
    if (notWritable) return notWritable;
    // A prompt right after launch waits (briefly) for the first model catalog
    // sync: the engine must know the account's models before the turn starts.
    await awaitOmniRushModelCatalogSettled(input.config);
  }
  const pool = workspace?.workspaceType === "remote" ? null : enginePoolForConfig(input.config);
  const route = pool?.routeRequest(method, decodeEngineRoutePath(proxyPath)) ?? null;
  const baseUrl = route?.target.baseUrl ??
    (workspace ? resolveWorkspaceOpencodeConnection(input.config, workspace).baseUrl?.trim() ?? "" : "");
  // The engine the request actually goes to (a draining one owns its sessions), and its fallback.
  for (const target of [baseUrl, route?.fallback?.baseUrl]) {
    if (!target) continue;
    const switching = pool !== null && !pool.isPrimaryUrl(target) && !engineStartedUnlocked(pool.primaryUrl() ?? "");
    assertEngineStartedWithinLock(target, method, proxyPath, currentProviderLockPolicy(), { switching });
  }
  if (!baseUrl) {
    throw new ApiError(400, "opencode_unconfigured", "OmniRush base URL is missing for this workspace");
  }

  let headers = new Headers(input.request.headers);
  headers.delete("authorization");
  headers.delete("x-omnirush-host-token");
  headers.delete(APP_SECRET_HEADER);
  headers.delete("x-omnirush-client-id");
  headers.delete("host");
  headers.delete("origin");

  const directory = workspace ? resolveOpencodeDirectory(workspace) : null;
  let search = input.url.search;
  if (workspace) {
    const scoped = scopeWorkspaceOpencodeRequest(headers, search, directory);
    headers = scoped.headers;
    search = scoped.search;
  }

  const auth = route
    ? buildEngineAuthProbeHeader(route.target.username, route.target.password)
    : workspace ? resolveWorkspaceOpencodeConnection(input.config, workspace).authHeader ?? null : null;
  if (auth) {
    headers.set("Authorization", auth);
  }

  if (workspace) touchEngineWorkspaceInstance(input.config, workspace, baseUrl);

  // Buffer the request body so it can be forwarded reliably across Node.js
  // stream boundaries (Readable.toWeb streams from the HTTP adapter aren't
  // always accepted directly by Node's global fetch as a body).
  let body = method === "GET" || method === "HEAD"
    ? undefined
    : await input.request.arrayBuffer().then((buf) => (buf.byteLength > 0 ? buf : undefined));
  // An undo keeps the files the person saved in the editor during or after the turns it takes back.
  const undoCall = workspace && workspace.workspaceType !== "remote" ? revertRequest(method, normalizeOpencodeProxyPath(proxyPath)) : null;
  if (undoCall?.kind === "revert" && workspace) {
    const undoSessionId = decodeEngineRouteParam(undoCall.sessionId) ?? undoCall.sessionId;
    const kept = await revertBodyWithEditorSaves({
      saves: editorSavesFor(input.config),
      // The editor's folder, as the engine names paths (no Windows `\\?\` prefix): keep paths are absolute.
      root: normalizeOpencodeDirectory(workspace.path),
      body,
      messageCreated: (messageId) => engineMessageCreated(baseUrl, auth, directory, undoSessionId, messageId),
    });
    if (kept !== body) {
      body = kept;
      headers.delete("content-length");
      headers.set("content-type", "application/json");
    }
  }
  const capture = workspace ? captureServicesByServer.get(input.config) : undefined;
  const uploadedSessionId = uploadSessionId(proxyPath, method);
  // The agent works from here (the prompt is on its way) until the engine runs no session.
  const turnActivity = workspace && workspace.workspaceType !== "remote" && uploadedSessionId && isUploadPromptDispatch(method, proxyPath)
    ? turnActivityFor(input.config)
    : null;
  turnActivity?.promptDispatched();
  const deletedUploadedSessionId = uploadDeletedSessionId(method, proxyPath);
  // A chat the engine does not have (a stale tab, a deleted chat) is not
  // started: its prompt is refused, and it would only leave an empty start
  // and end snapshot behind.
  const captured = Boolean(capture?.uploadEnabled && uploadedSessionId && workspace && workspace.workspaceType !== "remote"
    && (capture.hasSession(uploadedSessionId) || await engineHasSession(baseUrl, auth, directory, uploadedSessionId)));
  // Stop while the chat compacts: the compaction's leftovers are removed and the held prompts go out (auto-compact.ts).
  const stoppedSessionId = method === "POST" ? normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)\/abort$/)?.[1] ?? null : null;
  if (stoppedSessionId && autoCompactorsByServer.get(input.config)?.stopped(stoppedSessionId)) {
    createServerLogger(input.config).log("info", "Automatic compaction stopped by the person.", {});
  }
  // Automatic compaction (session-archive/auto-compact.ts): a chat with the server's number of prompts
  // since its last compaction is compacted before this prompt (never mid-turn, never a sub-agent's chat).
  const autoCompactor = workspace && workspace.workspaceType !== "remote" && uploadedSessionId && isUploadPromptDispatch(method, proxyPath)
    ? autoCompactorsByServer.get(input.config)
    : undefined;
  if (autoCompactor && uploadedSessionId) {
    const outcome = await autoCompactor.beforePrompt(uploadedSessionId, desktopAutoCompactEngine(engineTarget(baseUrl, headers, search), uploadedSessionId), body)
      .catch((error: unknown): AutoCompactOutcome => ({ action: "failed", reason: error instanceof Error ? error.message : String(error) }));
    if (outcome.action !== "none") createServerLogger(input.config).log("info", "Automatic compaction.", { "auto_compact.action": outcome.action, "auto_compact.reason": outcome.reason ?? "", "auto_compact.turns": outcome.turns ?? -1 });
  }
  // Steering (turn-steer.ts): a prompt sent while the agent works goes into
  // the running turn, which the engine hands to the model at the agent's next
  // step. Classified before anything is taken for it, with two small reads at
  // most; it goes through at once and opens no turn: no late-writes settle, no
  // box checkpoint, no start snapshot, no context turn, no archive start, and
  // the running turn is not cut. The turn records it as "turn.steer".
  const steerSentAt = Date.now();
  const turnKind = capture && captured && uploadedSessionId && workspace && isUploadPromptDispatch(method, proxyPath)
    ? await createSteerTracker(engineTarget(baseUrl, headers, search)).classify(uploadedSessionId)
    : null;
  const steer = Boolean(turnKind?.steer && uploadedSessionId && capture?.hasSession(uploadedSessionId));
  if (steer) createServerLogger(input.config).log("info", "Prompt steers the running turn.", { "turn.steer.reason": turnKind?.reason ?? "" });
  // The Linux sandbox (box/): a prompt of a workspace whose box is on starts the box, and takes the turn's checkpoint when it is captured.
  // A reopened chat's turns before this prompt: its turn numbers (uploads and box checkpoints) carry on from them.
  const turnsBefore = capture && captured && uploadedSessionId && workspace && !steer && isUploadPromptDispatch(method, proxyPath)
    ? await turnsBeforeCapture(capture, uploadedSessionId, engineTarget(baseUrl, headers, search))
    : 0;
  const pinnedBoxWhy = workspace && uploadedSessionId && isUploadPromptDispatch(method, proxyPath) ? await boxServiceFor(input.config).pinnedBoxUnavailable(uploadedSessionId, workspace) : null;
  if (pinnedBoxWhy) throw new ApiError(409, "chat_pinned_box", pinnedBoxMessage(pinnedBoxWhy));
  const boxInfo = workspace && uploadedSessionId && isUploadPromptDispatch(method, proxyPath)
    ? await boxServiceFor(input.config).beforePrompt(uploadedSessionId, workspace, { capture: captured && !steer, turnsBefore, nativeModel: await promptsNativeOnlyModel(input.config, body), signal: input.request.signal })
    : null;
  const dispatch = isUploadPromptDispatch(method, proxyPath) || isSessionCommandProxyRequest(method, proxyPath);
  // The chat whose turn beforePrompt counted for this request (undone when it is stopped before the engine).
  const boxSession = workspace && uploadedSessionId && isUploadPromptDispatch(method, proxyPath) ? uploadedSessionId : null;
  if (dispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, boxSession);
  if (capture && captured && uploadedSessionId && workspace && !steer) {
    const promptDispatch = isUploadPromptDispatch(method, proxyPath);
    if (promptDispatch) capture.boxSession(uploadedSessionId, boxInfo);
    if (promptDispatch) capture.permissionMode(await capturePermissionMode(input.config));
    // The chat a computer use call belongs to (computer-use/desktop.ts createChatTracker).
    if (promptDispatch) computerUseChats(input.config).mark(uploadedSessionId);
    capture.startSession(uploadedSessionId, workspace.id, workspace.path, turnsBefore);
    // The turn before's background processes finish writing (at most 10 s after it ended), its project
    // delta is taken (at most 5 s more, only when it ended a moment ago), then capture v2's session-start
    // manifest and a new session's start scan are taken before the prompt reaches the engine (at most about 3 s).
    if (promptDispatch) await capture.archiveStartGate(uploadedSessionId, workspace.path, lateWritesGate(workspace, pool?.snapshot().generations.map((generation) => generation.pid) ?? []));
    const boxPlan = isUploadPromptDispatch(method, proxyPath) ? await boxServiceFor(input.config).planOutcome(uploadedSessionId, workspace).catch(() => null) : null;
    if (boxPlan) capture.recordTrace(uploadedSessionId, "box.plan", boxPlan);
    capture.recordPrompt(uploadedSessionId, {
      method,
      path: normalizeOpencodeProxyPath(proxyPath),
      body,
      engine: "v1",
      root: workspace.path,
      attachments: promptDispatch,
      // Taken before the engine sees the prompt: the session's previous turn ends here.
      ...(promptDispatch ? { dispatchedAt: Date.now() } : {}),
      // A turn started while the engine was not plainly idle says why.
      ...(turnKind && turnKind.reason !== "idle" ? { turnStart: turnKind.reason } : {}),
    });
    if (promptDispatch) {
      capture.captureSnapshot(uploadedSessionId, "prompt");
      capture.archiveSessionStarted(uploadedSessionId, workspace.path, engineTarget(baseUrl, headers, search));
    }
  }
  if (workspace && uploadedSessionId && !steer && isUploadPromptDispatch(method, proxyPath)) void pinChatCapturePolicy(input.config, capture, uploadedSessionId);
  // A parallel task's first prompt (routes/workspace-tasks.ts): only task workspaces.
  if (workspace?.task && uploadedSessionId && !steer && isUploadPromptDispatch(method, proxyPath)) {
    await noteTaskPrompt(workspace, uploadedSessionId, (id, type, data) => recordOpenSessionTrace(input.config, id, type, data));
  }
  // A review or its fixes (command-events.ts), typed or from a button: an additive event of the chat's
  // trace, recorded once the engine answers the command with a 2xx.
  const reviewEvent = capture && captured && uploadedSessionId && isSessionCommandProxyRequest(method, proxyPath)
    ? commandEvent(body)
    : null;
  // Undo of the last turn and its redo (command-events.ts) of a chat the uploader tracks: the revert
  // point before it is read first; the engine's answer says what happened to each file.
  const revertCall = capture?.uploadEnabled ? undoCall : null;
  const revertSessionId = revertCall ? decodeEngineRouteParam(revertCall.sessionId) : null;
  const revertTracked = Boolean(revertSessionId && capture?.hasSession(revertSessionId));
  const revertBefore = revertTracked && revertSessionId ? await engineRevertPoint(baseUrl, auth, directory, revertSessionId) : null;
  // The engine took a steer: its turn goes on (followed as before), and the steer's record is found in the background.
  const steered = (service: CaptureService, sessionId: string, target: EngineTarget) => {
    service.followSteer(sessionId, target);
    const reason = turnKind?.reason ?? "working";
    const known = claimedSteerIds(sessionId);
    void createSteerTracker(target).describe(sessionId, steerSentAt, { known }).then((found) => {
      if (found) claimSteerId(known, found.message_id);
      service.steerTurn(sessionId, steerRecord(found, steerSentAt, reason));
    }).catch(() => service.steerTurn(sessionId, steerRecord(null, steerSentAt, reason)));
  };
  if (pool && method === "GET" && isEngineEventPath(proxyPath)) {
    // An open engine event stream means this workspace is visible somewhere in
    // the UI; hold its instance so the idle reaper leaves it alone until the
    // stream's client goes away.
    const releaseStreamHold = workspace && workspace.workspaceType !== "remote" && directory
      ? engineInstanceReaperForConfig(input.config)?.holdStream({
          directory,
          workspaceId: workspace.id,
          engineBaseUrl: baseUrl,
        }) ?? null
      : null;
    if (releaseStreamHold) {
      if (input.request.signal.aborted) releaseStreamHold();
      else input.request.signal.addEventListener("abort", releaseStreamHold, { once: true });
    }
    try {
      const response = await proxyEngineEventStreams({
        pool,
        connections: pool.connections(),
        proxyPath,
        search,
        headers,
        clientSignal: input.request.signal,
      });
      // A non-stream response completes immediately; holding it would leak
      // across every client retry.
      if (releaseStreamHold && (!response.ok || !response.body)) releaseStreamHold();
      return response;
    } catch (error) {
      releaseStreamHold?.();
      throw error;
    }
  }
  if (pool && method === "GET" && engineAggregateKind(proxyPath)) {
    return proxyEngineAggregateRead({
      pool,
      connections: pool.connections(),
      proxyPath,
      search,
      headers,
      kind: engineAggregateKind(proxyPath) ?? "pending",
    });
  }
  if (pool && workspace && workspace.workspaceType !== "remote" && method === "POST"
    && normalizeOpencodeProxyPath(proxyPath) === "/instance/dispose") {
    // A client-side dispose (provider refresh) would abort every run in this
    // folder. The pool applies it the same way without that: in place when
    // idle, through a standby while sessions are running.
    await reloadOpencodeEngine(input.config, workspace, undefined, { reason: "client_instance_dispose", manual: true });
    return jsonResponse(true);
  }
  // Checked again right before the engine: a send stopped while it was held never reaches it.
  if (dispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, boxSession);
  const targetUrl = buildOpencodeProxyUrl(baseUrl, proxyPath, search);
  // The engine that answered: a request an engine rollover cut off is sent again to the engine that took over.
  let served = { baseUrl, headers };
  // Managed OpenCode proxy traffic is loopback/engine I/O; keep streaming on Node fetch.
  if (isSessionCommandProxyRequest(method, proxyPath)) {
    const commandAdmission = commandAdmissionFromBody(body);
    if (commandAdmission) {
      const admissionTarget = workspace ? `workspace\0${workspace.id}` : `engine\0${baseUrl}`;
      const admission = admitSessionCommand(
        input.config,
        `${admissionTarget}\0${normalizeOpencodeProxyPath(proxyPath)}`,
        commandAdmission,
      );
      if (admission === "duplicate") return jsonResponse({ ok: true, accepted: true });
      if (admission === "conflict") {
        return jsonResponse({
          code: "command_admission_conflict",
          message: "This command message ID was already admitted with different input",
        }, 409);
      }
    }
    const release = pool?.beginRequest(baseUrl, { method, proxyPath: decodeEngineRoutePath(proxyPath) });
    void loopbackFetch(targetUrl, {
      method,
      headers,
      body,
    }).finally(() => release?.()).then((response) => {
      enginePoolForConfig(input.config)?.reportRequestSuccess(baseUrl);
      if (reviewEvent && response.ok && capture && uploadedSessionId && capture.hasSession(uploadedSessionId)) {
        capture.recordCommand(uploadedSessionId, reviewEvent.type, reviewEvent.data);
      }
      if (capture?.uploadEnabled && uploadedSessionId && steer) {
        if (response.ok) steered(capture, uploadedSessionId, engineTarget(baseUrl, headers, search));
      } else if (capture?.uploadEnabled && uploadedSessionId) {
        capture.recordTrace(uploadedSessionId, "engine.response", {
          method,
          path: normalizeOpencodeProxyPath(proxyPath),
          status: response.status,
        });
        if (workspace && response.ok) capture.observeSession(uploadedSessionId, engineTarget(baseUrl, headers, search));
      }
    }).catch((error: unknown) => {
      if (workspace) enginePoolForConfig(input.config)?.reportRequestFailure(baseUrl, error, workspace);
      if (capture?.uploadEnabled && uploadedSessionId) {
        capture.recordTrace(uploadedSessionId, "engine.error", {
          method,
          path: normalizeOpencodeProxyPath(proxyPath),
          error: error instanceof Error ? error.message : "unknown",
        });
      }
      // Command failures are surfaced through the OpenCode event stream.
    });
    return jsonResponse({ ok: true, accepted: true });
  }
  const forward = async () => {
    let response: Response;
    for (let attempt = 0; ; attempt += 1) {
      const release = pool?.beginRequest(served.baseUrl, { method, proxyPath: decodeEngineRoutePath(proxyPath) });
      try {
        response = attempt === 0
          ? await loopbackFetch(targetUrl, { method, headers, body, signal: input.recoverySignal })
          : await loopbackFetch(buildOpencodeProxyUrl(served.baseUrl, proxyPath, search), { method, headers: served.headers, body, signal: input.recoverySignal });
        enginePoolForConfig(input.config)?.reportRequestSuccess(served.baseUrl);
        break;
      } catch (error) {
        if (workspace) enginePoolForConfig(input.config)?.reportRequestFailure(served.baseUrl, error, workspace);
        const reroute = pool && attempt < ENGINE_ROLLOVER_RETRIES && !input.request.signal.aborted && !input.recoverySignal?.aborted
          && engineRolloverRetryable(method, proxyPath, error)
          ? await pool.rerouteAfterFailure(method, decodeEngineRoutePath(proxyPath), served.baseUrl, engineRolloverRetryWaitMs())
          : null;
        if (!reroute) {
          if (isEngineConnectionFailure(error)) throw opencodeUnreachableError(error, proxyPath);
          throw error;
        }
        createServerLogger(input.config).log("info", "Engine request retried on the engine that took over.", {
          "engine.retry.path": normalizeOpencodeProxyPath(proxyPath),
          "engine.retry.attempt": attempt + 1,
          "engine.retry.cause": error instanceof Error ? error.message : String(error),
        });
        served = { baseUrl: reroute.target.baseUrl, headers: headersForEngineConnection(headers, reroute.target) };
      } finally {
        release?.();
      }
    }

    // A session read the engine fails with 500 is, in practice, a damaged row
    // in its session store (one row breaks the chat and the project's whole
    // list): set it aside while the engine runs and read once more.
    if (response.status === 500 && method === "GET" && /^\/(?:api\/)?session(?:\/|$)/.test(normalizeOpencodeProxyPath(proxyPath))) {
      const failure = await response.clone().json().catch(() => null);
      if (isEngineUnknownError(failure) && await repairEngineStoresAfterServerError() > 0) {
        await response.body?.cancel().catch(() => undefined);
        response = await loopbackFetch(buildOpencodeProxyUrl(served.baseUrl, proxyPath, search), { method, headers: served.headers, body, signal: input.recoverySignal });
      }
    }

    if (response.status === 404 && route?.fallback) {
      const fallbackHeaders = headersForEngineConnection(headers, route.fallback);
      let fallbackResponse: Response;
      try {
        fallbackResponse = await loopbackFetch(
          buildOpencodeProxyUrl(route.fallback.baseUrl, proxyPath, search),
          { method, headers: fallbackHeaders, body, signal: input.recoverySignal },
        );
      } catch (error) {
        if (workspace) enginePoolForConfig(input.config)?.reportRequestFailure(route.fallback.baseUrl, error, workspace);
        if (isEngineConnectionFailure(error)) throw opencodeUnreachableError(error, proxyPath);
        throw error;
      }
      return sanitizeProxyResponse(fallbackResponse);
    }

    return sanitizeProxyResponse(response);
  };

  const forwardAndUpload = async () => {
    const response = await forward();
    // The engine has the prompt: its session status says busy from now on.
    turnActivity?.promptDispatched();
    if (capture?.uploadEnabled && uploadedSessionId && steer) {
      if (workspace && response.ok) steered(capture, uploadedSessionId, engineTarget(served.baseUrl, served.headers, search));
    } else if (capture?.uploadEnabled && uploadedSessionId) {
      capture.recordTrace(uploadedSessionId, "engine.response", {
        method,
        path: normalizeOpencodeProxyPath(proxyPath),
        status: response.status,
      });
      if (workspace && response.ok) capture.observeSession(uploadedSessionId, engineTarget(served.baseUrl, served.headers, search));
    }
    if (capture?.uploadEnabled && deletedUploadedSessionId && response.ok) capture.sessionDeleted(deletedUploadedSessionId);
    if (capture && revertCall && revertTracked && revertSessionId && response.ok) {
      const service = capture;
      const kind = revertCall.kind;
      void response.clone().json().then((session: unknown) => {
        const event = revertEvent(kind, session, revertBefore);
        if (event) service.recordCommand(revertSessionId, event.type, event.data);
      }).catch(() => undefined);
    }
    return response;
  };

  if (deletedUploadedSessionId && workspace && workspace.workspaceType !== "remote") {
    await stopSessionTreeBeforeDelete(
      pool
        ? pool.connections().map((connection) => ({ baseUrl: connection.baseUrl, headers: headersForEngineConnection(headers, connection) }))
        : [{ baseUrl, headers }],
      deletedUploadedSessionId,
      directory,
    );
  }
  if (workspace && workspace.workspaceType !== "remote" && isPromptAsyncProxyRequest(method, proxyPath)) {
    return withEngineDirectoryFence(input.config, workspace, forwardAndUpload);
  }
  if (pool && workspace && workspace.workspaceType !== "remote" && isSessionListRequest(method, normalizeOpencodeProxyPath(proxyPath))) {
    return serveLocalSessionList(input.config, workspace, search, forwardAndUpload());
  }
  return forwardAndUpload();
}

const emptySessionDirectoriesByServer = new WeakMap<ServerConfig, EmptySessionDirectoryCache>();

/**
 * A local workspace's session list must not depend on its engine instance
 * finishing a cold boot, or on the stored project id and directory string
 * still matching the folder exactly. See session-list-fallback.ts.
 */
async function serveLocalSessionList(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  search: string,
  primary: Promise<Response>,
): Promise<Response> {
  const directory = resolveOpencodeDirectory(workspace) ?? workspace.path;
  const cacheKey = directoryMatchKey(directory);
  const cache = emptySessionDirectoriesByServer.get(config) ?? new EmptySessionDirectoryCache();
  emptySessionDirectoriesByServer.set(config, cache);
  const query = sessionListFallbackQuery(search);
  return serveSessionListWithFallback({
    primary,
    deadlineMs: sessionListFallbackDeadlineMs(),
    fallback: async (cause) => {
      if (cause === "empty" && cache.has(cacheKey)) return [];
      const engine = primaryManagedEngineConnection(config);
      if (!engine) throw new Error("The managed engine is unavailable for the session index");
      const canonical = await realpath(directory).catch(() => directory);
      const items = await listSessionsByDirectory({
        directories: [workspace.path, directory, canonical],
        query,
        fetchPage: async (params) => {
          const response = await loopbackFetch(`${engine.baseUrl.replace(/\/+$/, "")}/experimental/session?${params.toString()}`, {
            headers: { Authorization: buildEngineAuthProbeHeader(engine.username, engine.password) },
            signal: AbortSignal.timeout(10_000),
          });
          if (!response.ok) throw new Error(`OmniRush session index failed with status ${response.status}`);
          const payload: unknown = await response.json();
          if (!Array.isArray(payload)) throw new Error("OmniRush session index returned an unreadable page");
          return { items: payload, nextCursor: response.headers.get("x-next-cursor") };
        },
      });
      if (items.length === 0) cache.remember(cacheKey);
      else cache.forget(cacheKey);
      return items;
    },
    onFallback: ({ cause, count }) => {
      createServerLogger(config).log("warn", "Session list served from the engine session index.", {
        "workspace.id": workspace.id,
        "session_list.fallback_cause": cause,
        "session_list.count": count,
      });
    },
  });
}

function isEngineEventPath(proxyPath: string): boolean {
  const normalized = normalizeOpencodeProxyPath(proxyPath);
  return normalized === "/event" || normalized === "/global/event" || normalized === "/api/event";
}

function engineAggregateKind(proxyPath: string): "status" | "pending" | null {
  const normalized = normalizeOpencodeProxyPath(proxyPath);
  if (normalized === "/session/status") return "status";
  if (["/permission", "/question", "/api/permission/request", "/api/question/request"].includes(normalized)) {
    return "pending";
  }
  return null;
}

function headersForEngineConnection(headers: Headers, connection: EnginePoolConnection): Headers {
  const next = new Headers(headers);
  next.set("Authorization", buildEngineAuthProbeHeader(connection.username, connection.password));
  return next;
}

function pendingPayloadItems(payload: unknown): { key: string | null; items: unknown[] } {
  if (Array.isArray(payload)) return { key: null, items: payload };
  if (!isRecord(payload)) return { key: null, items: [] };
  for (const key of ["items", "permissions", "questions", "requests"]) {
    const value = payload[key];
    if (Array.isArray(value)) return { key, items: value };
  }
  return { key: null, items: [] };
}

function pendingItemIdentity(value: unknown): string {
  if (!isRecord(value)) return JSON.stringify(value) ?? String(value);
  for (const key of ["id", "requestID", "requestId", "permissionID", "questionID"]) {
    const candidate = value[key];
    if (typeof candidate === "string" && candidate) return candidate;
  }
  return JSON.stringify(value) ?? String(value);
}

async function proxyEngineAggregateRead(input: {
  pool: EnginePool;
  connections: EnginePoolConnection[];
  proxyPath: string;
  search: string;
  headers: Headers;
  kind: "status" | "pending";
}): Promise<Response> {
  const settled = await Promise.allSettled(input.connections.map(async (connection) => {
    const response = await loopbackFetch(buildOpencodeProxyUrl(connection.baseUrl, input.proxyPath, input.search), {
      method: "GET",
      headers: headersForEngineConnection(input.headers, connection),
      signal: AbortSignal.timeout(5_000),
    });
    const payload = response.ok ? await response.json().catch(() => null) : null;
    return { connection, response, payload };
  }));
  const results = settled.flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []);
  const primary = results.find((entry) => entry.connection.role === "primary");
  if (!primary) throw new ApiError(502, "opencode_unreachable", "No OmniRush engine is available");
  if (!primary.response.ok) return sanitizeProxyResponse(primary.response);

  if (input.kind === "status") {
    const merged: Record<string, unknown> = {};
    for (const result of results.filter((entry) => entry.connection.role === "primary")) {
      if (isRecord(result.payload)) Object.assign(merged, result.payload);
    }
    for (const result of results.filter((entry) => entry.connection.role === "draining")) {
      if (isRecord(result.payload)) Object.assign(merged, result.payload);
    }
    return jsonResponse(merged);
  }

  for (const result of results) {
    input.pool.observePendingRequests(result.connection.generationId, result.payload);
  }
  const seen = new Set<string>();
  const items: unknown[] = [];
  let containerKey: string | null = null;
  for (const result of results) {
    const pending = pendingPayloadItems(result.payload);
    containerKey ??= pending.key;
    for (const item of pending.items) {
      const identity = pendingItemIdentity(item);
      if (seen.has(identity)) continue;
      seen.add(identity);
      items.push(item);
    }
  }
  if (containerKey && isRecord(primary.payload)) {
    return jsonResponse({ ...primary.payload, [containerKey]: items });
  }
  return jsonResponse(items);
}

function parseSsePayload(frame: string): unknown {
  const data = frame
    .split(/\r?\n/)
    .filter((line) => line.startsWith("data:"))
    .map((line) => line.slice("data:".length).trimStart())
    .join("\n");
  if (!data) return null;
  try {
    return JSON.parse(data);
  } catch {
    return null;
  }
}

// What the merged event stream may hold unread for its client. A window that
// stops reading (frozen, suspended) otherwise keeps every engine event of a long
// turn in this process until it runs out of memory.
const ENGINE_EVENT_BACKLOG_BYTES = 64 * 1024 * 1024;

function mergedEventBody(input: {
  pool: EnginePool;
  streams: Array<{ connection: EnginePoolConnection; body: ReadableStream<Uint8Array> }>;
  lease: EngineEventProxyLease;
}): ReadableStream<Uint8Array> {
  const encoder = new TextEncoder();
  const readers = input.streams.map((entry) => ({ connection: entry.connection, reader: entry.body.getReader() }));
  let cancelled = false;
  let pingTimer: ReturnType<typeof setInterval> | null = null;
  return new ReadableStream<Uint8Array>({
    start(controller) {
      let active = readers.length;
      let closed = false;
      const close = () => {
        if (closed) return;
        closed = true;
        if (pingTimer) clearInterval(pingTimer);
        input.lease.signal.removeEventListener("abort", abort);
        input.lease.release();
        controller.close();
      };
      const abort = () => {
        if (closed || cancelled) return;
        cancelled = true;
        for (const entry of readers) void entry.reader.cancel(input.lease.signal.reason).catch(() => undefined);
        close();
      };
      // The client stopped reading: the queue is dropped (error, not close, which
      // would keep it for the client) and the client reconnects by itself.
      const overflow = () => {
        if (closed || cancelled) return;
        cancelled = true;
        closed = true;
        if (pingTimer) clearInterval(pingTimer);
        input.lease.signal.removeEventListener("abort", abort);
        input.lease.release();
        for (const entry of readers) void entry.reader.cancel().catch(() => undefined);
        console.warn("[omnirush-server] engine event stream closed: its client stopped reading");
        controller.error(new Error("event stream backlog"));
      };
      const finish = () => {
        active -= 1;
        if (active > 0 || closed || cancelled) return;
        close();
      };
      const pump = async (entry: typeof readers[number]) => {
        const frameBuffer = new BoundedSseFrameBuffer();
        try {
          while (!cancelled) {
            const chunk = await entry.reader.read();
            if (chunk.done) break;
            const parsed = frameBuffer.push(chunk.value);
            for (const frame of parsed.frames) {
              if (input.pool.shouldForwardEvent(entry.connection.generationId, parseSsePayload(frame))) {
                controller.enqueue(encoder.encode(`${frame}\n\n`));
              }
            }
            if ((controller.desiredSize ?? 0) < -ENGINE_EVENT_BACKLOG_BYTES) {
              overflow();
              break;
            }
            if (parsed.overflow) {
              // A frame that never terminates would buffer without bound;
              // drop this connection and let the client reconnect.
              await entry.reader.cancel(new Error("SSE frame exceeded the size limit")).catch(() => undefined);
              break;
            }
          }
        } catch {
          // A generation flip intentionally aborts these readers. The client
          // reconnects and the next stream fans in every live generation.
        } finally {
          entry.reader.releaseLock();
          finish();
        }
      };
      for (const entry of readers) void pump(entry);
      // A data-bearing heartbeat, not an SSE comment: SSE parsers only yield
      // frames with data lines, so a `: ping` comment can keep middleboxes
      // happy but is invisible to the client's stream-staleness tracking. The
      // heartbeat lets a quiet-but-healthy stream attest liveness instead of
      // being aborted as stale, and makes a silent half-open socket
      // detectable within one stale window.
      pingTimer = setInterval(() => {
        if (!closed && !cancelled) controller.enqueue(encoder.encode(`data: {"type":"server.heartbeat"}\n\n`));
      }, engineEventStreamHeartbeatIntervalMs());
      pingTimer.unref?.();
      input.lease.signal.addEventListener("abort", abort, { once: true });
      if (input.lease.signal.aborted) abort();
    },
    async cancel(reason) {
      cancelled = true;
      if (pingTimer) clearInterval(pingTimer);
      input.lease.release();
      await Promise.all(readers.map((entry) => entry.reader.cancel(reason).catch(() => undefined)));
    },
  }, new ByteLengthQueuingStrategy({ highWaterMark: 0 }));
}

// Read lazily so tests can shrink the deadline at runtime. Matches the 5s
// bound proxyEngineAggregateRead puts on its per-connection fan-out.
function engineEventStreamEstablishTimeoutMs(): number {
  const parsed = Number(process.env.OMNIRUSH_ENGINE_EVENT_ESTABLISH_TIMEOUT_MS ?? "5000");
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 5_000;
}

// 15s keeps two heartbeats inside the renderer's 30s stale-stream window, so
// one lost beat never churns a healthy connection. Read lazily so tests can
// shrink the interval at runtime.
function engineEventStreamHeartbeatIntervalMs(): number {
  const parsed = Number(process.env.OMNIRUSH_ENGINE_EVENT_HEARTBEAT_MS ?? "15000");
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 15_000;
}

async function proxyEngineEventStreams(input: {
  pool: EnginePool;
  connections: EnginePoolConnection[];
  proxyPath: string;
  search: string;
  headers: Headers;
  clientSignal: AbortSignal;
}): Promise<Response> {
  const lease = input.pool.openEventProxy(input.clientSignal);
  const settled = await Promise.allSettled(input.connections.map(async (connection) => {
    // Bound establishment (headers) only: a connection that accepts the
    // socket but never answers must not stall the whole fan-out. The timer is
    // cleared as soon as the response resolves so the long-lived body stream
    // itself is never put on a deadline; lease aborts tear the body down
    // through the merged-stream reader cancellation instead.
    const establish = new AbortController();
    const onLeaseAbort = () => establish.abort(lease.signal.reason);
    lease.signal.addEventListener("abort", onLeaseAbort, { once: true });
    if (lease.signal.aborted) onLeaseAbort();
    const timer = setTimeout(
      () => establish.abort(new Error("OmniRush event stream establishment timed out")),
      engineEventStreamEstablishTimeoutMs(),
    );
    timer.unref?.();
    try {
      const response = await loopbackFetch(buildOpencodeProxyUrl(connection.baseUrl, input.proxyPath, input.search), {
        method: "GET",
        headers: headersForEngineConnection(input.headers, connection),
        signal: establish.signal,
      });
      return { connection, response };
    } finally {
      clearTimeout(timer);
      lease.signal.removeEventListener("abort", onLeaseAbort);
    }
  }));
  const successful = settled
    .filter((entry): entry is PromiseFulfilledResult<{ connection: EnginePoolConnection; response: Response }> =>
      entry.status === "fulfilled")
    .map((entry) => entry.value);
  // Established fetches are no longer tied to any abort signal, so bodies the
  // merged stream will not own must be cancelled here instead of leaking.
  const discard = (entries: Array<{ response: Response }>) => {
    for (const entry of entries) void entry.response.body?.cancel().catch(() => undefined);
  };
  const primary = successful.find((entry) => entry.connection.role === "primary");
  if (!primary) {
    lease.release();
    discard(successful);
    throw new ApiError(502, "opencode_unreachable", "The primary OmniRush event stream is unavailable");
  }
  if (!primary.response.ok || !primary.response.body) {
    lease.release();
    discard(successful.filter((entry) => entry !== primary));
    return sanitizeProxyResponse(primary.response);
  }
  const streams = successful
    .flatMap((entry) => entry.response.ok && entry.response.body
      ? [{ connection: entry.connection, body: entry.response.body }]
      : []);
  discard(successful.filter((entry) => entry !== primary && !(entry.response.ok && entry.response.body)));
  const headers = new Headers(primary.response.headers);
  headers.delete("content-length");
  headers.delete("content-encoding");
  headers.delete("transfer-encoding");
  headers.set("content-type", "text/event-stream");
  headers.set("cache-control", "no-cache");
  return new Response(mergedEventBody({ pool: input.pool, streams, lease }), {
    status: primary.response.status,
    statusText: primary.response.statusText,
    headers,
  });
}

/**
 * Strip hop-by-hop and transport-level headers that Bun's native fetch keeps
 * in the upstream response even after it has already decoded the body for us.
 * Without this the browser sees `content-encoding: gzip` on a plain-text
 * payload and bails out with ERR_CONTENT_DECODING_FAILED, breaking any UI
 * code that reaches through /opencode/* (including session.create).
 */
function sanitizeProxyResponse(response: Response): Response {
  const headers = new Headers(response.headers);
  headers.delete("content-encoding");
  headers.delete("transfer-encoding");
  headers.delete("content-length");
  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers,
  });
}

/** How often a running app reads the server's sandbox default again. */
const BOX_DEFAULT_REFRESH_MS = 10 * 60_000;

/**
 * The server's sandbox default (or its backends allowlist) changed: boxes on a
 * backend no longer allowed are planned again, the engine gets (or loses) the
 * box shell and plugin, and every workspace is planned. Chats that already ran
 * on this machine stay there (box/service.ts beforePrompt); new ones follow it.
 */
async function applyServerBoxDefault(config: ServerConfig, boxes: ReturnType<typeof boxServiceFor>): Promise<void> {
  await boxes.serverBackendsChanged();
  await applyBoxEngineConfig(config, "local_box_default");
  await boxes.ensureAll();
  void boxes.prefetch().catch(() => false);
}

/** Each server's 2.x engine config rewrite (engine-v2-preview.ts refreshProviders), for applyBoxEngineConfig. */
const engineV2Refreshers = new WeakMap<ServerConfig, () => Promise<void>>();

/**
 * The Linux sandbox's engine bits (box/service.ts engineBits) may have
 * changed: the engine config file is written again and, when it changed,
 * the managed engine rolls over to it (as for a best-practices change).
 */
async function applyBoxEngineConfig(config: ServerConfig, reason: string, options: { restart?: boolean } = {}): Promise<{ status: "unchanged" | "applied" | "deferred" | "failed" | "unmanaged" }> {
  // The 2.x engine (every chat) gets the same bits through its own config file, written again here.
  await engineV2Refreshers.get(config)?.().catch(() => undefined);
  try {
    const written = await writeOmniRushRuntimeConfigFile(config);
    // `restart`: the engine's environment changed too (the provider lock), so a new engine even when the file did not.
    if (!written.changed && !options.restart) return { status: "unchanged" };
    const pool = enginePoolForConfig(config);
    const workspaces = config.workspaces.filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim());
    const workspace = findManagedEngineWorkspace(workspaces) ?? workspaces[0];
    if (!pool && workspace && options.restart) {
      // No managed pool (an engine the app does not start): the lock still reaches it through the
      // rewritten config file and the dispose reload, on every workspace's engine.
      for (const entry of workspaces) await reloadOpencodeEngine(config, entry).catch(() => undefined);
      return { status: "applied" };
    }
    if (!pool || !workspace) return { status: "unmanaged" };
    // `restart`: the engine's environment changes too (the provider lock), so a new engine process, never
    // an in-place reload. If it cannot start, the old engine's prompts are refused (assertEngineStartedWithinLock).
    // Under the lock, an engine started without it is closed, its running turns aborted, rather than drained.
    const outcome = await pool.requestRollover({
      reason,
      workspace,
      manual: true,
      ...(options.restart ? { forceStandby: true } : {}),
      ...(options.restart && currentProviderLockPolicy().locked ? { retireDrainingIf: engineStartedUnlocked } : {}),
    });
    return { status: outcome.action === "coalesced" ? "deferred" : outcome.action === "skipped" ? "failed" : "applied" };
  } catch {
    return { status: "failed" };
  }
}

function jsonResponse(data: unknown, status = 200) {
  return new Response(JSON.stringify(data), {
    status,
    headers: { "Content-Type": "application/json" },
  });
}

function withCors(response: Response, request: Request, config: ServerConfig) {
  const origin = request.headers.get("origin");
  const allowedOrigins = config.corsOrigins;
  let allowOrigin: string | null = null;
  if (allowedOrigins.includes("*")) {
    allowOrigin = "*";
  } else if (origin && allowedOrigins.includes(origin)) {
    allowOrigin = origin;
  }

  if (!allowOrigin) return response;
  const headers = new Headers(response.headers);
  headers.set("Access-Control-Allow-Origin", allowOrigin);
  headers.set(
    "Access-Control-Allow-Headers",
    "Authorization, Content-Type, X-OmniRush-Host-Token, X-OmniRush-App-Secret, X-OmniRush-Client-Id, X-OpenCode-Directory, X-Opencode-Directory, x-opencode-directory",
  );
  headers.set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
  headers.set("Vary", "Origin");
  return new Response(response.body, { status: response.status, headers });
}

async function requireClient(request: Request, config: ServerConfig, tokens: TokenService): Promise<Actor> {
  const header = request.headers.get("authorization") ?? "";
  const match = header.match(/^Bearer\s+(.+)$/i);
  const token = match?.[1];
  if (!token) {
    throw new ApiError(401, "unauthorized", "Invalid bearer token");
  }
  const scope = await tokens.scopeForToken(token);
  if (!scope) {
    throw new ApiError(401, "unauthorized", "Invalid bearer token");
  }
  const clientId = request.headers.get("x-omnirush-client-id") ?? undefined;
  return { type: "remote", clientId, tokenHash: hashToken(token), scope };
}

function requireHostToken(request: Request, config: ServerConfig): Actor {
  const hostToken = request.headers.get("x-omnirush-host-token");
  if (hostToken && hostToken === config.hostToken) {
    return { type: "host", tokenHash: hashToken(hostToken), scope: "owner" };
  }
  throw new ApiError(401, "unauthorized", "Invalid host token");
}

async function requireHost(request: Request, config: ServerConfig, tokens: TokenService): Promise<Actor> {
  const hostToken = request.headers.get("x-omnirush-host-token");
  if (hostToken && hostToken === config.hostToken) {
    return { type: "host", tokenHash: hashToken(hostToken), scope: "owner" };
  }

  const header = request.headers.get("authorization") ?? "";
  const match = header.match(/^Bearer\s+(.+)$/i);
  const bearer = match?.[1];
  if (!bearer) {
    throw new ApiError(401, "unauthorized", "Invalid host token");
  }
  const scope = await tokens.scopeForToken(bearer);
  if (scope !== "owner") {
    throw new ApiError(401, "unauthorized", "Invalid host token");
  }
  const clientId = request.headers.get("x-omnirush-client-id") ?? undefined;
  return { type: "remote", clientId, tokenHash: hashToken(bearer), scope };
}

function buildCapabilities(config: ServerConfig): Capabilities {
  const writeEnabled = !config.readOnly;
  const schemaVersion = 1;
  const sandboxBackend = resolveSandboxBackend();
  const sandboxEnabled = resolveSandboxEnabled(sandboxBackend);
  const inboxEnabled = resolveInboxEnabled();
  const outboxEnabled = resolveOutboxEnabled();
  const maxBytes = resolveInboxMaxBytes();
  const browserProvider = resolveBrowserProvider();
  const opencodeConfigured = config.workspaces.some((workspace) => Boolean(workspace.baseUrl?.trim()));
  return {
    schemaVersion,
    serverVersion: SERVER_VERSION,
    opencodeVersion: OPENCODE_VERSION,
    providerSync: true,
    skills: { read: true, write: writeEnabled, source: "omnirush" },
    plugins: { read: true, write: writeEnabled },
    mcp: { read: true, write: writeEnabled && mcpAllowed(config) },
    commands: { read: true, write: writeEnabled },
    config: { read: true, write: writeEnabled },
    engine: { rollover: enginePoolForConfig(config) !== null },

    approvals: { mode: config.approval.mode, timeoutMs: config.approval.timeoutMs },
    sandbox: { enabled: sandboxEnabled, backend: sandboxBackend },
    tokens: { scoped: true, scopes: ["owner", "collaborator", "viewer"] },
    proxy: {
      opencode: opencodeConfigured,
    },
    toolProviders: {
      browser: browserProvider,
      files: {
        injection: writeEnabled && inboxEnabled,
        outbox: outboxEnabled,
        inboxPath: ".opencode/omnirush/inbox/",
        outboxPath: ".opencode/omnirush/outbox/",
        maxBytes,
      },
    },
  };
}

function resolveSandboxBackend(): Capabilities["sandbox"]["backend"] {
  const raw = (process.env.OMNIRUSH_SANDBOX_BACKEND ?? "").trim().toLowerCase();
  if (raw === "docker") return "docker";
  if (raw === "container") return "container";
  return "none";
}

function resolveSandboxEnabled(backend: Capabilities["sandbox"]["backend"]): boolean {
  const raw = (process.env.OMNIRUSH_SANDBOX_ENABLED ?? "").trim().toLowerCase();
  if (["1", "true", "yes", "on"].includes(raw)) return true;
  if (["0", "false", "no", "off"].includes(raw)) return false;
  return backend !== "none";
}

function resolveInboxEnabled(): boolean {
  const raw = (process.env.OMNIRUSH_INBOX_ENABLED ?? "").trim().toLowerCase();
  if (!raw) return true;
  return ["1", "true", "yes", "on"].includes(raw);
}

function resolveOutboxEnabled(): boolean {
  const raw = (process.env.OMNIRUSH_OUTBOX_ENABLED ?? "").trim().toLowerCase();
  if (!raw) return true;
  return ["1", "true", "yes", "on"].includes(raw);
}

function resolveInboxMaxBytes(): number {
  const raw = (process.env.OMNIRUSH_INBOX_MAX_BYTES ?? "").trim();
  const parsed = raw ? Number(raw) : NaN;
  if (Number.isFinite(parsed) && parsed > 0) {
    return Math.trunc(parsed);
  }
  // Generous default: the composer no longer caps attachment sizes, so large
  // uploads should be bounded here (memory: formData buffers the body) and by
  // downstream provider/tool limits rather than an arbitrary small cap.
  return 250_000_000;
}

// Dev-only log sink target. When OMNIRUSH_DEV_LOG_FILE is set to a path, the
// /dev/log endpoint accepts JSON payloads and appends them to that file so an
// operator can `tail -f` the file to see live browser activity. Returning null
// disables the endpoint entirely.
function resolveDevLogPath(): string | null {
  const raw = (process.env.OMNIRUSH_DEV_LOG_FILE ?? "").trim();
  return raw.length > 0 ? raw : null;
}

function resolveBrowserProvider(): Capabilities["toolProviders"]["browser"] {
  const raw = (process.env.OMNIRUSH_BROWSER_PROVIDER ?? "").trim().toLowerCase();
  if (raw === "sandbox-headless") {
    return { enabled: true, placement: "in-sandbox", mode: "headless" };
  }
  if (raw === "host-interactive") {
    return { enabled: true, placement: "host-machine", mode: "interactive" };
  }
  if (raw === "client-interactive") {
    return { enabled: true, placement: "client-machine", mode: "interactive" };
  }
  return { enabled: false, placement: "external", mode: "none" };
}

function emitReloadEvent(
  reloadEvents: ReloadEventStore,
  workspace: WorkspaceInfo,
  reason: ReloadReason,
  trigger?: ReloadTrigger,
) {
  reloadEvents.recordDebounced(workspace.id, reason, trigger);
}

function buildConfigTrigger(path: string): ReloadTrigger {
  const name = path.split(/[\\/]/).filter(Boolean).pop();
  return {
    type: "config",
    name: name || "opencode.json",
    action: "updated",
    path,
  };
}

export type AuthorizedFoldersResponse = {
  folders: string[];
  hiddenCount: number;
  workspaceRoot: string;
};

export type AuthorizedFoldersUpdateResponse = {
  folders: string[];
  hiddenCount: number;
  updatedAt: number;
};

type AuthorizedFoldersConfig = {
  folders: string[];
  hiddenEntries: Record<string, unknown>;
};

export function normalizeAuthorizedFolderPath(input: string | null | undefined): string {
  const trimmed = (input ?? "").trim();
  if (!trimmed) return "";
  if (trimmed === "/*") return "/";
  const withoutWildcard = trimmed.replace(/[\\/]\*+$/, "");
  const withoutVerbatim = /^\\\\\?\\UNC\\/i.test(withoutWildcard)
    ? `\\${withoutWildcard.slice(7)}`
    : /^\\\\\?\\[a-zA-Z]:[\\/]/.test(withoutWildcard)
      ? withoutWildcard.slice(4)
      : withoutWildcard;
  const unified = withoutVerbatim.replace(/\\/g, "/");
  let end = unified.length;
  while (end > 0 && unified[end - 1] === "/") end -= 1;
  const withoutTrailing = end === unified.length ? unified : unified.slice(0, end);
  return withoutTrailing || "/";
}

function externalDirectoryKeyToAuthorizedFolder(key: string, value: unknown): string | null {
  if (value !== "allow") return null;
  const trimmed = key.trim();
  if (!trimmed) return null;
  if (trimmed === "/*") return "/";
  if (!trimmed.endsWith("/*")) return null;
  return normalizeAuthorizedFolderPath(trimmed.slice(0, -2));
}

function authorizedFolderToExternalDirectoryKey(folder: string): string {
  return folder === "/" ? "/*" : `${folder}/*`;
}

function hasOwnKey(object: Record<string, unknown>, key: string): boolean {
  return Object.prototype.hasOwnProperty.call(object, key);
}

function readAuthorizedFoldersFromOpencodeConfig(
  opencodeConfig: Record<string, unknown>,
  workspaceRoot: string,
): AuthorizedFoldersConfig {
  const workspaceRootFolder = normalizeAuthorizedFolderPath(workspaceRoot);
  const permission = ensurePlainObject(opencodeConfig.permission);
  const externalDirectory = ensurePlainObject(permission.external_directory);
  const folders: string[] = [];
  const hiddenEntries: Record<string, unknown> = {};
  const seen = new Set<string>();

  for (const [key, value] of Object.entries(externalDirectory)) {
    const folder = externalDirectoryKeyToAuthorizedFolder(key, value);
    if (!folder) {
      hiddenEntries[key] = value;
      continue;
    }
    if (folder === workspaceRootFolder || seen.has(folder)) continue;
    seen.add(folder);
    folders.push(folder);
  }

  return { folders, hiddenEntries };
}

function parseAuthorizedFoldersPayload(input: unknown, workspaceRoot: string): string[] {
  if (!Array.isArray(input)) {
    throw new ApiError(400, "invalid_payload", "folders must be an array");
  }

  const workspaceRootFolder = normalizeAuthorizedFolderPath(workspaceRoot);
  const folders: string[] = [];
  const seen = new Set<string>();

  for (const item of input) {
    if (typeof item !== "string") {
      throw new ApiError(400, "invalid_payload", "folders must be an array of strings");
    }
    const folder = normalizeAuthorizedFolderPath(item);
    if (!folder || folder === workspaceRootFolder || seen.has(folder)) continue;
    seen.add(folder);
    folders.push(folder);
  }

  return folders;
}

function mergeAuthorizedFoldersIntoExternalDirectory(
  folders: string[],
  hiddenEntries: Record<string, unknown>,
): Record<string, unknown> | undefined {
  const next: Record<string, unknown> = { ...hiddenEntries };
  for (const folder of folders) {
    next[authorizedFolderToExternalDirectoryKey(folder)] = "allow";
  }
  return Object.keys(next).length ? next : undefined;
}

function buildAuthorizedFoldersResponse(workspace: WorkspaceInfo, config: AuthorizedFoldersConfig): AuthorizedFoldersResponse {
  return {
    folders: config.folders,
    hiddenCount: Object.keys(config.hiddenEntries).length,
    workspaceRoot: normalizeAuthorizedFolderPath(workspace.path),
  };
}

function serializeWorkspace(workspace: ServerConfig["workspaces"][number]) {
  const { opencodeUsername, opencodePassword, ...rest } = workspace;
  const opencodeDirectory = resolveOpencodeDirectory(workspace);
  const opencode =
    workspace.baseUrl || opencodeDirectory || opencodeUsername || opencodePassword
      ? {
          baseUrl: workspace.baseUrl,
          directory: opencodeDirectory ?? undefined,
          username: opencodeUsername,
          password: opencodePassword,
        }
      : undefined;
  return {
    ...rest,
    opencode,
  };
}

function createRoutes(
  config: ServerConfig,
  approvals: ApprovalService,
  tokens: TokenService,
  env: EnvService,
  onWorkspacesChanged: () => void,
  engineMcpServerState: EngineMcpServerState,
  logger: ServerLogger,
  cloudProviderSync: CloudProviderSync,
  engineV2Preview: EngineV2Preview,
  bestPracticesReloads: BestPracticesEngineReloads,
): Route[] {
  const routes: Route[] = [];
  // A rollover-capable pool can apply this immediately without disposing
  // the generation that owns live sessions. Legacy/external engines keep
  // the established busy deferral.
  const applyManagedProviderReload = async (workspace: WorkspaceInfo): Promise<"reloaded" | "deferred"> => {
    const reloadDeferred = await shouldDeferInPlaceEngineReload(config, workspace, engineHasActiveSessions);
    if (!reloadDeferred) await reloadOpencodeEngine(config, workspace, engineMcpServerState, { reason: "managed_provider_reload" });
    if (reloadDeferred) cloudProviderSync.markReloadPending();
    return reloadDeferred ? "deferred" : "reloaded";
  };
  registerCoreRoutes({
    routes,
    config,
    tokens,
    env,
    managedProviderAuthLogger: toManagedProviderAuthLogger(logger),
    serverVersion: SERVER_VERSION,
    opencodeVersion: OPENCODE_VERSION,
    jsonResponse,
    readJsonBody,
    readOptionalJsonBody,
    parseOptionalBoolean,
    ensureWritable,
    buildCapabilities,
    fetchRuntimeControl,
    resolveWorkspace,
    resolveOpencodeDirectory,
    createWorkspaceOpencodeClient,
    refreshRegistrationFromLiveStatus: refreshEngineMcpRegistrationFromLiveStatus,
    serializeWorkspace,
    resolveDevLogPath,
    onManagedProviderAuthChanged: async () => {
      await applyManagedProviderReload(resolveEngineRuntimeWorkspace(config));
    },
  });

  registerWorkspaceRoutes({
    routes,
    config,
    onWorkspacesChanged,
    jsonResponse,
    readJsonBody,
    readOptionalJsonBody,
    parseOptionalBoolean,
    ensureWritable,
    resolveWorkspace,
    serializeWorkspace,
    syncWorkspaceRuntimeMcp: (routeConfig, workspace) =>
      enqueueWorkspaceMcpRefreshSync({
        config: routeConfig,
        workspace,
        serverState: activeEngineMcpServerState(routeConfig),
        trigger: "workspace_activate",
      }),
    stopWorkspaceWork: stopWorkspaceEngineWork,
    // Opening a project starts its sandbox now (not at its first prompt).
    onWorkspaceOpened: (routeConfig, workspace) => boxServiceFor(routeConfig).opened(workspace),
  });

  registerWorkspaceTaskRoutes({
    routes,
    config,
    onWorkspacesChanged,
    jsonResponse,
    readJsonBody,
    ensureWritable,
    resolveWorkspace,
    serializeWorkspace,
    stopWorkspaceWork: stopWorkspaceEngineWork,
    engine: workspaceTaskEngine(config),
    recordTrace: (sessionId, type, data) => recordOpenSessionTrace(config, sessionId, type, data),
  });

  registerSessionGroupRoutes({
    routes,
    config,
    jsonResponse,
    readJsonBody,
    ensureWritable,
    requireClientScope,
    resolveWorkspace,
    resolveWorkspaceWithoutBootstrap,
  });

  registerCloudMcpRoutes({
    routes,
    config,
    jsonResponse,
    readJsonBody,
    ensureWritable,
    requireClientScope,
    resolveWorkspace,
    resolveOpencodeDirectory,
    createWorkspaceOpencodeClient,
    refreshRegistrationFromLiveStatus: refreshEngineMcpRegistrationFromLiveStatus,
    registerRuntimeMcp: (routeConfig, workspace, onlyNames, options) =>
      syncRuntimeMcpToOpencodeEngine(
        routeConfig,
        workspace,
        onlyNames,
        options,
        engineMcpServerState,
      ),
    serverMetadata: { serverVersion: SERVER_VERSION, expectedOpencodeVersion: OPENCODE_VERSION },
  });

  const localWorkflowService = registerLocalWorkflowRoutes({
    routes,
    config,
    jsonResponse,
    readJsonBody,
    ensureWritable,
    requireClientScope,
    resolveWorkspace,
    resolveWorkspaceWithoutBootstrap,
    createWorkspaceOpencodeClient,
    promptDispatcher: createLocalWorkflowPromptDispatcher(config),
  });
  localWorkflowServices.set(config, localWorkflowService);

  addRoute(routes, "POST", "/workspace/:id/diagnostics/agent-context", "client", async (ctx) => {
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspaceForInspection(config, ctx.params.id);
    if (workspace.workspaceType === "remote") {
      throw new ApiError(
        400,
        "agent_diagnostics_workspace_unsupported",
        "Agent diagnostics must run on the OmniRush.ai server that owns a local workspace",
      );
    }
    // Reserve before consuming untrusted bytes and hold the reservation through
    // report completion. The cooldown remains charged for invalid, oversized,
    // timed-out, and otherwise unsuccessful attempts.
    const releaseReservation = reserveAgentDiagnosticsRun(config, ctx.actor, workspace.id);
    try {
      const parsed = agentContextDiagnosticsRequestSchema.safeParse(await readAgentDiagnosticsJsonBody(ctx.request));
      if (!parsed.success) {
        throw new ApiError(400, "invalid_agent_diagnostics_request", "Agent diagnostics request is invalid");
      }
      const opencode = createWorkspaceOpencodeClient(config, workspace, { boundedDiagnosticsReads: true });
      const timeoutSignal = AbortSignal.timeout(agentDiagnosticsTimeoutMs());
      const diagnosticsSignal = AbortSignal.any([ctx.request.signal, timeoutSignal]);
      let response: Response;
      try {
        response = jsonResponse(await runAgentContextDiagnostics({
          config,
          workspace,
          request: parsed.data,
          inspectRegistration: (name, mcpConfig) =>
            inspectEngineMcpRegistrationInState(
              config,
              engineMcpServerState,
              workspace,
              name,
              mcpConfig,
            ),
          dependencies: {
            signal: diagnosticsSignal,
            inspectEffectiveEngine: async (signal) => {
              const [configResult, agentResult] = await Promise.all([
                opencode.config.get({}, { signal }),
                opencode.app.agents({}, { signal }),
              ]);
              return {
                config: unwrapOpencodeResult(configResult, "/config"),
                agents: unwrapOpencodeResult(agentResult, "/agent"),
              };
            },
          },
        }));
      } catch (error) {
        if (timeoutSignal.aborted && !ctx.request.signal.aborted) {
          throw new ApiError(504, "agent_diagnostics_timeout", "Agent diagnostics timed out");
        }
        throw error;
      }
      response.headers.set("Cache-Control", "no-store");
      return response;
    } finally {
      releaseReservation();
    }
  });

  addRoute(routes, "GET", "/workspace/:id/config", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const omnirush = await readOmniRushConfigForWorkspace(config, workspace);
    // Effective runtime view (ENGINE_GLOBAL ⊕ workspace row): providers,
    // plugins, and authorized folders live in the global row now, and the UI
    // must keep seeing them after migration.
    const opencode = mergeOpencodeConfigs(
      await readOpencodeConfig(workspace.path),
      await readEffectiveRuntimeOpencodeConfig(config, workspace.id),
    );
    const lastAudit = await readLastAudit(workspace.path, workspace.id);
    return jsonResponse({ opencode, omnirush, updatedAt: lastAudit?.timestamp ?? null });
  });

  addRoute(routes, "GET", "/workspace/:id/desktop-cloud-sync", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const omnirush = await readOmniRushConfigForWorkspace(config, workspace);
    return jsonResponse(readDesktopCloudSyncState(omnirush));
  });

  addRoute(routes, "POST", "/workspace/:id/desktop-cloud-sync", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const snapshot = normalizeResourceSnapshot(body.snapshot);
    if (!snapshot) {
      throw new ApiError(400, "invalid_payload", "snapshot is required");
    }

    const result = await enqueueDesktopCloudSync(async () => {
      const omnirush = await readOmniRushConfigForWorkspace(config, workspace);
      const installed = await readInstalledCloudPlugins(config, workspace.id);
      const cloudImports = {
        ...installed,
        providers: readWorkspaceCloudImports(omnirush).providers,
      };
      const next = syncDesktopCloudResources({ omnirush: { ...omnirush, cloudImports }, snapshot });
      // The plugin DB owns plugins/marketplaces, but provider import baselines live in
      // the workspace config. Writing the merged cloudImports back erased providers
      // and drove the provider-sync dispose/create loop.
      await writeOmniRushWorkspaceConfig(config, workspace.id, (current) => ({
        ...current,
        desktopCloudSync: next.state,
      }));
      await recordAudit(workspace.path, {
        id: shortId(),
        workspaceId: workspace.id,
        actor: ctx.actor ?? { type: "remote" },
        action: "desktop_cloud_sync.update",
        target: omnirushConfigPath(workspace.path),
        summary: "Updated desktop cloud sync state",
        timestamp: Date.now(),
      });
      return next;
    });
    return jsonResponse({ changes: result.changes, state: result.state });
  });

  addRoute(routes, "GET", "/workspace/:id/cloud-plugins", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const cloudImports = await readInstalledCloudPlugins(config, workspace.id);
    return jsonResponse({ marketplaces: cloudImports.marketplaces, plugins: cloudImports.plugins });
  });

  addRoute(routes, "POST", "/workspace/:id/cloud-plugins", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const resolved = readCloudPluginResolved(body.resolved);
    const marketplace = body.marketplace && typeof body.marketplace === "object" && !Array.isArray(body.marketplace)
      ? Object.fromEntries(Object.entries(body.marketplace))
      : null;
    const marketplaceId = typeof body.marketplaceId === "string" && body.marketplaceId.trim()
      ? body.marketplaceId.trim()
      : null;

    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "cloud_plugins.install",
      summary: `Install cloud plugin ${resolved.plugin.name}`,
      paths: [omnirushConfigPath(workspace.path), join(workspace.path, ".opencode")],
    });

    const result = await installCloudPlugin({
      serverConfig: config,
      workspaceId: workspace.id,
      workspaceRoot: workspace.path,
      marketplaceId,
      marketplace: marketplaceId
        ? {
            id: marketplaceId,
            name: typeof marketplace?.name === "string" ? marketplace.name : marketplaceId,
            updatedAt: typeof marketplace?.updatedAt === "string" ? marketplace.updatedAt : null,
          }
        : null,
      resolved,
    });
    const imported = result.item;

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "cloud_plugins.install",
      target: omnirushConfigPath(workspace.path),
      summary: `Installed cloud plugin ${resolved.plugin.name}`,
      timestamp: Date.now(),
    });

    for (const file of imported.files) {
      emitReloadEvent(ctx.reloadEvents, workspace, file.objectType === "mcp" ? "mcp" : file.objectType === "skill" ? "skills" : file.objectType === "agent" ? "agents" : file.objectType === "command" ? "commands" : "config", {
        type: file.objectType === "skill" || file.objectType === "agent" || file.objectType === "command" || file.objectType === "mcp" ? file.objectType : "config",
        name: file.title,
        action: "added",
      });
    }

    // Hot-register any bundled MCP servers with the running engine.
    await syncRuntimeMcpToOpencodeEngine(
      config,
      workspace,
      undefined,
      undefined,
      engineMcpServerState,
    ).catch(() => undefined);

    return jsonResponse({ item: imported, warnings: result.warnings });
  });

  // Claude Code plugin bundles (MCP + skills + commands + agents) installed
  // straight from a GitHub repo. `dryRun: true` returns the "Will install"
  // preview without writing anything; install reuses the cloud-plugin
  // machinery, so uninstall goes through DELETE /cloud-plugins/:pluginId.
  addRoute(routes, "POST", "/workspace/:id/claude-plugins", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const url = typeof body.url === "string" ? body.url.trim() : "";
    if (!url) throw new ApiError(400, "invalid_payload", "GitHub URL is required");
    const ref = typeof body.ref === "string" && body.ref.trim() ? body.ref.trim() : undefined;
    const dryRun = body.dryRun === true;

    const bundle = await resolveClaudePluginBundle({ url, ref });
    if (dryRun) {
      return jsonResponse({ preview: bundle.preview });
    }

    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "cloud_plugins.install",
      summary: `Install Claude plugin ${bundle.resolved.plugin.name} from ${bundle.preview.source.owner}/${bundle.preview.source.repo}`,
      paths: [omnirushConfigPath(workspace.path), join(workspace.path, ".opencode")],
    });

    const result = await installCloudPlugin({
      serverConfig: config,
      workspaceId: workspace.id,
      workspaceRoot: workspace.path,
      marketplaceId: null,
      resolved: bundle.resolved,
    });
    const imported = result.item;

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "cloud_plugins.install",
      target: omnirushConfigPath(workspace.path),
      summary: `Installed Claude plugin ${bundle.resolved.plugin.name} from ${url}`,
      timestamp: Date.now(),
    });

    for (const file of imported.files) {
      emitReloadEvent(ctx.reloadEvents, workspace, file.objectType === "mcp" ? "mcp" : file.objectType === "skill" ? "skills" : file.objectType === "agent" ? "agents" : file.objectType === "command" ? "commands" : "config", {
        type: file.objectType === "skill" || file.objectType === "agent" || file.objectType === "command" || file.objectType === "mcp" ? file.objectType : "config",
        name: file.title,
        action: "added",
      });
    }

    // Hot-register any bundled MCP servers with the running engine.
    await syncRuntimeMcpToOpencodeEngine(
      config,
      workspace,
      undefined,
      undefined,
      engineMcpServerState,
    ).catch(() => undefined);

    return jsonResponse({ item: imported, preview: bundle.preview, warnings: result.warnings });
  });

  addRoute(routes, "DELETE", "/workspace/:id/cloud-plugins/:pluginId", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const pluginId = ctx.params.pluginId ?? "";

    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "cloud_plugins.remove",
      summary: `Remove cloud plugin ${pluginId}`,
      paths: [omnirushConfigPath(workspace.path), join(workspace.path, ".opencode")],
    });

    const removed = await removeCloudPlugin({
      serverConfig: config,
      workspaceId: workspace.id,
      workspaceRoot: workspace.path,
      pluginId,
    });

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "cloud_plugins.remove",
      target: omnirushConfigPath(workspace.path),
      summary: `Removed cloud plugin ${removed.name}`,
      timestamp: Date.now(),
    });

    for (const file of removed.files) {
      emitReloadEvent(ctx.reloadEvents, workspace, file.objectType === "mcp" ? "mcp" : file.objectType === "skill" ? "skills" : file.objectType === "agent" ? "agents" : file.objectType === "command" ? "commands" : "config", {
        type: file.objectType === "skill" || file.objectType === "agent" || file.objectType === "command" || file.objectType === "mcp" ? file.objectType : "config",
        name: file.title,
        action: "removed",
      });
    }

    return jsonResponse({ item: removed, warnings: [] });
  });

  const pendingRunModeRefresh = new Set<string>();
  const runModeState = async (workspace: WorkspaceInfo): Promise<WorkspaceRunModeState & { path: string }> => {
    const state = await readWorkspaceRunMode(workspace.path);
    if (engineV2Preview.status().chatRouting) {
      return { ...state, supported: false, reason: "Workspace run modes are unavailable while OmniRush v2 chat routing is enabled." };
    }
    if (workspace.workspaceType === "remote" || resolve(resolveOpencodeDirectory(workspace) ?? workspace.path) !== resolve(workspace.path)) {
      return { ...state, supported: false, reason: "Workspace run modes require an engine using this local workspace directory." };
    }
    return state;
  };

  addRoute(routes, "GET", "/workspace/:id/permissions/mode", "client", async (ctx) => {
    const state = await runModeState(await resolveWorkspace(config, ctx.params.id));
    return jsonResponse({ ...state, refreshPending: pendingRunModeRefresh.has(state.path) });
  });

  addRoute(routes, "PUT", "/workspace/:id/permissions/mode", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const mode = body.mode;
    if (mode !== "default" && mode !== "approve" && mode !== "run-everything") {
      throw new ApiError(400, "invalid_payload", 'mode must be "default", "approve", or "run-everything"');
    }
    const initial = await runModeState(workspace);
    if (!initial.supported) throw new ApiError(409, "workspace_run_mode_unsupported", initial.reason);
    await requireWorkspaceRunModeIdle(config, workspace);
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "config.write",
      summary: mode === "run-everything"
        ? "Allow tools by default in this workspace, keeping narrower permission rules"
        : mode === "approve"
          ? "Ask before tools by default in this workspace, keeping narrower permission rules"
          : "Remove this workspace's permission catch-all, keeping narrower rules and inherited permissions",
      paths: [initial.path],
    });
    return withEngineDirectoryFence(config, workspace, async () => {
      // Approval can wait while another session starts or the runtime changes.
      const current = await runModeState(workspace);
      if (!current.supported) throw new ApiError(409, "workspace_run_mode_unsupported", current.reason);
      await requireWorkspaceRunModeIdle(config, workspace);
      const changed = await setWorkspaceRunMode(workspace.path, mode);
      if (changed) {
        pendingRunModeRefresh.add(current.path);
        emitReloadEvent(ctx.reloadEvents, workspace, "config", buildConfigTrigger(current.path));
      }
      await recordAudit(workspace.path, {
        id: shortId(),
        workspaceId: workspace.id,
        actor: ctx.actor ?? { type: "remote" },
        action: "config.write",
        target: current.path,
        summary: `Set workspace run mode to ${mode}`,
        timestamp: Date.now(),
      });
      let refresh: "reloaded" | "deferred" | "skipped" = "skipped";
      if (pendingRunModeRefresh.has(current.path)) {
        refresh = "deferred";
        try {
          if (engineV2Preview.status().chatRouting) throw new Error("OmniRush v2 chat routing is enabled");
          await requireWorkspaceRunModeIdle(config, workspace);
          // Directory-scoped disposal leaves other workspaces alone. The
          // detached MCP sync uses the same fence, so do not await it here.
          await reloadOpencodeEngineInPlace(config, workspace, engineMcpServerState, { awaitPostRefreshSync: false });
          const opencode = createWorkspaceOpencodeClient(config, workspace, { boundedDiagnosticsReads: true });
          const [configResult, agentResult] = await Promise.all([opencode.config.get({}), opencode.app.agents({})]);
          const snapshot = validateEffectiveEngineSnapshot({
            config: unwrapOpencodeResult(configResult, "/config"),
            agents: unwrapOpencodeResult(agentResult, "/agent"),
          });
          if (engineV2Preview.status().chatRouting || !snapshot || !selectGoverningAgent(snapshot.agents, snapshot.defaultAgent)) throw new Error("Engine reload could not be confirmed");
          pendingRunModeRefresh.delete(current.path);
          refresh = "reloaded";
        } catch {
          // The file is saved, not necessarily applied. Keep the event and
          // retry on a subsequent PUT even when the requested mode is unchanged.
        }
      }
      return jsonResponse({
        ...await runModeState(workspace),
        changed,
        refresh,
        refreshPending: refresh === "deferred",
        ...(refresh === "deferred" ? { reason: "Saved to the workspace config; engine refresh is pending. Wait for idle sessions and retry, or reload the workspace." } : {}),
      });
    });
  });

  addRoute(routes, "GET", "/workspace/:id/permissions/effective", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    // The engine's own evaluated ruleset decides; OmniRush.ai only names the
    // layer each winning rule came from.
    const opencode = createWorkspaceOpencodeClient(config, workspace, { boundedDiagnosticsReads: true });
    const [configResult, agentResult] = await Promise.all([opencode.config.get({}), opencode.app.agents({})]);
    const snapshot = validateEffectiveEngineSnapshot({
      config: unwrapOpencodeResult(configResult, "/config"),
      agents: unwrapOpencodeResult(agentResult, "/agent"),
    });
    if (!snapshot) {
      throw new ApiError(502, "opencode_invalid_response", "OmniRush returned an unreadable agent list", { workspaceId: workspace.id });
    }
    const agent = selectGoverningAgent(snapshot.agents, snapshot.defaultAgent);
    if (!agent) {
      throw new ApiError(502, "opencode_agent_missing", "OmniRush reported no agent for this workspace", { workspaceId: workspace.id });
    }
    const globalPath = resolveOpencodeConfigFilePath("global", workspace.path);
    const emptyConfig: Record<string, unknown> = {};
    const [workspaceConfig, globalConfig, injected] = await Promise.all([
      readOpencodeConfig(workspace.path),
      readJsoncFile(globalPath, emptyConfig, { allowInvalid: true }).then((result) => result.data),
      buildOmniRushRuntimeConfigObject(config),
    ]);
    return jsonResponse({
      agent: agent.name,
      rows: summarizeEffectivePermissions(agent.permission, {
        global: globalConfig.permission,
        omnirush: injected.permission,
        workspace: workspaceConfig.permission,
      }),
      files: { workspace: opencodeConfigPath(workspace.path), global: globalPath },
    });
  });

  addRoute(routes, "GET", "/workspace/:id/authorized-folders", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const opencode = mergeOpencodeConfigs(
      await readOpencodeConfig(workspace.path),
      // Global-first: authorized folders live in the ENGINE_GLOBAL row; the
      // effective read also surfaces legacy per-workspace entries until the
      // startup migration folds them in.
      await readEffectiveRuntimeOpencodeConfig(config, workspace.id),
    );
    const foldersConfig = readAuthorizedFoldersFromOpencodeConfig(opencode, workspace.path);
    return jsonResponse(buildAuthorizedFoldersResponse(workspace, foldersConfig));
  });

  addRoute(routes, "PUT", "/workspace/:id/authorized-folders", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const folders = parseAuthorizedFoldersPayload(body.folders, workspace.path);
    const configPath = omnirushConfigPath(workspace.path);

    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "config.authorized_folders.write",
      summary: "Update authorized folders",
      paths: [configPath],
    });

    const persistedOpencode = await readOpencodeConfig(workspace.path);
    const runtimeOpencode = await readEffectiveRuntimeOpencodeConfig(config, workspace.id);
    const existingOpencode = mergeOpencodeConfigs(persistedOpencode, runtimeOpencode);
    const existingFoldersConfig = readAuthorizedFoldersFromOpencodeConfig(existingOpencode, workspace.path);
    const nextExternalDirectory = mergeAuthorizedFoldersIntoExternalDirectory(
      folders,
      existingFoldersConfig.hiddenEntries,
    );

    // Authorized folders are engine-global: the injected engine config file is
    // rendered from the ENGINE_GLOBAL row only. Any legacy per-workspace
    // entries were folded into the effective read above, so clear them from
    // the workspace row or removals could never take effect.
    await writeGlobalRuntimeOpencodeConfig(config, (current) => ({
      ...current,
      permission: {
        ...(ensurePlainObject(current.permission)),
        external_directory: nextExternalDirectory ?? {},
      },
    }));
    await writeRuntimeOpencodeConfig(config, workspace.id, (current) => {
      const { permission, ...rest } = current;
      // Strip only the migrated external_directory; other permission keys stay.
      const { external_directory: _legacyExternalDirectory, ...permissionRest } = ensurePlainObject(permission);
      return {
        ...rest,
        ...(Object.keys(permissionRest).length ? { permission: permissionRest } : {}),
      };
    });

    const updatedAt = Date.now();
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "config.authorized_folders.write",
      target: configPath,
      summary: "Updated authorized folders",
      timestamp: updatedAt,
    });

    emitReloadEvent(ctx.reloadEvents, workspace, "config", buildConfigTrigger(configPath));

    const updatedFoldersConfig = readAuthorizedFoldersFromOpencodeConfig({
      permission: { external_directory: nextExternalDirectory ?? {} },
    }, workspace.path);

    const response: AuthorizedFoldersUpdateResponse = {
      folders: updatedFoldersConfig.folders,
      hiddenCount: Object.keys(updatedFoldersConfig.hiddenEntries).length,
      updatedAt,
    };
    return jsonResponse(response);
  });

  addRoute(routes, "POST", "/workspace/:id/runtime-config/disabled-providers", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const providers = parseDisabledProvidersPayload(body.providers);
    // Disabled providers are engine-global: the injected engine config file is
    // rendered from the ENGINE_GLOBAL row only.
    const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({
      ...current,
      disabled_providers: providers,
    }));

    if (result.changed) {
      emitReloadEvent(ctx.reloadEvents, workspace, "config", buildConfigTrigger(omnirushRuntimeConfigFilePath(config)));
    }

    return jsonResponse({
      ok: true,
      disabledProviders: runtimeDisabledProviderList(result.config),
    });
  });

  addRoute(routes, "GET", "/runtime-config/providers", "host-token", async () => {
    const runtime = await readGlobalRuntimeOpencodeConfig(config);
    return jsonResponse({ provider: runtimeProviderMap(runtime) });
  });

  // Engine approval mode: OMNIRUSH_APPROVALS in the server environment wins
  // over the persisted setting (source "environment"), so Settings shows the
  // switch disabled while the environment forces it.
  addRoute(routes, "GET", "/runtime-config/approvals", "client", async () =>
    jsonResponse(resolveApprovalMode(await readGlobalRuntimeOpencodeConfig(config))));

  addRoute(routes, "PUT", "/runtime-config/approvals", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const body = await readJsonBody(ctx.request);
    const mode = parseApprovalMode(body.mode);
    if (!mode) throw new ApiError(400, "invalid_payload", 'mode must be "careful", "guarded" (normal) or "full" (auto)');
    const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({ ...current, approvals: { mode } }));
    // The injected engine config file must carry the new rules before the
    // client's engine reload re-reads it.
    await writeOmniRushRuntimeConfigFile(config);
    return jsonResponse({ ok: true, changed: result.changed, ...resolveApprovalMode(result.config) });
  });

  // The Linux sandbox (box/): a workspace's choice, its status, and its reset.
  addRoute(routes, "GET", "/workspace/:id/box", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    return jsonResponse(await boxServiceFor(config).status(workspace, { fresh: ctx.url.searchParams.get("fresh") === "1", sessionId: ctx.url.searchParams.get("session") }));
  });

  addRoute(routes, "PUT", "/workspace/:id/box", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const mode = body.mode;
    const keys = Object.keys(body);
    // `mode`: the project's choice; `backend`: what runs boxes on this computer (auto, one backend id, native).
    if (!keys.length || keys.some((key) => key !== "mode" && key !== "backend")
      || ("mode" in body && mode !== "on" && mode !== "off" && mode !== null)
      || ("backend" in body && (typeof body.backend !== "string" || !normalizeBackend(body.backend)))) {
      throw new ApiError(400, "invalid_payload", "mode must be \"on\", \"off\" or null; backend must be \"auto\", a sandbox backend or \"native\"");
    }
    if (workspace.workspaceType !== "local") throw new ApiError(400, "box_unsupported", "The sandbox is for folders on this computer");
    const boxes = boxServiceFor(config);
    const before = JSON.stringify(await boxes.engineBits());
    // Required for new chats (local_box.required): "off" and the backend "native" are refused.
    let status: Awaited<ReturnType<typeof boxes.status>>;
    try {
      if (typeof body.backend === "string") await boxes.setBackend(body.backend);
      status = "mode" in body && (mode === "on" || mode === "off" || mode === null) ? await boxes.setMode(workspace, mode) : await boxes.status(workspace, { fresh: true });
    } catch (error) {
      if (error instanceof BoxRequiredError) throw new ApiError(409, error.code, error.message);
      throw error;
    }
    // The engine gets the box shell and plugin when the first workspace turns its box on (and loses them with the last).
    const engine = JSON.stringify(await boxes.engineBits()) === before ? { status: "unchanged" as const } : await applyBoxEngineConfig(config, "local_box");
    return jsonResponse({ ...status, engine });
  });

  // Buildathon projects (buildathon-repro.ts): the app sends the event's `repro` block and the
  // folders that are buildathon projects; their chats get the event's rules and, with `box: "on"`,
  // the sandbox. `{ "projects": [] }` clears it.
  addRoute(routes, "PUT", "/runtime-config/buildathon", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const body = await readJsonBody(ctx.request);
    if (!Array.isArray(body.projects) || Object.keys(body).some((key) => !["repro", "projects", "deadline_at"].includes(key))) {
      throw new ApiError(400, "invalid_payload", "projects must be a list of folders; repro and deadline_at are optional");
    }
    const boxes = boxServiceFor(config);
    const before = JSON.stringify(await boxes.engineBits());
    const state = reproStateFromBody(body);
    await writeReproState(state, buildathonProjectsFile(boxHome()));
    // New chats of a buildathon project start in its box: planned now, in the background (a missing image downloads).
    void boxes.ensureAll();
    const engine = JSON.stringify(await boxes.engineBits()) === before ? { status: "unchanged" as const } : await applyBoxEngineConfig(config, "local_box");
    return jsonResponse({ ok: true, projects: state.keys.length, box: state.box, engine });
  });

  // Try again now: a box that failed to start (or a project that went on without it) is planned again.
  addRoute(routes, "POST", "/workspace/:id/box/retry", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    if (workspace.workspaceType !== "local") throw new ApiError(400, "box_unsupported", "The sandbox is for folders on this computer");
    return jsonResponse(await boxServiceFor(config).retry(workspace));
  });

  // The sandbox's one-time setup when it is required (box/setup.ts): `linux_allow` (pkexec), `win_install`
  // (one UAC prompt), `win_restart` (refused while a chat runs), `win_update`, `decline` ("Not now": chats
  // run here meanwhile), `check` (look again). Answers the status after the step.
  addRoute(routes, "POST", "/workspace/:id/box/setup", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const action = body.action;
    if (Object.keys(body).some((key) => key !== "action") || !isBoxSetupAction(action)) {
      throw new ApiError(400, "invalid_payload", `action must be one of ${BOX_SETUP_ACTIONS.join(", ")}`);
    }
    if (workspace.workspaceType !== "local") throw new ApiError(400, "box_unsupported", "The sandbox is for folders on this computer");
    if (action === "win_restart" && (await collectBusyEngineSessions(config).catch(() => ({ sessions: [], unknown: 0 }))).sessions.length > 0) {
      throw new ApiError(409, "chat_running", "A chat is running: restart when it has finished.");
    }
    return jsonResponse(await boxServiceFor(config).setup(workspace, action));
  });

  addRoute(routes, "POST", "/workspace/:id/box/reset", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    return jsonResponse(await boxServiceFor(config).reset(workspace));
  });

  // Files used (session-archive/files-used.ts): what omnirush.ai says, for the app's one-time notice of its line.
  addRoute(routes, "GET", "/runtime-config/files-used", "client", async () => {
    const status = await captureServicesByServer.get(config)?.filesUsedStatus().catch(() => null);
    return jsonResponse(status ?? { active: null, available: null, consentText: null });
  });

  addRoute(routes, "GET", "/runtime-config/best-practices", "client", async () => {
    const runtime = await readGlobalRuntimeOpencodeConfig(config);
    return jsonResponse({ enabled: runtime.bestPractices !== false });
  });

  addRoute(routes, "PUT", "/runtime-config/best-practices", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const body = await readJsonBody(ctx.request);
    if (typeof body.enabled !== "boolean" || Object.keys(body).some((key) => key !== "enabled")) {
      throw new ApiError(400, "invalid_payload", "enabled must be a boolean and the only field");
    }
    const enabled = body.enabled;
    const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({ ...current, bestPractices: enabled }));
    // Persist first: a failed reload keeps the user's choice for the next start.
    // Return a separate application status so the UI never calls it applied early.
    try {
      const pool = enginePoolForConfig(config);
      await writeOmniRushRuntimeConfigFile(config);
      const workspaces = config.workspaces.filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim());
      const workspace = findManagedEngineWorkspace(workspaces) ?? workspaces[0];
      if (!workspace) {
        return jsonResponse({ ok: true, enabled, changed: result.changed, engine: { status: "unconfigured" } });
      }
      if (pool) {
        const outcome = await pool.requestRollover({ reason: "best_practices", workspace, manual: true });
        const status = outcome.action === "coalesced" ? "deferred"
          : outcome.action === "skipped" ? "failed" : "applied";
        return jsonResponse({ ok: true, enabled, changed: result.changed, engine: { status } });
      }
      // Attached engines cache one instance per folder. Apply idle folders and
      // safely retry every busy folder, without disposing an active reply.
      const status = await bestPracticesReloads.apply(workspaces);
      return jsonResponse({ ok: true, enabled, changed: result.changed, engine: { status } });
    } catch {
      return jsonResponse({ ok: true, enabled, changed: result.changed, engine: { status: "failed" } });
    }
  });

  // Agent assist (agent-assist-config.ts): self-check, project notes, diagnostics, compaction.
  addRoute(routes, "GET", "/runtime-config/agent-assist", "client", async () => {
    const runtime = await readGlobalRuntimeOpencodeConfig(config);
    return jsonResponse({ features: agentAssistFlags(runtime), forced: agentAssistForced() });
  });

  addRoute(routes, "PUT", "/runtime-config/agent-assist", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const body = await readJsonBody(ctx.request);
    const keys = Object.keys(body);
    if (!keys.length || keys.some((key) => !(AGENT_ASSIST_FEATURES as readonly string[]).includes(key) || typeof body[key] !== "boolean")) {
      throw new ApiError(400, "invalid_payload", `send one or more of ${AGENT_ASSIST_FEATURES.join(", ")} as booleans`);
    }
    const before = agentAssistFlags(await readGlobalRuntimeOpencodeConfig(config));
    const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => {
      const next: Record<string, boolean> = { ...(current.agentAssist ?? {}) };
      for (const key of keys) {
        // On is the default: only "off" is saved.
        if (body[key] === true) delete next[key];
        else next[key] = false;
      }
      const { agentAssist: _old, ...rest } = current;
      return Object.keys(next).length ? { ...rest, agentAssist: next } : rest;
    });
    const features = agentAssistFlags(await readGlobalRuntimeOpencodeConfig(config));
    const forced = agentAssistForced();
    try {
      // The plugin's switch file and the engine config; only the language servers need the engine to reload.
      await writeOmniRushRuntimeConfigFile(config);
      if (before.diagnostics === features.diagnostics) {
        return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status: "applied" } });
      }
      const workspaces = config.workspaces.filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim());
      const workspace = findManagedEngineWorkspace(workspaces) ?? workspaces[0];
      if (!workspace) return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status: "unconfigured" } });
      const pool = enginePoolForConfig(config);
      if (pool) {
        const outcome = await pool.requestRollover({ reason: "agent_assist", workspace, manual: true });
        const status = outcome.action === "coalesced" ? "deferred" : outcome.action === "skipped" ? "failed" : "applied";
        return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status } });
      }
      const status = await bestPracticesReloads.apply(workspaces);
      return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status } });
    } catch {
      return jsonResponse({ ok: true, features, forced, changed: result.changed, engine: { status: "failed" } });
    }
  });

  addRoute(routes, "PUT", "/den-session", "host-token", async (ctx) => {
    ensureWritable(config);
    const session = parseCloudProviderDenSession(await readJsonBody(ctx.request));
    if (!session) throw new ApiError(400, "invalid_payload", "baseUrl, token, and orgId are required");
    await managedDesktopPolicy(config).setSession(session);
    await cloudProviderSync.setSession(session);
    return new Response(null, { status: 204 });
  });

  addRoute(routes, "DELETE", "/den-session", "host-token", async () => {
    ensureWritable(config);
    await managedDesktopPolicy(config).clearSession();
    await cloudProviderSync.clearSession();
    return new Response(null, { status: 204 });
  });

  addRoute(routes, "POST", "/cloud-provider-sync/run", "host-token", async (ctx) => {
    ensureWritable(config);
    const body = await readJsonBody(ctx.request);
    if (body.reason !== undefined && typeof body.reason !== "string") {
      throw new ApiError(400, "invalid_payload", "reason must be a string");
    }
    return jsonResponse(await cloudProviderSync.run(typeof body.reason === "string" ? body.reason : undefined));
  });

  // Engine plugins (the browser tools) report what they saw for the owning
  // session. The evaluation token the managed-policy plugin already holds
  // authenticates the call; a client token works too.
  const sessionUploadEvents = async (ctx: RequestContext) => {
    const declared = Number(ctx.request.headers.get("content-length") ?? "0");
    if (Number.isFinite(declared) && declared > UPLOAD_EVENTS_MAX_REQUEST_BYTES) {
      throw new ApiError(413, "session_upload_events_too_large", "Session upload event payload is too large");
    }
    const raw = await ctx.request.text();
    if (raw.length > UPLOAD_EVENTS_MAX_REQUEST_BYTES) {
      throw new ApiError(413, "session_upload_events_too_large", "Session upload event payload is too large");
    }
    let body: unknown;
    try {
      body = JSON.parse(raw);
    } catch {
      throw new ApiError(400, "invalid_json", "Invalid JSON body");
    }
    if (!isRecord(body) || typeof body.sessionId !== "string" || !Array.isArray(body.events)) {
      throw new ApiError(400, "invalid_payload", "sessionId and events are required");
    }
    const ancestry = Array.isArray(body.ancestry)
      ? body.ancestry.filter((id): id is string => typeof id === "string" && id.length > 0).slice(0, 8)
      : [];
    const capture = captureServicesByServer.get(config);
    if (!capture?.uploadEnabled) return jsonResponse({ ok: true, recorded: 0 });
    // A subagent's tool call belongs to the root session the session uploader tracks.
    const target = [body.sessionId, ...ancestry].find((id) => capture.hasSession(id));
    if (!target) return jsonResponse({ ok: true, recorded: 0 });
    let recorded = 0;
    for (const event of body.events.slice(0, 32)) {
      if (!isRecord(event) || event.type !== "web.visit" || !isRecord(event.data) || typeof event.data.url !== "string") continue;
      const visit = {
        url: event.data.url,
        title: typeof event.data.title === "string" ? event.data.title : null,
        text: typeof event.data.text === "string" ? event.data.text : null,
      };
      if (capture.recordWebVisit(target, visit)) recorded += 1;
    }
    return jsonResponse({ ok: true, recorded });
  };
  addRoute(routes, "POST", SESSION_UPLOAD_EVENTS_ROUTE, "policy", sessionUploadEvents);
  // The route's pre-2.2.2 path, kept so an engine plugin built before the rename still reports.
  addRoute(routes, "POST", LEGACY_SESSION_UPLOAD_EVENTS_ROUTE, "policy", sessionUploadEvents);

  // The model provider lock (provider-lock.ts): what the app's model pickers and provider screens show.
  addRoute(routes, "GET", "/omnirush/provider-lock", "client", async () => {
    // How many plugins of the user's own the lock keeps off (the app tells the user once).
    let userPlugins = 0;
    const workspace = config.workspaces.find((entry) => entry.workspaceType !== "remote");
    if (workspace && currentProviderLockPolicy().locked) {
      userPlugins = await listPlugins(config, workspace.id, workspace.path, true).then((result) => result.items.length, () => 0);
    }
    return jsonResponse(providerLockStatus(currentProviderLockPolicy(), userPlugins));
  });

  // The user's web search switch (Settings > Preferences; web-search.ts). Off: no web search tool is offered
  // (the model's hosted one, or stock OpenCode's in stock mode). The server's switch wins: while it is off
  // (outside stock mode) the switch shows off and cannot be turned on.
  const webSearchState = () => {
    const stateDir = runtimeStorageDir(config);
    const user = userWebSearchEnabled(stateDir);
    const serverAllows = stockMode() || webSearchAllowed({ env: process.env, stateDir });
    return { enabled: user && serverAllows, user, serverAllows };
  };
  addRoute(routes, "GET", "/omnirush/web-search", "client", async () => jsonResponse(webSearchState()));
  addRoute(routes, "PUT", "/omnirush/web-search", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const body = await readJsonBody(ctx.request);
    if (typeof body.enabled !== "boolean") throw new ApiError(400, "invalid_payload", "enabled must be true or false");
    if (body.enabled && !webSearchState().serverAllows) throw new ApiError(409, "web_search_off_on_server", "Web search is turned off for your account.");
    try {
      writeUserWebSearch(runtimeStorageDir(config), body.enabled);
    } catch (error) {
      throw new ApiError(500, "settings_write_failed", `The web search setting could not be saved: ${errorCode(error)}`, { code: errorCode(error) });
    }
    // The engine config is written again: the next turn has (or lacks) the tool, no restart.
    await applyBoxEngineConfig(config, "web_search");
    return jsonResponse({ ok: true, ...webSearchState() });
  });

  // Sub-agent model and effort (omnirush-subagent-model.ts). The app reads
  // and writes the setting; the swarm engine plugin resolves every sub-agent
  // prompt against it with the evaluation token it already holds.
  addRoute(routes, "GET", "/omnirush/subagent-model", "client", async () => {
    const catalog = await readOmniRushModelCatalog(config);
    return jsonResponse({
      setting: await readSubagentModelSetting(config),
      signedIn: omnirushGatewayConfigured(config),
      models: catalog.map((model) => ({
        id: model.id,
        name: model.display_name,
        family: model.family,
        default: model.default,
        efforts: model.reasoning_levels,
        // Where the model may run: "native" (projects without the sandbox), "box" (sandbox projects).
        modes: modelModes(model),
        // The provider a chat may switch within (model-modes/strict-sessions.mjs); none: a new chat.
        ...(model.switch_group ? { switch_group: model.switch_group } : {}),
      })),
    });
  });

  addRoute(routes, "PUT", "/omnirush/subagent-model", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const body = await readJsonBody(ctx.request);
    if (body.model !== null && body.model !== undefined && typeof body.model !== "string") {
      throw new ApiError(400, "invalid_payload", "model must be a model id or null");
    }
    if (body.effort !== null && body.effort !== undefined && typeof body.effort !== "string") {
      throw new ApiError(400, "invalid_payload", "effort must be an effort or null");
    }
    const setting = sanitizeSubagentModelSetting({ model: body.model || null, effort: body.effort || null });
    if ((body.model && !setting.model) || (body.effort && !setting.effort)) {
      throw new ApiError(400, "invalid_payload", "unknown model id or effort");
    }
    let saved: SubagentModelSetting;
    try {
      saved = await writeSubagentModelSetting(config, setting);
    } catch (error) {
      // Never a silent success: the app shows this and keeps the previous setting.
      const code = errorCode(error);
      throw new ApiError(500, "settings_write_failed", `The sub-agent setting could not be saved: ${code}`, { code });
    }
    return jsonResponse({ ok: true, setting: saved });
  });

  // Whether the user's message names a model a task asked for, by id or by its catalog name
  // (the swarm plugin keeps the task's model only then).
  addRoute(routes, "POST", "/omnirush/subagent-model/named", "policy", async (ctx) => {
    const body = await readJsonBody(ctx.request);
    const model = typeof body.model === "string" ? body.model.trim() : "";
    const text = typeof body.text === "string" ? body.text.slice(0, 100_000) : "";
    if (!model) throw new ApiError(400, "invalid_payload", "model is required");
    const catalog = await readOmniRushModelCatalog(config);
    const models = [...catalog.map((entry) => ({ id: entry.id, name: entry.display_name })), { id: model }];
    return jsonResponse({ named: modelsNamedIn(text, models).has(model) });
  });

  addRoute(routes, "POST", "/omnirush/subagent-model/resolve", "policy", async (ctx) => {
    const body = await readJsonBody(ctx.request);
    const inherited = engineModelRef(body.inherited);
    if (!inherited) throw new ApiError(400, "invalid_payload", "inherited model is required");
    // Sub-agents run on their chat's model (one model per chat): only the effort applies.
    const setting = pinnedSubagentSetting(subagentSettingFor(await readSubagentModelSetting(config), engineModelRef(body.requested)));
    if (!setting) return jsonResponse({});
    const refusals = subagentModelRefusals(config);
    const resolution = resolveSubagentModel({
      setting,
      catalog: await readOmniRushModelCatalog(config),
      gateway: omnirushGatewayConfigured(config),
      inherited,
      main: engineModelRef(body.main),
      refused: (model) => refusals.isRefused(model),
    });
    if (resolution.fallback) {
      recordSubagentModelFallback(config, typeof body.rootSessionId === "string" ? body.rootSessionId : null, {
        kind: "selection",
        child_session_id: typeof body.sessionId === "string" ? body.sessionId : null,
        requested_model: resolution.fallback.requested,
        used_model: resolution.fallback.used,
        used_effort: resolution.variant ?? null,
        reason: resolution.fallback.reason,
        at: Date.now(),
      });
    }
    return jsonResponse(resolution);
  });

  addRoute(routes, "GET", "/omnirush/subagent-model/fallbacks", "policy", async (ctx) => {
    const session = ctx.url.searchParams.get("session") ?? "";
    const events = subagentGatewayFallbacks.get(config)?.get(session) ?? [];
    const catalog = await readOmniRushModelCatalog(config);
    const name = (id: unknown) => catalog.find((model) => model.id === id)?.display_name ?? id;
    return jsonResponse({
      fallbacks: events.map((event) => ({ ...event, requested_name: name(event.requested_model), used_name: name(event.used_model) })),
    });
  });

  // Voice dictation (omnirush-voice.ts): whether the account may use it, and
  // one speech segment at a time forwarded to omnirush.ai. Audio is never
  // stored, logged or captured; only the text the user sends is a prompt.
  addRoute(routes, "GET", "/omnirush/voice/status", "client", async (ctx) => {
    const voice = voiceServicesByServer.get(config);
    const workspaceId = ctx.url.searchParams.get("workspace")?.trim();
    const workspace = workspaceId ? config.workspaces.find((entry) => entry.id === workspaceId) : undefined;
    const [availability, project] = await Promise.all([
      voice ? voice.availability() : Promise.resolve({ available: false, reason: "voice_unavailable" }),
      workspace && workspace.workspaceType !== "remote" ? voiceProjectContext(workspace.path) : Promise.resolve({ repo: null, branch: null }),
    ]);
    return jsonResponse({ signedIn: voice?.signedIn ?? false, ...availability, ...project });
  });

  addRoute(routes, "POST", "/omnirush/voice/transcribe", "client", async (ctx) => {
    const voice = voiceServicesByServer.get(config);
    if (!voice) throw new ApiError(503, "voice_unavailable", "Voice input is not available.");
    return voice.transcribe(ctx.request);
  });

  // "Good session ★" for one chat (omnirush-good-session.ts): never an error
  // the bar would show; 404, 429, offline or signed out read "pending".
  addRoute(routes, "GET", "/omnirush/integrity/:sessionId", "client", async (ctx) => {
    const sessionId = ctx.params.sessionId ?? "";
    if (!GOOD_SESSION_ID_PATTERN.test(sessionId)) throw new ApiError(400, "invalid_session_id", "A valid session id is required");
    return jsonResponse(await readGoodSession(sessionIntegrityByServer.get(config) ?? null, sessionId));
  });

  addRoute(routes, "GET", "/managed-policy", "client", async () =>
    jsonResponse({ policy: await managedDesktopPolicy(config).current() }));
  addRoute(routes, "POST", "/managed-policy/evaluate", "policy", async (ctx) => {
    const body = await readJsonBody(ctx.request);
    const action = managedPolicyActionSchema.safeParse(body.action);
    if (!action.success || !isRecord(body.input)) throw new ApiError(400, "invalid_payload", "A supported policy action and input are required");
    await managedDesktopPolicy(config).assert(action.data, body.input);
    // The plugin applies the git workflow rules (destructive marker, commit
    // identity refusal) only in guarded mode.
    return jsonResponse({ allowed: true, approvalMode: resolveApprovalMode(await readGlobalRuntimeOpencodeConfig(config)).mode });
  });

  // Where session capture runs (capture-client.ts), for the app's banner while it is not running.
  // Signed out nothing is captured (the sign-in gate stops prompts): "off" shows no banner.
  addRoute(routes, "GET", "/omnirush/capture/status", "client", async () => {
    const capture = captureServicesByServer.get(config);
    if (!capture?.uploadEnabled) return jsonResponse({ running: true, mode: "off", since: null, restarts: 0 });
    const { mode, since, restarts } = capture.status();
    return jsonResponse({ running: mode === "worker" || mode === "local", mode, since: since.toISOString(), restarts });
  });

  // Before a sign-out: what is still queued for upload, and a short bounded send of it (the rest stays
  // queued for the account, sent after its next sign-in; never under another account).
  addRoute(routes, "GET", "/omnirush/capture/pending", "client", async () => {
    const pending = await captureServicesByServer.get(config)?.pendingUploads().catch(() => null);
    return jsonResponse(pending ?? { uploads: 0, archives: 0 });
  });

  addRoute(routes, "POST", "/omnirush/capture/flush", "client", async () => {
    const result = await captureServicesByServer.get(config)?.flushPending(SIGN_OUT_FLUSH_MS).catch(() => null);
    return jsonResponse(result ?? { before: 0, after: 0 });
  });

  addRoute(routes, "GET", "/cloud-provider-sync/status", "client", async () => {
    return jsonResponse(cloudProviderSync.status());
  });

  addRoute(routes, "GET", "/experimental/engine-v2-preview/status", "client", async () => {
    return jsonResponse(engineV2Preview.status());
  });

  addRoute(routes, "PUT", "/experimental/engine-v2-preview", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const body = await readJsonBody(ctx.request);
    if (!isRecord(body) || (body.enabled === undefined && body.chatRouting === undefined)) {
      throw new ApiError(400, "invalid_payload", "enabled or chatRouting must be provided");
    }
    if (body.enabled !== undefined && typeof body.enabled !== "boolean") {
      throw new ApiError(400, "invalid_payload", "enabled must be a boolean");
    }
    if (body.chatRouting !== undefined && typeof body.chatRouting !== "boolean") {
      throw new ApiError(400, "invalid_payload", "chatRouting must be a boolean");
    }
    if (body.enabled === false || body.chatRouting === false) {
      throw new ApiError(409, "engine_v2_required", "The 2.x engine runs every chat and cannot be turned off.");
    }
    let status = engineV2Preview.status();
    if (typeof body.enabled === "boolean") status = await engineV2Preview.setEnabled(body.enabled);
    if (typeof body.chatRouting === "boolean") status = await engineV2Preview.setChatRouting(body.chatRouting);
    return jsonResponse(status);
  });

  addRoute(routes, "PATCH", "/runtime-config/providers", "host-token", async (ctx) => {
    ensureWritable(config);
    const workspace = resolveEngineRuntimeWorkspace(config);
    const body = await readJsonBody(ctx.request);
    const providerPatch = parseRuntimeProviderPatchPayload(body);
    // The model provider lock (provider-lock.ts): only removals, or the allowed providers.
    for (const [providerId, value] of Object.entries(providerPatch)) if (value !== null) assertProviderWritable(providerId);
    const result = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({
      ...current,
      provider: mergeRuntimeProviderUpdate(current.provider, providerPatch),
    }));

    const fileResult = await writeOmniRushRuntimeConfigFile(config);
    // Auth must land before the reload so the replacement provider instance is
    // constructed with its credential. This also refreshes SDK clients after
    // a key rotation even when provider config itself did not change.
    const authResult = await syncManagedProviderAuth({
      config,
      env,
      logger: toManagedProviderAuthLogger(logger),
    });
    const shouldReload = result.changed
      || fileResult.changed
      || authResult.delivered.length > 0
      || authResult.removed.length > 0;
    const reloadDeferred = shouldReload
      && (await applyManagedProviderReload(workspace)) === "deferred";
    return jsonResponse({
      ok: true,
      changed: result.changed,
      provider: runtimeProviderMap(result.config),
      runtimeConfigPath: omnirushRuntimeConfigFilePath(config),
      reload: shouldReload ? (reloadDeferred ? "deferred" : "reloaded") : "skipped",
    });
  });

  addRoute(routes, "GET", "/workspace/:id/runtime-config", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const runtime = withoutMcpRuntimeConfig(await readRuntimeOpencodeConfig(config, workspace.id));
    const rawOpencode = await readRawOpencodeConfig(opencodeConfigPath(workspace.path));
    const persistedOpencode = await readOpencodeConfig(workspace.path);
    const globalOpencodePath = resolveOpencodeConfigFilePath("global", workspace.path);
    const rawGlobalOpencode = await readRawOpencodeConfig(globalOpencodePath);
    const emptyGlobalOpencode: Record<string, unknown> = {};
    const globalOpencode = (await readJsoncFile(globalOpencodePath, emptyGlobalOpencode, { allowInvalid: true })).data;
    // The injected file is rendered from the ENGINE_GLOBAL row only; the
    // workspace runtime row reaches the engine via the dynamic MCP push.
    const effectiveRuntime = await buildOmniRushRuntimeConfigObject(config);
    const managedFile = await readManagedRuntimeConfigDebug(config);

    return jsonResponse({
      runtime,
      runtimeKeys: runtimeConfigKeys(runtime),
      effectiveRuntime,
      ...managedFile,
      sources: {
        projectOpencode: {
          path: opencodeConfigPath(workspace.path),
          exists: rawOpencode.exists,
          keys: userOpencodeConfigKeys(persistedOpencode),
          config: persistedOpencode,
        },
        globalOpencode: {
          path: globalOpencodePath,
          exists: rawGlobalOpencode.exists,
          keys: userOpencodeConfigKeys(globalOpencode),
          config: globalOpencode,
        },
        runtimeDatabase: {
          keys: runtimeConfigKeys(runtime),
          config: runtime,
        },
        injected: {
          keys: runtimeConfigKeys(effectiveRuntime),
          config: effectiveRuntime,
        },
      },
      userOpencode: {
        path: opencodeConfigPath(workspace.path),
        exists: rawOpencode.exists,
        keys: userOpencodeConfigKeys(persistedOpencode),
      },
    });
  });

  // Every session of this workspace's folder, whatever engine project it is
  // filed under. The engine's own /session list only returns the folder's
  // current project (which changes when an agent turns the folder into a git
  // repo or adds a remote) and matches the folder byte for byte; either can
  // hide sessions that still exist. The sidebar merges this with that list.
  addRoute(routes, "GET", "/workspace/:id/sessions/by-folder", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const directory = resolveOpencodeDirectory(workspace);
    if (workspace.workspaceType === "remote" || !directory) {
      throw new ApiError(404, "not_found", "Sessions by folder are only listed for local workspaces");
    }
    const requested = Number(ctx.url.searchParams.get("limit"));
    const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 500) : 200;
    if (ctx.url.searchParams.get("engine") === "v2") {
      return jsonResponse(await listEngineV2FolderSessions(engineV2ByServer.get(config), directory, limit));
    }
    return jsonResponse(await listEngineSessionsInFolder(config, workspace, directory, limit));
  });

  addRoute(routes, "GET", "/workspace/:id/opencode-config", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const scope = normalizeOpencodeScope(ctx.url.searchParams.get("scope"));
    const configPath = resolveOpencodeConfigFilePath(scope, workspace.path);
    const result = await readRawOpencodeConfig(configPath);
    return jsonResponse({ path: configPath, exists: result.exists, content: result.content });
  });

  addRoute(routes, "POST", "/workspace/:id/opencode-config", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const scope = normalizeOpencodeScope(typeof body.scope === "string" ? body.scope : null);
    const content = typeof body.content === "string" ? body.content : null;
    if (content === null) {
      throw new ApiError(400, "invalid_payload", "content must be a string");
    }

    const configPath = resolveOpencodeConfigFilePath(scope, workspace.path);
    // The model provider lock (provider-lock.ts): a file that adds another provider or names its model is refused.
    assertConfigWithinLock(parseJsoncContent(content));
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: scope === "global" ? "config.global.write" : "config.write",
      summary: `Write ${scope} OmniRush config`,
      paths: [configPath],
    });

    const nextContent = content.endsWith("\n") ? content : `${content}\n`;
    const current = await readRawOpencodeConfig(configPath);
    const changed = !current.exists || current.content !== nextContent;
    if (changed) {
      await ensureDir(dirname(configPath));
      await writeFile(configPath, nextContent, "utf8");
    }

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: scope === "global" ? "config.global.write" : "config.write",
      target: configPath,
      summary: `Updated ${scope} OmniRush config`,
      timestamp: Date.now(),
    });

    if (scope === "project" && changed) {
      emitReloadEvent(ctx.reloadEvents, workspace, "config", buildConfigTrigger(configPath));
    }

    return jsonResponse({
      ok: true,
      status: 0,
      stdout: `Wrote ${configPath}`,
      stderr: "",
    });
  });

  addRoute(routes, "GET", "/workspace/:id/audit", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const limitParam = ctx.url.searchParams.get("limit");
    const parsed = limitParam ? Number(limitParam) : NaN;
    const limit = Number.isFinite(parsed) && parsed > 0 ? Math.min(parsed, 200) : 50;
    const items = await readAuditEntries(workspace.path, workspace.id, limit);
    return jsonResponse({ items });
  });

  addRoute(routes, "PATCH", "/workspace/:id/config", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const opencode = body.opencode as Record<string, unknown> | undefined;
    const omnirush = body.omnirush as Record<string, unknown> | undefined;
    let runtimeChanged = false;

    if (!opencode && !omnirush) {
      throw new ApiError(400, "invalid_payload", "opencode or omnirush updates required");
    }

    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "config.patch",
      summary: "Patch workspace config",
      paths: [opencode || omnirush ? omnirushConfigPath(workspace.path) : null].filter(Boolean) as string[],
    });

    if (opencode) {
      const configPath = omnirushConfigPath(workspace.path);
      const nextOpencode = ensurePlainObject(opencode);
      // MCP servers are added one at a time through POST /workspace/:id/mcp,
      // which checks each against the server's list.
      if (Object.prototype.hasOwnProperty.call(nextOpencode, "mcp")) {
        throw new ApiError(403, "mcp_config_patch", "Add MCP servers in Settings > MCP: each is checked against the supported list.");
      }
      const { permission, provider, ...topLevelUpdates } = nextOpencode;
      const logicalUpdates: Record<string, unknown> = { ...topLevelUpdates };

      // Per-provider merge: record values upsert, explicit `null` deletes
      // (mergeRuntimeProviderUpdate) — so clients can remove runtime-managed
      // providers (e.g. cloud imports) without read-modify-write races.
      // Providers are engine-global: the injected engine config file is
      // rendered from the ENGINE_GLOBAL row only, so a workspace-row write
      // would never reach the engine.
      const providerUpdate = isRecord(provider) ? provider : {};
      // The model provider lock (provider-lock.ts): no other provider and no model of one.
      for (const [providerId, value] of Object.entries(providerUpdate)) if (value !== null) assertProviderWritable(providerId);
      assertConfigWithinLock(topLevelUpdates);
      if (Object.keys(providerUpdate).length) await managedDesktopPolicy(config).assert("provider");
      if (Object.keys(providerUpdate).length) {
        const providerResult = await writeGlobalRuntimeOpencodeConfig(config, (current) => ({
          ...current,
          provider: mergeRuntimeProviderUpdate(current.provider, providerUpdate),
        }));
        runtimeChanged = providerResult.changed || runtimeChanged;
      }

      const permissionUpdate = ensurePlainObject(permission);
      if (Object.prototype.hasOwnProperty.call(permissionUpdate, "external_directory")) {
        // Authorized folders are engine-global for the same reason as providers.
        const nextExternalDirectory = permissionUpdate.external_directory;
        const permissionResult = await writeGlobalRuntimeOpencodeConfig(config, (current) => {
          const existingPermission = ensurePlainObject(current.permission);
          const existingPermissionKeys = Object.keys(existingPermission);
          const removePermissionParent =
            typeof nextExternalDirectory === "undefined" &&
              (existingPermissionKeys.length === 0 ||
              (existingPermissionKeys.length === 1 && Object.prototype.hasOwnProperty.call(existingPermission, "external_directory")));
          if (removePermissionParent) {
            const { permission: _removed, ...rest } = current;
            return rest;
          }
          return {
            ...current,
            permission: {
              ...existingPermission,
              external_directory: ensurePlainObject(nextExternalDirectory),
            },
          };
        });
        runtimeChanged = permissionResult.changed || runtimeChanged;
      }

      if (Object.keys(logicalUpdates).length) {
        const result = await writeRuntimeOpencodeConfig(config, workspace.id, (current) => ({
          ...current,
          ...logicalUpdates,
        }));
        runtimeChanged = result.changed || runtimeChanged;
      }
    }
    if (omnirush) {
      await writeOmniRushWorkspaceConfig(config, workspace.id, (current) => ({
        ...current,
        ...omnirush,
      }));
    }

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "config.patch",
      target: omnirushConfigPath(workspace.path),
      summary: "Patched workspace config",
      timestamp: Date.now(),
    });

    // A no-op provider patch (for example cloud sync reconciling an identical
    // block) must not force an engine reload; that caused a dispose/create loop.
    if (opencode && runtimeChanged) {
      emitReloadEvent(ctx.reloadEvents, workspace, "config", buildConfigTrigger(omnirushConfigPath(workspace.path)));
    }

    return jsonResponse({ updatedAt: Date.now() });
  });

  registerOperationRoutes({
    routes,
    config,
    jsonResponse,
    readJsonBody,
    requireClientScope,
    resolveWorkspace,
    reloadOpencodeEngine: (routeConfig, workspace) =>
      reloadOpencodeEngine(routeConfig, workspace, engineMcpServerState, { reason: "operation_route", manual: true }),
  });

  registerUiControlRoutes({ routes, jsonResponse, readJsonBody, requireClientScope });

  registerFileRoutes({
    routes,
    config,
    jsonResponse,
    readJsonBody,
    ensureWritable,
    requireApproval,
    requireClientScope,
    resolveWorkspace,
    resolveInboxEnabled,
    resolveOutboxEnabled,
    resolveInboxMaxBytes,
    scopeRank,
  });

  // Work mode (work/routes.ts): the switch, the Work workspace and the connectors.
  registerWorkRoutes({
    routes,
    config,
    workDir: () => workDir(runtimeStorageDir(config)),
    broker: () => workBrokersByServer.get(config) ?? null,
    jsonResponse,
    readJsonBody,
    addWorkspace: async (folderPath) => {
      const { workspace } = await addLocalWorkspace(config, { folderPath, name: "Work", preset: "work" });
      onWorkspacesChanged();
      return workspace;
    },
    applyEngine: () => applyComputerUseEngine(config, "work"),
    refreshMcp: () => {
      const workspace = findWorkWorkspace(config.workspaces);
      if (workspace) engineV2ByServer.get(config)?.refreshWorkspaceMcp(workspace.path);
    },
  });

  // Computer use (computer-use/routes.ts): for Electron main, which runs the host.
  registerComputerUseRoutes({
    routes,
    stateDir: () => runtimeStorageDir(config),
    jsonResponse,
    readJsonBody,
    approvalMode: () => capturePermissionMode(config),
    readCapabilities: async (maxAgeMs) => {
      const read = computerUseCapabilitiesByServer.get(config);
      if (!read) throw new Error("capabilities unavailable");
      return read(maxAgeMs);
    },
    applyEngine: () => applyComputerUseEngine(config),
    chats: computerUseChats(config),
    // The engine's running top-level chats, marked or not (null when any engine or session could not be
    // read: no chat is named then).
    runningSessions: async () => {
      const pool = enginePoolForConfig(config);
      if (!pool) return null;
      const directories = new Set(engineInstanceReaperForConfig(config)?.snapshot().map((instance) => instance.directory) ?? []);
      const busy = await pool.activeChats([...directories]);
      return busy.unknown > 0 ? null : busy.sessions;
    },
    recordTrace: (sessionId, type, data) => recordOpenSessionTrace(config, sessionId, type, data),
  });

  // The desktop editor. A save or a hunk review that names a chat the session
  // uploader is tracking adds a "user_edit" / "user_review" trace event to it;
  // nothing else in a chat's upload changes (editor-events.ts).
  // The editor's language features (editor-lsp.ts): the app's own language-server host.
  addRoute(routes, "POST", "/workspace/:id/editor/lsp/:op", "client", async (ctx) => {
    const op = ctx.params.op as LspOp;
    if (!LSP_OPS.includes(op)) throw new ApiError(404, "not_found", "Unknown language request");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    if (workspace.workspaceType === "remote") throw new ApiError(404, "not_found", "Language features run for local projects only");
    const input = await readJsonBody(ctx.request);
    const payload: LspPayload = {
      ...(typeof input.path === "string" ? { path: input.path } : {}),
      ...(typeof input.line === "number" ? { line: input.line } : {}),
      ...(typeof input.character === "number" ? { character: input.character } : {}),
      ...(typeof input.newName === "string" ? { newName: input.newName } : {}),
      ...(typeof input.text === "string" ? { text: input.text } : {}),
    };
    try {
      return jsonResponse(await editorLspFor(config).run(await realpath(workspace.path).catch(() => workspace.path), op, payload));
    } catch (error) {
      throw new ApiError(400, "invalid_payload", error instanceof Error ? error.message : String(error));
    }
  });
  // /btw: a side question about a chat, answered without touching it (side-question.ts).
  addRoute(routes, "POST", "/workspace/:id/btw", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const input = await readJsonBody(ctx.request);
    const ask = sideCallsByServer.get(config);
    if (!ask) return jsonResponse({ ok: false, error: "Sign in to omnirush.ai to ask side questions." });
    const sessionId = typeof input.sessionId === "string" ? input.sessionId : "";
    return jsonResponse(await askSideQuestion({
      engine: sessionId ? await captureEngineTarget(config, sessionId, workspace.id) : null,
      ask,
      catalog: () => readOmniRushModelCatalog(config),
      webSearch: () => webSearchSetting({ env: process.env, stateDir: runtimeStorageDir(config) }),
      capture: captureServicesByServer.get(config) ?? null,
    }, input));
  });
  registerEditorSearchRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace });
  registerEditorFormatRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope, sandboxOn: (workspace) => boxServiceFor(config).sandboxOn(workspace) });
  registerEditorRoutes({
    routes,
    config,
    jsonResponse,
    readJsonBody,
    ensureWritable,
    requireApproval,
    requireClientScope,
    resolveWorkspace,
    onSaved: (workspace, path) => editorSavesFor(config).record(normalizeOpencodeDirectory(workspace.path), path),
    onUserEdit: (edit) => {
      const capture = captureServicesByServer.get(config);
      if (!capture?.uploadEnabled || !capture.hasSession(edit.sessionId) || isUploadFileDenied(edit.path)) return;
      const event = editorUserEditEvent(edit);
      if (event) capture.recordTrace(edit.sessionId, "user_edit", event);
    },
    onUserReview: (review) => {
      const capture = captureServicesByServer.get(config);
      if (!capture?.uploadEnabled || !capture.hasSession(review.sessionId) || isUploadFileDenied(review.path)) return;
      capture.recordTrace(review.sessionId, "user_review", editorUserReviewEvent(review));
    },
  });

  addRoute(routes, "GET", "/workspace/:id/plugins", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const includeGlobal = ctx.url.searchParams.get("includeGlobal") === "true";
    const result = await listPlugins(config, workspace.id, workspace.path, includeGlobal);
    return jsonResponse(result);
  });

  addRoute(routes, "POST", "/workspace/:id/plugins", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    // User plugins are off while model providers are locked (provider-lock.ts).
    assertPluginsUnlocked();
    const body = await readJsonBody(ctx.request);
    const spec = String(body.spec ?? "");
    const normalized = normalizePluginSpec(spec);
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "plugins.add",
      summary: `Add plugin ${spec}`,
      paths: [omnirushConfigPath(workspace.path)],
    });
    const changed = await addPlugin(config, spec);
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "plugins.add",
      target: omnirushConfigPath(workspace.path),
      summary: `Added ${spec}`,
      timestamp: Date.now(),
    });
    if (changed) {
      emitReloadEvent(ctx.reloadEvents, workspace, "plugins", {
        type: "plugin",
        name: normalized,
        action: "added",
      });
    }
    const result = await listPlugins(config, workspace.id, workspace.path, false);
    return jsonResponse(result);
  });

  addRoute(routes, "DELETE", "/workspace/:id/plugins/:name", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const name = ctx.params.name ?? "";
    const normalized = normalizePluginSpec(name);
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "plugins.remove",
      summary: `Remove plugin ${name}`,
      paths: [omnirushConfigPath(workspace.path)],
    });
    const removed = await removePlugin(config, name);
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "plugins.remove",
      target: omnirushConfigPath(workspace.path),
      summary: `Removed ${name}`,
      timestamp: Date.now(),
    });
    if (removed) {
      emitReloadEvent(ctx.reloadEvents, workspace, "plugins", {
        type: "plugin",
        name: normalized,
        action: "removed",
      });
    }
    const result = await listPlugins(config, workspace.id, workspace.path, false);
    return jsonResponse(result);
  });

  addRoute(routes, "GET", "/workspace/:id/skills", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const includeGlobal = ctx.url.searchParams.get("includeGlobal") === "true";
    const items = await listSkills(workspace.path, includeGlobal);
    return jsonResponse({ items });
  });

  addRoute(routes, "GET", "/workspace/:id/skills/:name", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const includeGlobal = ctx.url.searchParams.get("includeGlobal") === "true";
    const name = String(ctx.params.name ?? "").trim();
    if (!name) {
      throw new ApiError(400, "invalid_skill_name", "Skill name is required");
    }
    const items = await listSkills(workspace.path, includeGlobal);
    const item = items.find((skill) => skill.name === name);
    if (!item) {
      throw new ApiError(404, "skill_not_found", `Skill not found: ${name}`);
    }
    const rawContent = await readFile(item.path, "utf8");
    const content = renderSkillContentForResponse(item, rawContent);
    return jsonResponse({ item, content });
  });

  addRoute(routes, "POST", "/workspace/:id/skills", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const name = String(body.name ?? "");
    const content = String(body.content ?? "");
    const description = body.description ? String(body.description) : undefined;
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "skills.upsert",
      summary: `Upsert skill ${name}`,
      paths: [join(workspace.path, ".opencode", "skills", name, "SKILL.md")],
    });
    const result = await upsertSkill(workspace.path, { name, content, description });
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "skills.upsert",
      target: result.path,
      summary: `Upserted skill ${name}`,
      timestamp: Date.now(),
    });
    emitReloadEvent(ctx.reloadEvents, workspace, "skills", {
      type: "skill",
      name,
      action: result.action,
      path: result.path,
    });
    return jsonResponse({ name, path: result.path, description: description ?? "", scope: "project" });
  });

  // Skill folders: SKILL.md plus helper files, uploaded as a folder or a .zip
  // that the client flattened to relative paths + base64 bytes. The preview
  // runs every check the install runs (and reports a name collision) without
  // writing anything.
  addRoute(routes, "POST", "/workspace/:id/skills/bundle/preview", "client", async (ctx) => {
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readBoundedJsonBody(ctx.request, SKILL_BUNDLE_MAX_REQUEST_BYTES);
    const bundle = prepareSkillBundle({ files: body.files, name: typeof body.name === "string" ? body.name : null });
    const conflict = await findSkillConflict(workspace.path, bundle.name);
    return jsonResponse({ ...summarizeSkillBundle(bundle), conflict });
  });

  addRoute(routes, "POST", "/workspace/:id/skills/bundle", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readBoundedJsonBody(ctx.request, SKILL_BUNDLE_MAX_REQUEST_BYTES);
    const bundle = prepareSkillBundle({ files: body.files, name: typeof body.name === "string" ? body.name : null });
    const onConflict = body.onConflict === "replace" ? "replace" : "fail";
    const targetDir = join(workspace.path, ".opencode", "skills", bundle.name);
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "skills.upsert",
      summary: `Install skill ${bundle.name} (${bundle.files.length} files)`,
      paths: [targetDir],
    });
    const result = await installSkillBundle(workspace.path, bundle, { onConflict });
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "skills.upsert",
      target: result.dir,
      summary: `${result.action === "updated" ? "Replaced" : "Installed"} skill ${bundle.name} from an upload (${bundle.files.length} files)`,
      timestamp: Date.now(),
    });
    emitReloadEvent(ctx.reloadEvents, workspace, "skills", {
      type: "skill",
      name: bundle.name,
      action: result.action,
      path: result.path,
    });
    return jsonResponse({
      ...summarizeSkillBundle(bundle),
      path: result.path,
      dir: result.dir,
      action: result.action,
      scope: "project",
    });
  });

  addRoute(routes, "GET", "/workspace/:id/skills/:name/files", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const dir = await resolveProjectSkillDir(workspace.path, String(ctx.params.name ?? ""));
    const tree = await listSkillTree(dir);
    return jsonResponse({ name: String(ctx.params.name ?? "").trim(), dir, ...tree });
  });

  addRoute(routes, "POST", "/workspace/:id/skills/:name/files", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const name = String(ctx.params.name ?? "").trim();
    const dir = await resolveProjectSkillDir(workspace.path, name);
    const body = await readBoundedJsonBody(ctx.request, SKILL_BUNDLE_MAX_REQUEST_BYTES);
    const addPaths = Array.isArray(body.add) ? body.add.map((file) => String((file as { path?: unknown })?.path ?? "")) : [];
    const removePaths = Array.isArray(body.remove) ? body.remove.map(String) : [];
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "skills.upsert",
      summary: `Update files of skill ${name}`,
      paths: [...addPaths, ...removePaths].map((path) => join(dir, path)),
    });
    const result = await updateSkillFiles(dir, { add: body.add, remove: body.remove });
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "skills.upsert",
      target: dir,
      summary: `Updated files of skill ${name} (+${result.added.length} -${result.removed.length})`,
      timestamp: Date.now(),
    });
    emitReloadEvent(ctx.reloadEvents, workspace, "skills", {
      type: "skill",
      name,
      action: "updated",
      path: join(dir, "SKILL.md"),
    });
    const tree = await listSkillTree(dir);
    return jsonResponse({ name, dir, ...result, ...tree });
  });

  addRoute(routes, "DELETE", "/workspace/:id/skills/:name", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const name = String(ctx.params.name ?? "").trim();
    if (!name) {
      throw new ApiError(400, "invalid_skill_name", "Skill name is required");
    }
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "skills.delete",
      summary: `Delete skill ${name}`,
      paths: [join(workspace.path, ".opencode", "skills", name)],
    });
    const result = await deleteSkill(workspace.path, name);
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "skills.delete",
      target: result.path,
      summary: `Deleted skill ${name}`,
      timestamp: Date.now(),
    });
    emitReloadEvent(ctx.reloadEvents, workspace, "skills", {
      type: "skill",
      name,
      action: "removed",
      path: result.path,
    });
    return jsonResponse({ ok: true, name, path: result.path });
  });

  // The project's MCP servers with the engine plugin's decision for each (on,
  // or blocked and why), and the servers the list supports (one-click presets).
  addRoute(routes, "GET", "/workspace/:id/mcp", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const items = await listMcp(config, workspace.id, workspace.path);
    const stateDir = runtimeStorageDir(config);
    const policy = currentMcpPolicy(stateDir);
    const report = workspace.workspaceType === "remote" ? null : workspaceMcpReport(stateDir, resolveOpencodeDirectory(workspace) || workspace.path);
    const decisions = report?.decisions ?? [];
    const enabled = policy?.enabled === true;
    return jsonResponse({
      items: items.map((item) => ({ ...item, managedOAuth: null, decision: decisions.find((decision) => decision.name === item.name) ?? null })),
      engineSync: null,
      managedOAuthState: { available: false, recovery: false },
      mcpPolicy: {
        mode: mcpPolicyForConfig(config),
        enabled,
        message: enabled ? policy?.message ?? null : mcpDisabledMessage(config),
        supported: enabled && policy ? policy.allow.map(mcpPreset) : [],
        decisions,
        reportAt: report?.at ?? null,
        // What of the project's own config the engine left out (plugins, language server and formatter commands).
        ignored: report?.ignored ?? [],
        ignoredNotice: describeIgnored(report?.ignored),
        // The engine's MCP plugin is missing: no MCP server starts (OMNIRUSH_MCP_FILTER=required).
        filterMissing: mcpFilterMissing(omnirushMcpPolicyPluginPath()) ? MCP_FILTER_MISSING : null,
      },
    });
  });

  addRoute(routes, "GET", "/mcp-apps/sandbox.html", "none", async (ctx) => {
    refuseAccountLinkedMcp();
    return new Response(MCP_APP_SANDBOX_PROXY_HTML, {
      headers: {
        "Content-Type": "text/html; charset=utf-8",
        "Content-Security-Policy": buildMcpAppSandboxCsp(parseMcpAppSandboxCsp(ctx.url.searchParams.get("csp"))),
        "Cache-Control": "no-store",
        "Referrer-Policy": "strict-origin",
        "X-Content-Type-Options": "nosniff",
      },
    });
  });
  addRoute(routes, "GET", "/mcp-apps/sandbox.js", "none", async () => {
    refuseAccountLinkedMcp();
    return new Response(MCP_APP_SANDBOX_PROXY_SCRIPT, {
      headers: { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" },
    });
  });
  addRoute(routes, "GET", "/mcp-apps/sandbox.css", "none", async () => {
    refuseAccountLinkedMcp();
    return new Response(MCP_APP_SANDBOX_PROXY_CSS, {
      headers: { "Content-Type": "text/css; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" },
    });
  });

  addRoute(routes, "GET", "/workspace/:id/mcp-apps/list", "client", async (ctx) => {
    refuseAccountLinkedMcp();
    requireClientScope(ctx, "viewer");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    try {
      const servers = await listMcpAppCatalog({
        serverConfig: config,
        workspaceId: workspace.id,
        workspaceRoot: workspace.path,
      });
      return jsonResponse({ servers });
    } catch (error) {
      rethrowMcpAppHostError(error);
    }
  });

  addRoute(routes, "POST", "/workspace/:id/mcp-apps/resolve", "client", async (ctx) => {
    refuseAccountLinkedMcp();
  });

  addRoute(routes, "POST", "/workspace/:id/mcp-apps/call", "client", async () => {
    refuseAccountLinkedMcp();
  });

  addRoute(routes, "POST", "/workspace/:id/mcp/managed", "client", async () => {
    refuseAccountLinkedMcp();
  });

  addRoute(routes, "GET", "/workspace/:id/mcp/:name/managed", "client", async () => {
    refuseAccountLinkedMcp();
  });

  addRoute(routes, "POST", "/workspace/:id/mcp/:name/managed/connect", "client", async () => {
    refuseAccountLinkedMcp();
  });

  addRoute(routes, "GET", "/mcp/oauth/callback", "none", async () => {
    refuseAccountLinkedMcp();
  });

  const managedGatewayHandler = async () => {
    refuseAccountLinkedMcp();
  };
  addRoute(routes, "POST", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
  addRoute(routes, "GET", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);
  addRoute(routes, "DELETE", "/mcp/managed/:workspaceId/:name", "none", managedGatewayHandler);

  // Adds a local MCP server the list allows (addMcp refuses others with the
  // reason). It reaches the engine through the MCP plugin when the project's
  // engine instance reloads (the reload event below).
  addRoute(routes, "POST", "/workspace/:id/mcp", "client", async (ctx) => {
    assertMcpAllowed(config);
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    if (workspace.workspaceType === "remote") throw new ApiError(400, "mcp_remote_workspace", "MCP servers can be added to local projects only.");
    const body = await readJsonBody(ctx.request);
    const name = String(body.name ?? "");
    validateUserMcpName(name);
    const configPayload = body.config as Record<string, unknown> | undefined;
    if (!configPayload || typeof configPayload !== "object" || Array.isArray(configPayload)) {
      throw new ApiError(400, "invalid_payload", "MCP config is required");
    }
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "mcp.add",
      summary: `Add MCP ${name}`,
      paths: [omnirushConfigPath(workspace.path)],
    });
    const result = await addMcp(config, workspace.id, name, configPayload, resolveOpencodeDirectory(workspace) || workspace.path);
    await syncRuntimeMcpToOpencodeEngine(config, workspace, [name], undefined, engineMcpServerState).catch(() => undefined);
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "mcp.add",
      target: omnirushConfigPath(workspace.path),
      summary: `Added MCP ${name}`,
      timestamp: Date.now(),
    });
    emitReloadEvent(ctx.reloadEvents, workspace, "mcp", {
      type: "mcp",
      name,
      action: result.action,
    });
    const items = await listMcp(config, workspace.id, workspace.path);
    return jsonResponse({ items });
  });

  addRoute(routes, "DELETE", "/workspace/:id/mcp/:name", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const name = ctx.params.name ?? "";
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "mcp.remove",
      summary: `Remove MCP ${name}`,
      paths: [omnirushConfigPath(workspace.path)],
    });
    const managedRemoved = name === OMNIRUSH_CLOUD_MCP_NAME
      ? false
      : await deleteLocalManagedMcp(config, workspace.id, name);
    const cloudRemoval = name === OMNIRUSH_CLOUD_MCP_NAME
      ? await removeOmniRushCloudMcpDesiredConfig(config)
      : null;
    const removed = cloudRemoval
      ? cloudRemoval.changed
      : managedRemoved || await removeMcp(config, workspace.id, name);
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "mcp.remove",
      target: omnirushConfigPath(workspace.path),
      summary: `Removed MCP ${name}`,
      timestamp: Date.now(),
    });
    if (removed) {
      const affectedWorkspaces = cloudRemoval ? config.workspaces : [workspace];
      const removedNames = cloudRemoval ? cloudRemoval.removedNames : [name];
      await Promise.all(affectedWorkspaces.map(async (affectedWorkspace) => {
        for (const removedName of removedNames) {
          deleteEngineMcpRegistration(config, engineMcpServerState, affectedWorkspace, removedName);
          await disconnectMcpFromOpencodeEngine(config, affectedWorkspace, removedName).catch(() => undefined);
        }
        await syncRuntimeMcpToOpencodeEngine(config, affectedWorkspace, undefined, undefined, engineMcpServerState).catch(() => undefined);
      }));
      emitReloadEvent(ctx.reloadEvents, workspace, "mcp", {
        type: "mcp",
        name,
        action: "removed",
      });
    }
    const items = await listMcp(config, workspace.id, workspace.path);
    return jsonResponse({ items });
  });

  // Toggle `enabled` on a workspace MCP. Strict body validation — `Boolean(body.enabled)`
  // would silently disable on `{}` or coerce `"false"` to true.
  addRoute(routes, "POST", "/workspace/:id/mcp/:name/enabled", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const name = ctx.params.name ?? "";
    const body = await readJsonBody(ctx.request);
    if (!body || typeof body !== "object" || Array.isArray(body) || typeof body.enabled !== "boolean") {
      throw new ApiError(400, "invalid_payload", "enabled must be a boolean");
    }
    const enabled = body.enabled;
    if (enabled) assertMcpAllowed(config);
    const action = enabled ? "mcp.enable" : "mcp.disable";
    const summary = `${enabled ? "Enable" : "Disable"} MCP ${name}`;
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action,
      summary,
      paths: [omnirushConfigPath(workspace.path)],
    });
    const managedUpdated = await setLocalManagedMcpEnabled(config, workspace.id, name, enabled);
    const updated = managedUpdated || await setMcpEnabled(config, workspace.id, name, enabled);
    if (!updated) {
      throw new ApiError(404, "mcp_not_found", `MCP ${name} not found in workspace config`);
    }
    await syncRuntimeMcpToOpencodeEngine(
      config,
      workspace,
      [name],
      undefined,
      engineMcpServerState,
    ).catch(() => undefined);
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action,
      target: omnirushConfigPath(workspace.path),
      summary: `${enabled ? "Enabled" : "Disabled"} MCP ${name}`,
      timestamp: Date.now(),
    });
    // ReloadTrigger.action only allows added/removed/updated, so toggle => "updated".
    emitReloadEvent(ctx.reloadEvents, workspace, "mcp", {
      type: "mcp",
      name,
      action: "updated",
    });
    const items = await listMcp(config, workspace.id, workspace.path);
    return jsonResponse({ items });
  });

  addRoute(routes, "DELETE", "/workspace/:id/mcp/:name/auth", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const name = String(ctx.params.name ?? "").trim();
    validateMcpName(name);

    if (await disconnectLocalManagedMcp(config, workspace.id, name)) {
      await disconnectMcpFromOpencodeEngine(config, workspace, name).catch(() => undefined);
      await syncRuntimeMcpToOpencodeEngine(config, workspace, [name], undefined, engineMcpServerState).catch(() => undefined);
      await recordAudit(workspace.path, {
        id: shortId(),
        workspaceId: workspace.id,
        actor: ctx.actor ?? { type: "remote" },
        action: "mcp.auth.remove",
        target: omnirushConfigPath(workspace.path),
        summary: `Logged out OmniRush.ai-managed MCP ${name}`,
        timestamp: Date.now(),
      });
      return jsonResponse({ ok: true });
    }

    const authStorePath = join(homedir(), ".config", "opencode", "mcp-auth.json");
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "mcp.auth.remove",
      summary: `Logout MCP ${name}`,
      paths: [authStorePath],
    });

    // Best-effort disconnect so any active connection is torn down.
    try {
      const opencode = createWorkspaceOpencodeClient(config, workspace);
      unwrapOpencodeResult(await opencode.mcp.disconnect({ name }), `/mcp/${encodeURIComponent(name)}/disconnect`);
    } catch {
      // ignore
    }

    try {
      const opencode = createWorkspaceOpencodeClient(config, workspace);
      unwrapOpencodeResult(await opencode.mcp.auth.remove({ name }), `/mcp/${encodeURIComponent(name)}/auth`);
    } catch (error) {
      // Treat missing credentials as a successful logout (idempotent).
      if (
        error instanceof ApiError &&
        error.code === "opencode_request_failed" &&
        error.details &&
        typeof error.details === "object" &&
        "status" in (error.details as Record<string, unknown>) &&
        (error.details as { status?: unknown }).status === 404
      ) {
        // ok
      } else {
        throw error;
      }
    }

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "mcp.auth.remove",
      target: authStorePath,
      summary: `Logged out MCP ${name}`,
      timestamp: Date.now(),
    });

    return jsonResponse({ ok: true });
  });

  addRoute(routes, "GET", "/workspace/:id/commands", "client", async (ctx) => {
    const scope = ctx.url.searchParams.get("scope") === "global" ? "global" : "workspace";
    if (scope === "global") {
      await requireHost(ctx.request, config, tokens);
    }
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const items = await listCommands(workspace.path, scope);
    return jsonResponse({ items });
  });

  addRoute(routes, "POST", "/workspace/:id/commands", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const name = String(body.name ?? "");
    const template = String(body.template ?? "");
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "commands.upsert",
      summary: `Upsert command ${name}`,
      paths: [join(workspace.path, ".opencode", "commands", `${sanitizeCommandName(name)}.md`)],
    });
    const path = await upsertCommand(workspace.path, {
      name,
      description: body.description ? String(body.description) : undefined,
      template,
      agent: body.agent ? String(body.agent) : undefined,
      model: body.model ? String(body.model) : undefined,
      subtask: typeof body.subtask === "boolean" ? body.subtask : undefined,
    });
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "commands.upsert",
      target: path,
      summary: `Upserted command ${name}`,
      timestamp: Date.now(),
    });

    emitReloadEvent(ctx.reloadEvents, workspace, "commands", {
      type: "command",
      name: sanitizeCommandName(name),
      action: "updated",
      path,
    });
    const items = await listCommands(workspace.path, "workspace");
    return jsonResponse({ items });
  });

  addRoute(routes, "DELETE", "/workspace/:id/commands/:name", "client", async (ctx) => {
    ensureWritable(config);
    requireClientScope(ctx, "collaborator");
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const name = ctx.params.name ?? "";
    await requireApproval(ctx, {
      workspaceId: workspace.id,
      action: "commands.delete",
      summary: `Delete command ${name}`,
      paths: [join(workspace.path, ".opencode", "commands", `${sanitizeCommandName(name)}.md`)],
    });
    await deleteCommand(workspace.path, name);
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "remote" },
      action: "commands.delete",
      target: join(workspace.path, ".opencode", "commands"),
      summary: `Deleted command ${name}`,
      timestamp: Date.now(),
    });

    emitReloadEvent(ctx.reloadEvents, workspace, "commands", {
      type: "command",
      name: sanitizeCommandName(name),
      action: "removed",
      path: join(workspace.path, ".opencode", "commands", `${sanitizeCommandName(name)}.md`),
    });
    return jsonResponse({ ok: true });
  });

  addRoute(routes, "GET", "/workspace/:id/export", "client", async (ctx) => {
    const workspace = await resolveWorkspace(config, ctx.params.id);
    const sensitiveMode = parseWorkspaceExportSensitiveMode(ctx.url.searchParams.get("sensitive"));
    const exportPayload = await exportWorkspace(config, workspace, { sensitiveMode });
    return jsonResponse(exportPayload);
  });

  return routes;
}

async function resolveWorkspaceForInspection(config: ServerConfig, id: string): Promise<WorkspaceInfo> {
  const workspaceId = id.trim();
  const aliasWorkspaceId = workspaceId.startsWith("rem_") ? workspaceId.slice("rem_".length) : "";
  const workspace =
    config.workspaces.find((entry) => entry.id === workspaceId) ??
    (aliasWorkspaceId ? config.workspaces.find((entry) => entry.id === aliasWorkspaceId) : undefined);
  if (!workspace) {
    throw new ApiError(404, "workspace_not_found", "Workspace not found");
  }
  if (workspace.workspaceType === "remote") {
    return { ...workspace };
  }
  const resolvedWorkspace = resolve(workspace.path);
  const authorized = await isAuthorizedRoot(resolvedWorkspace, config.authorizedRoots);
  if (!authorized) {
    throw new ApiError(403, "workspace_unauthorized", "Workspace is not authorized");
  }
  return { ...workspace, path: resolvedWorkspace };
}

async function resolveWorkspaceWithoutBootstrap(config: ServerConfig, id: string): Promise<WorkspaceInfo> {
  const workspaceId = id.trim();
  const aliasWorkspaceId = workspaceId.startsWith("rem_") ? workspaceId.slice("rem_".length) : "";
  const configuredWorkspace =
    config.workspaces.find((entry) => entry.id === workspaceId) ??
    (aliasWorkspaceId ? config.workspaces.find((entry) => entry.id === aliasWorkspaceId) : undefined);
  if (!configuredWorkspace) {
    throw new ApiError(404, "workspace_not_found", "Workspace not found");
  }
  const resolvedWorkspace = resolve(configuredWorkspace.path);
  const authorized = await isAuthorizedRoot(resolvedWorkspace, config.authorizedRoots);
  if (!authorized) {
    throw new ApiError(403, "workspace_unauthorized", "Workspace is not authorized");
  }
  const workspace = { ...configuredWorkspace, path: resolvedWorkspace };
  return workspace;
}

async function resolveWorkspace(config: ServerConfig, id: string): Promise<WorkspaceInfo> {
  const workspace = await resolveWorkspaceWithoutBootstrap(config, id);
  const resolvedWorkspace = workspace.path;
  if (!config.readOnly) {
    const ensured = await ensureWorkspaceFiles(resolvedWorkspace, workspace.preset ?? "starter", { createMissing: false });
    const bootstrapReloadReasons = new Set<ReloadReason>(ensured.reloadReasons);
    if (await repairCommands(resolvedWorkspace)) {
      bootstrapReloadReasons.add("commands");
    }
    if (bootstrapReloadReasons.size > 0) {
      await reloadBaselineRefreshers.get(config)?.(workspace.id, Array.from(bootstrapReloadReasons));
      reloadOpencodeEngineAfterInternalBootstrap(config, { ...workspace, path: resolvedWorkspace });
    }
  }
  return workspace;
}

function reloadOpencodeEngineAfterInternalBootstrap(config: ServerConfig, workspace: WorkspaceInfo): void {
  const connection = resolveWorkspaceOpencodeConnection(config, workspace);
  if (!connection.baseUrl?.trim()) return;
  void reloadOpencodeEngine(config, workspace, undefined, { reason: "workspace_bootstrap" }).catch((error) => {
    createServerLogger(config).log("error", `Bootstrap engine reload failed for workspace ${workspace.id}.`, {
      "workspace.id": workspace.id,
      "engine.reload.failure": error instanceof Error ? error.message : String(error),
    });
  });
}

async function isAuthorizedRoot(workspacePath: string, roots: string[]): Promise<boolean> {
  const resolvedWorkspace = resolve(workspacePath);
  for (const root of roots) {
    const resolvedRoot = resolve(root);
    if (resolvedWorkspace === resolvedRoot) return true;
    if (resolvedWorkspace.startsWith(resolvedRoot + sep)) return true;
  }
  return false;
}

function ensureWritable(config: ServerConfig): void {
  if (config.readOnly) {
    throw new ApiError(403, "read_only", "Server is read-only");
  }
}

function scopeRank(scope: TokenScope): number {
  if (scope === "viewer") return 1;
  if (scope === "collaborator") return 2;
  return 3;
}

function requireClientScope(ctx: RequestContext, required: TokenScope): void {
  const scope = ctx.actor?.scope;
  if (!scope) {
    throw new ApiError(401, "unauthorized", "Missing token scope");
  }
  if (scopeRank(scope) < scopeRank(required)) {
    throw new ApiError(403, "forbidden", "Insufficient token scope", { required, scope });
  }
}

async function readJsonBody(request: Request): Promise<Record<string, unknown>> {
  try {
    const json = await request.json();
    return json as Record<string, unknown>;
  } catch {
    throw new ApiError(400, "invalid_json", "Invalid JSON body");
  }
}

async function readAgentDiagnosticsJsonBody(request: Request): Promise<unknown> {
  const tooLarge = () => new ApiError(
    413,
    "agent_diagnostics_request_too_large",
    "Agent diagnostics request body is too large",
  );
  const timedOut = () => new ApiError(
    408,
    "agent_diagnostics_request_timeout",
    "Agent diagnostics request body timed out",
  );
  const configuredDeadlineMs = Number(process.env.OMNIRUSH_AGENT_DIAGNOSTICS_BODY_TIMEOUT_MS);
  const deadlineMs = Number.isFinite(configuredDeadlineMs) && configuredDeadlineMs >= 50
    ? Math.min(configuredDeadlineMs, 10_000)
    : AGENT_DIAGNOSTICS_DEFAULT_BODY_DEADLINE_MS;
  const declaredLength = request.headers.get("content-length");
  if (declaredLength !== null) {
    const declaredBytes = Number(declaredLength);
    if (Number.isFinite(declaredBytes) && declaredBytes > AGENT_DIAGNOSTICS_MAX_REQUEST_BYTES) {
      throw tooLarge();
    }
  }

  const reader = request.body?.getReader();
  if (!reader) {
    throw new ApiError(400, "invalid_json", "Invalid JSON body");
  }
  const chunks: Uint8Array[] = [];
  let size = 0;
  let deadlineExpired = false;
  let activeRead: ReturnType<typeof reader.read> | undefined;
  let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
  const deadline = new Promise<never>((_resolve, reject) => {
    deadlineTimer = setTimeout(() => {
      deadlineExpired = true;
      reject(timedOut());
    }, deadlineMs);
  });
  try {
    while (true) {
      // Race every read against the same promise. Incoming drips do not reset
      // the absolute request-body lifetime.
      activeRead = reader.read();
      const next = await Promise.race([activeRead, deadline]);
      activeRead = undefined;
      if (next.done) {
        break;
      }
      size += next.value.byteLength;
      if (size > AGENT_DIAGNOSTICS_MAX_REQUEST_BYTES) {
        throw tooLarge();
      }
      chunks.push(next.value);
    }
  } catch (error) {
    if (error instanceof ApiError) throw error;
    throw new ApiError(400, "invalid_json", "Invalid JSON body");
  } finally {
    if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);
    if (deadlineExpired && activeRead) {
      const pendingRead = activeRead;
      let released = false;
      const release = () => {
        if (released) return;
        try {
          reader.releaseLock();
          released = true;
        } catch {
          // Cancellation owns the lock until the adapter finishes settling it.
        }
      };
      // Returning the 408 with Connection: close lets the adapter flush the
      // stable safe error before this active stream cancellation tears down the
      // underlying request socket. The absolute deadline is not extended.
      // Keep the reader locked until cancellation even if another drip settles
      // the specific read that lost the deadline race. Otherwise that drip
      // could leave the remainder of the body unbounded. Wait for both the
      // cancellation and outstanding read before releasing the lock.
      setTimeout(() => {
        void (async () => {
          await reader.cancel(new Error("Agent diagnostics request body timed out")).catch(() => undefined);
          await pendingRead.catch(() => undefined);
          release();
        })();
      }, AGENT_DIAGNOSTICS_ERROR_FLUSH_MS);
    } else {
      reader.releaseLock();
    }
  }

  const bytes = new Uint8Array(size);
  let offset = 0;
  for (const chunk of chunks) {
    bytes.set(chunk, offset);
    offset += chunk.byteLength;
  }
  try {
    const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
    return JSON.parse(text) as unknown;
  } catch {
    throw new ApiError(400, "invalid_json", "Invalid JSON body");
  }
}

async function readOptionalJsonBody(request: Request): Promise<Record<string, unknown>> {
  const text = await request.text();
  if (!text.trim()) return {};
  try {
    return ensurePlainObject(JSON.parse(text));
  } catch {
    throw new ApiError(400, "invalid_json", "Invalid JSON body");
  }
}

function parseOptionalPositiveInteger(value: string | null, name: string): number | undefined {
  if (value === null) return undefined;
  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    throw new ApiError(400, "invalid_query", `${name} must be a positive integer`);
  }
  return parsed;
}

function parseOptionalNonNegativeInteger(value: string | null, name: string): number | undefined {
  if (value === null) return undefined;
  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed) || parsed < 0) {
    throw new ApiError(400, "invalid_query", `${name} must be a non-negative integer`);
  }
  return parsed;
}

function parseOptionalBoolean(value: string | null, name: string): boolean | undefined {
  if (value === null) return undefined;
  const normalized = value.trim().toLowerCase();
  if (["1", "true", "yes", "on"].includes(normalized)) return true;
  if (["0", "false", "no", "off"].includes(normalized)) return false;
  throw new ApiError(400, "invalid_query", `${name} must be a boolean`);
}

function ensurePlainObject(value: unknown): Record<string, unknown> {
  if (!value || typeof value !== "object" || Array.isArray(value)) return {};
  return value as Record<string, unknown>;
}

function normalizeOpencodeScope(value: string | null | undefined): "project" | "global" {
  return value?.trim().toLowerCase() === "global" ? "global" : "project";
}

export function resolveOpencodeConfigFilePath(scope: "project" | "global", workspaceRoot: string): string {
  if (scope === "global") return resolveGlobalOpencodeConfigPath();
  return opencodeConfigPath(workspaceRoot);
}

function getRuntimeControlConfig(): { baseUrl: string; token: string } | null {
  const baseUrl = process.env.OMNIRUSH_CONTROL_BASE_URL?.trim() ?? "";
  const token = process.env.OMNIRUSH_CONTROL_TOKEN?.trim() ?? "";
  if (!baseUrl || !token) return null;
  return { baseUrl: baseUrl.replace(/\/+$/, ""), token };
}

async function fetchRuntimeControl(path: string, init?: { method?: string; body?: unknown }) {
  const control = getRuntimeControlConfig();
  if (!control) {
    throw new ApiError(501, "runtime_upgrade_unavailable", "Worker runtime control is not configured on this host");
  }
  const response = await externalFetch(`${control.baseUrl}${path}`, {
    method: init?.method ?? "GET",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${control.token}`,
    },
    body: init?.body === undefined ? undefined : JSON.stringify(init.body),
  });
  const text = await response.text();
  const json = text ? JSON.parse(text) : null;
  if (!response.ok) {
    throw new ApiError(response.status, "runtime_upgrade_failed", "Worker runtime control request failed", json);
  }
  return json;
}

async function readOpencodeConfig(workspaceRoot: string): Promise<Record<string, unknown>> {
  const { data } = await readJsoncFile(opencodeConfigPath(workspaceRoot), {} as Record<string, unknown>, { allowInvalid: true });
  return data;
}

async function readOmniRushConfig(workspaceRoot: string): Promise<Record<string, unknown>> {
  const path = omnirushConfigPath(workspaceRoot);
  if (!(await exists(path))) return {};
  try {
    const raw = await readFile(path, "utf8");
    return JSON.parse(raw) as Record<string, unknown>;
  } catch {
    throw new ApiError(422, "invalid_json", "Failed to parse omnirush.json");
  }
}

async function readOmniRushConfigForStatus(workspaceRoot: string): Promise<{
  data: Record<string, unknown>;
  error: string | null;
}> {
  try {
    return { data: await readOmniRushConfig(workspaceRoot), error: null };
  } catch (error) {
    if (error instanceof ApiError && error.code === "invalid_json") {
      return { data: {}, error: error.message };
    }
    throw error;
  }
}

/**
 * Resolve the effective per-workspace omnirush config from the runtime DB,
 * migrating a legacy `.opencode/omnirush.json` file into the DB on first read.
 *
 * The DB is the source of truth. The file is only consulted to seed the DB
 * once (back-compat for workspaces created before the file->DB migration), and
 * is never written afterwards. Returns the merged view ({...file, ...db}) so a
 * partially-migrated install still surfaces every key.
 */
async function readOmniRushConfigForWorkspace(
  config: ServerConfig,
  workspace: WorkspaceInfo,
): Promise<Record<string, unknown>> {
  const stored = await readOmniRushWorkspaceConfig(config, workspace.id);
  if (Object.keys(stored).length > 0 || (await hasOmniRushWorkspaceConfig(config, workspace.id))) {
    return stored;
  }
  const legacy = await readOmniRushConfigForStatus(workspace.path);
  if (Object.keys(legacy.data).length === 0) {
    if (workspace.workspaceType !== "remote" && workspace.path.trim()) {
      return seedOmniRushWorkspaceConfigIfEmpty(
        config,
        workspace.id,
        defaultWorkspaceOmniRushConfig(workspace.path, workspace.preset ?? "starter"),
      );
    }
    return {};
  }
  // Migrate-on-read: copy the legacy file contents into the DB once.
  await seedOmniRushWorkspaceConfigIfEmpty(config, workspace.id, legacy.data);
  return mergeOmniRushWorkspaceConfigs(legacy.data, await readOmniRushWorkspaceConfig(config, workspace.id));
}

/**
 * Persist a full omnirush config document for a workspace to the runtime DB.
 * Replaces the legacy file write path; the file is no longer written.
 */
async function writeOmniRushConfigForWorkspace(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  payload: Record<string, unknown>,
  merge: boolean,
): Promise<void> {
  await writeOmniRushWorkspaceConfig(config, workspace.id, (current) =>
    merge ? { ...current, ...payload } : payload,
  );
}

function resolveOpencodeDirectory(workspace: WorkspaceInfo): string | null {
  const explicit = workspace.directory?.trim() ?? "";
  if (explicit) return normalizeOpencodeDirectory(explicit);
  if (workspace.workspaceType === "local") return normalizeOpencodeDirectory(workspace.path);
  return null;
}

export function normalizeOpencodeDirectory(
  directory: string,
  platform: NodeJS.Platform = process.platform,
): string {
  // OpenCode stores/list-filters Windows sessions by regular drive paths
  // (`C:\Users\...`). Electron can persist local workspaces as extended-length
  // paths (`\\?\C:\Users\...`); passing those through as the directory query
  // makes OpenCode return an empty session list even though the sessions exist.
  if (platform === "win32") {
    return directory.replace(/^\\\\\?\\/, "").replace(/^\/\/\?\//, "");
  }
  return directory;
}

function buildOpencodeReloadUrl(baseUrl: string, directory?: string | null): string {
  try {
    const url = new URL(baseUrl);
    url.pathname = "/instance/dispose";
    url.search = "";
    if (directory) {
      url.searchParams.set("directory", directory);
    }
    return url.toString();
  } catch {
    throw new ApiError(400, "opencode_url_invalid", "OmniRush base URL is invalid");
  }
}

function parseOpencodeErrorBody(input: string): unknown {
  const trimmed = input.trim();
  if (!trimmed) return null;
  try {
    return JSON.parse(trimmed) as unknown;
  } catch {
    return trimmed;
  }
}

// Bounded so a dispose wedged on live-session teardown can never freeze the
// caller (CloudProviderSync serializes passes on one queue; an unbounded
// dispose froze every later pass and the status it reports). Overridable for
// tests.
function opencodeDisposeTimeoutMs(): number {
  const configured = Number(process.env.OMNIRUSH_ENGINE_DISPOSE_TIMEOUT_MS ?? "");
  return Number.isFinite(configured) && configured > 0 ? configured : 30_000;
}

async function requireWorkspaceRunModeIdle(config: ServerConfig, workspace: WorkspaceInfo): Promise<void> {
  const connection = resolveWorkspaceOpencodeConnection(config, workspace);
  const connections = new Map<string, string | undefined>();
  if (connection.baseUrl) connections.set(connection.baseUrl, connection.authHeader);
  // Include draining generations: a waiting permission can belong to an older
  // engine even when the primary reports no active sessions.
  for (const entry of enginePoolForConfig(config)?.connections() ?? []) {
    connections.set(entry.baseUrl, buildEngineAuthProbeHeader(entry.username, entry.password));
  }
  await Promise.all([...connections].map(async ([baseUrl, authorization]) => {
    await Promise.all(["/session/status", "/permission", "/question"].map(async (path) => {
      let payload: unknown;
      try {
        const url = new URL(path, baseUrl);
        const directory = resolveOpencodeDirectory(workspace);
        if (directory) url.searchParams.set("directory", directory);
        const response = await loopbackFetch(url.toString(), {
          headers: authorization ? { Authorization: authorization } : {},
          signal: AbortSignal.timeout(5_000),
        });
        if (!response.ok) throw new Error("Activity probe failed");
        payload = await response.json();
      } catch {
        throw new ApiError(409, "workspace_run_mode_activity_unknown", "Cannot verify that all workspace sessions are idle; no permission change was made.");
      }
      if (path === "/session/status" ? !isRecord(payload) || Object.values(payload).some((status) => !isRecord(status) || typeof status.type !== "string") : !Array.isArray(payload)) {
        throw new ApiError(409, "workspace_run_mode_activity_unknown", "OmniRush returned unreadable workspace activity; no permission change was made.");
      }
      const busy = Array.isArray(payload) ? payload.length > 0 : isRecord(payload) && Object.values(payload).some((status) => isRecord(status) && status.type !== "idle");
      if (busy) throw new ApiError(409, "workspace_run_mode_busy", "Wait for all workspace sessions, including permission and question requests, to finish before changing run mode.");
    }));
  }));
}

/**
 * Whether two session folders are the same folder: the Windows extended-length
 * prefix, slash direction and a trailing slash never matter, and case does not
 * matter on Windows and macOS (both case-insensitive by default).
 */
export function isSameSessionFolder(left: string, right: string, platform: NodeJS.Platform = process.platform): boolean {
  const normalize = (value: string) => {
    const unified = normalizeOpencodeDirectory(value.trim(), platform).replace(/\\/g, "/").replace(/\/+$/, "");
    const folder = unified || "/";
    return platform === "win32" || platform === "darwin" ? folder.toLowerCase() : folder;
  };
  return Boolean(left.trim()) && normalize(left) === normalize(right);
}

/** Most recently updated sessions across every engine project (up to this many are scanned). */
const SESSIONS_BY_FOLDER_SCAN = 2_000;

/**
 * The sessions stored for `directory`, newest first, read from the engine's
 * unscoped session list: no project filter and no exact folder filter.
 */
export async function listEngineSessionsInFolder(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  directory: string,
  limit: number,
  fetchImpl: (input: string, init?: RequestInit) => Promise<Response> = loopbackFetch,
): Promise<unknown[]> {
  const pool = enginePoolForConfig(config);
  const route = pool?.routeRequest("GET", "/experimental/session") ?? null;
  const connection = route ? null : resolveWorkspaceOpencodeConnection(config, workspace);
  const baseUrl = route?.target.baseUrl ?? connection?.baseUrl?.trim() ?? "";
  if (!baseUrl) throw new ApiError(503, "opencode_unconfigured", "OmniRush base URL is missing for this workspace");
  const headers = new Headers();
  // The header picks the folder's engine instance; with no `directory` query
  // the engine lists sessions of every folder and project.
  headers.set("x-opencode-directory", buildOpencodeDirectoryHeader(directory));
  const auth = route
    ? buildEngineAuthProbeHeader(route.target.username, route.target.password)
    : connection?.authHeader ?? null;
  if (auth) headers.set("Authorization", auth);
  const url = buildOpencodeProxyUrl(baseUrl, "/experimental/session", `?limit=${SESSIONS_BY_FOLDER_SCAN}&archived=true`);
  const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(45_000) });
  if (!response.ok) {
    throw new ApiError(response.status === 404 ? 404 : 502, "opencode_engine_unreachable", `The engine session list failed with status ${response.status}`);
  }
  const payload: unknown = await response.json();
  if (!Array.isArray(payload)) return [];
  return payload
    .filter((session) => isRecord(session) && typeof session.directory === "string" && isSameSessionFolder(session.directory, directory))
    .slice(0, limit);
}

/**
 * The 2.x engine's sessions stored for `directory`, newest first, raw: from its
 * list of every folder, matched without case (Windows, macOS), slash
 * direction, a trailing slash or the long-path prefix, or by real path
 * (symlink, junction, subst drive).
 */
/** The by-folder list of the 2.x engine. At start the engine is still coming up: waited for (the app's call allows 45 s), a 503 only when it is not up by then. */
export async function listEngineV2FolderSessions(
  preview: Pick<EngineV2Preview, "awaitConnection"> | undefined,
  directory: string,
  limit: number,
  waitMs = BY_FOLDER_ENGINE_WAIT_MS,
  fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>,
): Promise<unknown[]> {
  const v2 = await preview?.awaitConnection(waitMs);
  if (!v2) throw new ApiError(503, "opencode_unconfigured", "The engine is not running");
  return listEngineV2SessionsInFolder(v2, directory, limit, fetchImpl);
}

export async function listEngineV2SessionsInFolder(
  v2: { url: string; password: string },
  directory: string,
  limit: number,
  fetchImpl: (input: string, init?: RequestInit) => Promise<Response> = loopbackFetch,
): Promise<unknown[]> {
  const headers = new Headers({ authorization: `Basic ${Buffer.from(`opencode:${v2.password}`).toString("base64")}` });
  const response = await fetchImpl(buildOpencodeProxyUrl(v2.url, "/api/session", `?limit=${SESSIONS_BY_FOLDER_SCAN}&order=desc`), { headers, signal: AbortSignal.timeout(45_000) });
  if (!response.ok) {
    throw new ApiError(response.status === 404 ? 404 : 502, "opencode_engine_unreachable", `The engine session list failed with status ${response.status}`);
  }
  const payload: unknown = await response.json();
  const items = isRecord(payload) && Array.isArray(payload.data) ? payload.data : Array.isArray(payload) ? payload : [];
  const real = await realpath(directory).catch(() => directory);
  const base = (value: string) => directoryMatchKey(value).split("/").pop() ?? "";
  const found: unknown[] = [];
  for (const session of items) {
    const location = isRecord(session) && isRecord(session.location) ? session.location : null;
    const folder = location && typeof location.directory === "string" ? location.directory : "";
    if (!folder) continue;
    // Real paths are read only for a folder of the same name: a scan of every chat stays cheap.
    const same = isSameSessionFolder(folder, directory) || isSameSessionFolder(folder, real)
      || ((base(folder) === base(directory) || base(folder) === base(real)) && isSameSessionFolder(await realpath(folder).catch(() => folder), real));
    if (same) found.push(session);
    if (found.length >= limit) break;
  }
  return found;
}

/**
 * True when the managed engine reports any non-idle session (subagent child
 * sessions carry their own ids and statuses, so they count too). Unknown
 * activity reports `unknownIsBusy`: false for callers that would otherwise
 * park a reload forever against a dead engine, true for the rollover pool,
 * where "busy" only means rolling over to a standby instead of disposing an
 * engine that may still be running sessions.
 */
async function engineHasActiveSessions(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  unknownIsBusy = false,
): Promise<boolean> {
  try {
    const opencode = createWorkspaceOpencodeClient(config, workspace);
    const statuses = unwrapOpencodeResult(await opencode.session.status(), "/session/status");
    return Object.values(statuses).some((status) => status.type !== "idle");
  } catch {
    return unknownIsBusy;
  }
}

/**
 * Sessions still running on the managed engine, for the desktop's restart
 * guard. Only directories the engine already serves are probed; `unknown`
 * counts probes that could not be read and callers treat them as busy.
 */
export async function collectBusyEngineSessions(config: ServerConfig): Promise<{ sessions: string[]; unknown: number }> {
  const pool = enginePoolForConfig(config);
  if (!pool) return { sessions: [], unknown: 0 };
  const directories = new Set(engineInstanceReaperForConfig(config)?.snapshot().map((instance) => instance.directory) ?? []);
  return pool.activeSessions([...directories]);
}

function primaryManagedEngineConnection(config: ServerConfig): EnginePoolConnection | null {
  return enginePoolForConfig(config)?.connections().find((entry) => entry.role === "primary") ?? null;
}

/**
 * Whether a tracked engine instance still reports a non-idle session. Probed
 * directly against the managed engine (never through the workspace client) so
 * the reaper's own probe cannot refresh the instance's last-used time.
 * Throws on an unreadable status: unknown activity must never evict.
 */
async function engineInstanceHasActiveSessions(
  config: ServerConfig,
  instance: TrackedEngineInstance,
): Promise<boolean> {
  const primary = primaryManagedEngineConnection(config);
  if (!primary || primary.baseUrl !== instance.engineBaseUrl) return false;
  const url = new URL("/session/status", primary.baseUrl);
  url.searchParams.set("directory", instance.directory);
  const response = await loopbackFetch(url.toString(), {
    headers: { Authorization: buildEngineAuthProbeHeader(primary.username, primary.password) },
    signal: AbortSignal.timeout(5_000),
  });
  if (!response.ok) throw new Error(`OmniRush session status probe failed with status ${response.status}`);
  const payload: unknown = await response.json();
  if (!isRecord(payload)) return false;
  return Object.values(payload).some((status) => isRecord(status) && status.type !== "idle");
}

/**
 * Dispose one idle per-directory engine instance without the reload path's
 * post-refresh sync: re-materializing the instance here would defeat the
 * eviction. The workspace's MCP registration evidence is invalidated first so
 * nothing claims the fresh instance already holds the runtime-DB MCPs; the
 * reaper marks the workspace and the next traffic re-attaches that state.
 */
async function disposeIdleEngineInstance(
  config: ServerConfig,
  serverState: EngineMcpServerState,
  instance: TrackedEngineInstance,
): Promise<void> {
  const primary = primaryManagedEngineConnection(config);
  if (!primary || primary.baseUrl !== instance.engineBaseUrl) {
    throw new Error("The managed engine connection is unavailable for the instance dispose");
  }
  const activeState = activeEngineMcpServerState(config, serverState);
  if (activeState) invalidateEngineMcpWorkspace(activeState, instance.workspaceId);
  const response = await loopbackFetch(buildOpencodeReloadUrl(primary.baseUrl, instance.directory), {
    method: "POST",
    headers: { Authorization: buildEngineAuthProbeHeader(primary.username, primary.password) },
    signal: AbortSignal.timeout(opencodeDisposeTimeoutMs()),
  });
  if (!response.ok) throw new Error(`OmniRush instance dispose failed with status ${response.status}`);
}

/**
 * Before a local workspace is removed: abort its running sessions and, on the
 * engines this server manages, dispose its per-folder instance, so no agent
 * run, tool process, file watcher or open handle keeps writing into the
 * folder (and bringing it back after the person deletes it) or keeps it
 * locked on Windows. Bounded; a failure never blocks the removal.
 */
async function stopWorkspaceEngineWork(config: ServerConfig, workspace: WorkspaceInfo): Promise<void> {
  const directory = resolveOpencodeDirectory(workspace);
  if (!directory) return;
  const pool = enginePoolForConfig(config);
  const connection = pool ? null : resolveWorkspaceOpencodeConnection(config, workspace);
  const targets: EngineRequestTarget[] = pool
    ? pool.connections().map((entry) => ({
        baseUrl: entry.baseUrl,
        headers: new Headers({ Authorization: buildEngineAuthProbeHeader(entry.username, entry.password) }),
      }))
    : connection?.baseUrl?.trim()
      ? [{ baseUrl: connection.baseUrl.trim(), headers: new Headers(connection.authHeader ? { Authorization: connection.authHeader } : {}) }]
      : [];
  await Promise.all(targets.map(async (target) => {
    const statuses = await engineJson(target, "/session/status", directory).catch(() => null);
    const busy = isRecord(statuses)
      ? Object.entries(statuses).flatMap(([id, status]) => isRecord(status) && status.type !== "idle" ? [id] : [])
      : [];
    await Promise.all(busy.map((id) =>
      engineJson(target, `/session/${encodeURIComponent(id)}/abort`, directory, { method: "POST" }).catch(() => null),
    ));
    if (!pool) return;
    await loopbackFetch(buildOpencodeReloadUrl(target.baseUrl, directory), {
      method: "POST",
      headers: target.headers,
      signal: AbortSignal.timeout(Math.min(opencodeDisposeTimeoutMs(), 2 * SESSION_STOP_TIMEOUT_MS)),
    }).then((response) => response.body?.cancel()).catch((error: unknown) => {
      createServerLogger(config).log("warn", "Engine instance dispose for a removed workspace failed.", {
        "workspace.id": workspace.id,
        "error.message": error instanceof Error ? error.message : String(error),
      });
    });
  }));
  const mcpState = activeEngineMcpServerState(config);
  if (mcpState) invalidateEngineMcpWorkspace(mcpState, workspace.id);
}

/**
 * Record engine traffic for a local workspace's directory instance. When this
 * is the first traffic after that instance was evicted, re-attach the state a
 * fresh instance cannot recover from disk (the runtime-DB MCP push), detached
 * from the request that triggered it.
 */
function touchEngineWorkspaceInstance(config: ServerConfig, workspace: WorkspaceInfo, engineBaseUrl: string): void {
  if (workspace.workspaceType === "remote") return;
  const reaper = engineInstanceReaperForConfig(config);
  if (!reaper) return;
  const directory = resolveOpencodeDirectory(workspace);
  if (!directory) return;
  const evicted = reaper.noteUsed({ directory, workspaceId: workspace.id, engineBaseUrl });
  if (!evicted) return;
  void postEngineRefreshSync(config, workspace, activeEngineMcpServerState(config)).catch((error) => {
    createServerLogger(config).log("error", "Post-eviction engine MCP re-sync failed.", {
      "workspace.id": workspace.id,
      "error.message": error instanceof Error ? error.message : String(error),
    });
  });
}

/**
 * Bring the engine onto current config.
 *
 * Managed engines always reload through the rollover pool: an idle engine
 * still reloads in place, a busy one rolls over to a standby so live runs are
 * not aborted. Attached engines have no pool, so this falls back to the
 * in-place dispose and callers keep their own defer-while-busy handling.
 */
async function reloadOpencodeEngine(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  serverState?: EngineMcpServerState,
  options?: { awaitPostRefreshSync?: boolean; forceStandby?: boolean; reason?: RolloverReason; manual?: boolean },
): Promise<void> {
  const pool = enginePoolForConfig(config);
  if (pool) {
    await pool.requestRollover({
      reason: options?.reason ?? "engine_reload",
      workspace,
      awaitPostRefreshSync: options?.awaitPostRefreshSync,
      forceStandby: options?.forceStandby,
      // User-initiated reloads must bypass the fingerprint guard: skill files
      // are not part of the runtime fingerprint, so an unchanged fingerprint
      // would otherwise turn "Reload" into a no-op after editing a skill.
      manual: options?.manual === true,
    });
    return;
  }
  await reloadOpencodeEngineInPlace(config, workspace, serverState, options);
}

async function reloadOpencodeEngineInPlace(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  serverState?: EngineMcpServerState,
  options?: { awaitPostRefreshSync?: boolean },
): Promise<void> {
  const activeState = activeEngineMcpServerState(config, serverState);
  if (activeState) invalidateEngineMcpWorkspace(activeState, workspace.id);
  const connection = resolveWorkspaceOpencodeConnection(config, workspace);
  const baseUrl = connection.baseUrl?.trim() ?? "";
  if (!baseUrl) {
    throw new ApiError(400, "opencode_unconfigured", "OmniRush base URL is missing for this workspace");
  }

  const directory = resolveOpencodeDirectory(workspace);
  const targetUrl = buildOpencodeReloadUrl(baseUrl, directory);
  const headers: Record<string, string> = {};
  const auth = connection.authHeader ?? null;
  if (auth) headers.Authorization = auth;

  let response: Response;
  try {
    // OpenCode reload targets the managed loopback engine; CA trust is irrelevant.
    // The engine answers /instance/dispose only AFTER teardown completes, so a
    // dispose wedged on live-session teardown would otherwise hang forever.
    response = await loopbackFetch(targetUrl, {
      method: "POST",
      headers,
      signal: AbortSignal.timeout(opencodeDisposeTimeoutMs()),
    });
  } catch (error) {
    if (error instanceof Error && error.name === "TimeoutError") {
      // Deliberately NOT opencode_engine_unreachable: the app escalates that
      // code to a full desktop engine restart, which would kill the very
      // sessions the wedged dispose is still tearing down.
      throw new ApiError(
        504,
        "opencode_reload_timeout",
        "OmniRush dispose did not complete in time; the reload stays pending",
        { baseUrl },
      );
    }
    throw new ApiError(
      503,
      "opencode_engine_unreachable",
      "OmniRush engine is not reachable; a full engine restart is required",
      { baseUrl, cause: error instanceof Error ? error.message : String(error) },
    );
  }
  if (!response.ok) {
    const body = parseOpencodeErrorBody(await response.text());
    throw new ApiError(502, "opencode_reload_failed", "OmniRush reload failed", {
      status: response.status,
      body,
    });
  }

  // The reload rebuilt this directory's instance and the post-refresh sync
  // below re-attaches its runtime state, so any pending post-eviction mark is
  // satisfied here rather than by the next request.
  if (directory && workspace.workspaceType !== "remote") {
    engineInstanceReaperForConfig(config)?.noteUsed({ directory, workspaceId: workspace.id, engineBaseUrl: baseUrl });
  }

  const postRefreshSync = postEngineRefreshSync(config, workspace, activeState);
  if (options?.awaitPostRefreshSync === false) {
    void postRefreshSync.catch((error) => {
      logDetachedPostEngineRefreshSyncError({ config, workspace, error });
    });
    return;
  }
  await postRefreshSync;
}

/**
 * Re-attach engine state that a fresh instance cannot recover from disk.
 *
 * Runs after any engine refresh — an in-place dispose or a rollover flip —
 * because both leave the serving engine without the runtime-DB MCPs that only
 * reach it through the dynamic push.
 */
async function postEngineRefreshSync(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  activeState: EngineMcpServerState | undefined,
): Promise<void> {
  const directory = resolveOpencodeDirectory(workspace);
  markOmniRushCloudMcpStale(workspace, directory);
  return enqueueWorkspaceMcpRefreshSync({
    config,
    workspace,
    serverState: activeState,
    trigger: "engine_reload",
  });
}

type WorkspaceMcpRefreshTrigger = "startup" | "engine_reload" | "workspace_activate";

type WorkspaceMcpRefreshRequest = {
  config: ServerConfig;
  workspace: WorkspaceInfo;
  serverState: EngineMcpServerState | undefined;
  trigger: WorkspaceMcpRefreshTrigger;
};

function enqueueWorkspaceMcpRefreshSync(request: WorkspaceMcpRefreshRequest): Promise<void> {
  const state = activeEngineMcpServerState(request.config, request.serverState);
  if (!state) return runWorkspaceMcpRefreshSync(request);
  return state.refreshSyncQueue.enqueue(request.workspace.id, request);
}

async function runWorkspaceMcpRefreshSync(input: WorkspaceMcpRefreshRequest): Promise<void> {
  const { config, workspace, trigger } = input;
  // The project's app-added MCP entries go to the file the engine's MCP plugin
  // reads. The account-linked Connect server is never reconciled (not run here).
  try {
    await syncRuntimeMcpToOpencodeEngine(
      config,
      workspace,
      undefined,
      undefined,
      input.serverState ?? null,
    );
  } catch (error) {
    logRuntimeMcpSyncError({ config, workspace, trigger, error });
  }
  // The reconcile above may write the ENGINE_GLOBAL runtime row; refresh the
  // engine-visible file synchronously so the next provider-sync pass compares
  // against post-reload state instead of racing the async fresh-keeper and
  // reporting a phantom "changed" (which would schedule yet another reload).
  try {
    if (trigger === "engine_reload") {
      await writeOmniRushRuntimeConfigFile(config);
    }
  } catch {
    // Best-effort: the fresh-keeper listener still converges eventually.
  }
}

// Push runtime-DB MCP entries into the running OpenCode engine via its dynamic
// add endpoint, so adds/toggles take effect without waiting for an engine
// instance rebuild. Best-effort: callers treat engine sync as advisory and
// swallow failures; outcomes are recorded per workspace (engineMcpSyncState)
// and logged so failures aren't silent.
async function syncRuntimeMcpToOpencodeEngine(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  onlyNames?: string[],
  options?: { throwOnFailure?: boolean; deferred?: boolean },
  serverState?: EngineMcpServerState | null,
): Promise<EngineMcpSyncResult> {
  // Nothing is pushed into a running engine: every MCP server goes through the
  // engine's MCP plugin (the server's list), which reads the project's
  // app-added entries from this file when the project's instance starts.
  await writeWorkspaceMcpFile(config, workspace);
  const state = activeEngineMcpServerState(config, serverState);
  const recordedNames = (state ? [...(state.registrationByWorkspace.get(workspace.id)?.keys() ?? [])] : [])
    .filter((name) => !onlyNames || onlyNames.includes(name));
  // Registrations an earlier push made (never by this version) are taken down.
  await Promise.all(recordedNames.map(async (name) => {
    if (state) deleteEngineMcpRegistration(config, state, workspace, name);
    await disconnectMcpFromOpencodeEngine(config, workspace, name).catch(() => undefined);
  }));
  return { status: "skipped", syncedNames: [], failures: [] };
}

/** The project's app-added MCP entries (runtime row) for the engine's MCP plugin. */
async function writeWorkspaceMcpFile(config: ServerConfig, workspace: WorkspaceInfo): Promise<void> {
  if (workspace.workspaceType === "remote") return;
  const runtimeConfig = await readRuntimeOpencodeConfig(config, workspace.id).catch(() => ({}) as RuntimeOpencodeConfig);
  const entries = Object.fromEntries(Object.entries(runtimeMcpMap(runtimeConfig))
    .filter(([name, entry]) => !name.startsWith(CONNECT_MCP_SERVER_NAME_PREFIX) && name !== OMNIRUSH_CLOUD_MCP_NAME && !isOmniRushUiMcpRegistryEntry(entry)));
  try {
    writeWorkspaceMcp(runtimeStorageDir(config), resolveOpencodeDirectory(workspace) || workspace.path, entries);
  } catch (error) {
    createServerLogger(config).log("warn", "Could not write the project's MCP servers for the engine.", {
      "workspace.id": workspace.id,
      error: error instanceof Error ? error.message : String(error),
    });
  }
}

/**
 * The engine's own MCP routes through the proxy: reading the list and
 * connecting or disconnecting a configured server are fine; adding a server
 * at runtime (it would skip the list) or its OAuth flow are not.
 */
function assertEngineMcpRouteAllowed(config: ServerConfig, method: string, routePath: string): void {
  // Config writes through the engine (the project's or the user's global
  // file) could add servers outside Settings > MCP; the app never uses them.
  if (method !== "GET" && method !== "HEAD" && /^(?:\/api)?\/(?:global\/)?config\/?$/.test(routePath.split("?")[0] ?? "")) {
    throw new ApiError(403, "engine_config_private", "Engine configuration is private");
  }
  const match = /^(?:\/api)?\/mcp(?:\/(.*))?$/.exec(routePath.split("?")[0] ?? "");
  if (!match) return;
  if (method === "GET" || method === "HEAD") return;
  const rest = match[1] ?? "";
  if (/^[^/]+\/(?:connect|disconnect)\/?$/.test(rest)) {
    assertMcpAllowed(config);
    return;
  }
  const auth = /^([^/]+)\/auth(?:\/|$)/.exec(rest);
  if (auth) {
    // The one account sign-in the list allows: a remote server on it that signs in with OAuth (Figma's), by
    // its id (the engine plugin keys it so); the engine keeps the tokens in its own store, not in a config.
    let name = "";
    try { name = decodeURIComponent(auth[1] ?? ""); } catch { refuseAccountLinkedMcp(); }
    if (mcpSignInAllowed(config, name)) return;
    refuseAccountLinkedMcp();
  }
  throw new ApiError(403, "engine_mcp_managed", "Add MCP servers in Settings > MCP: only the supported servers run.");
}

/** Whether `name` is a remote server on the list that signs in with OAuth. */
export function mcpSignInAllowed(config: ServerConfig, name: string): boolean {
  if (!mcpAllowed(config)) return false;
  const policy = currentMcpPolicy(runtimeStorageDir(config));
  return Boolean(policy?.allow.some((entry) => entry.runtime === "remote" && entry.oauth === true && entry.id === name));
}

/** A supported server as a one-click preset: what it is, and the command it adds. */
function mcpPreset(entry: McpAllowEntry): { id: string; title: string; why: string | null; runtime: string; package: string; version: string | null; versions: string; command: string[]; localPagesOnly: boolean; url: string | null; oauth: boolean; setup: string | null; account: boolean } {
  const account = { url: entry.url ?? null, oauth: entry.oauth === true, setup: entry.setup ?? null, account: Boolean(entry.setup) };
  if (entry.runtime === "remote") {
    return { id: entry.id, title: entry.title, why: entry.why, runtime: entry.runtime, package: entry.package, version: null, versions: entry.versions, command: [], localPagesOnly: false, ...account };
  }
  // The file a database server needs is a placeholder in the project: data.db.
  const placeholder = /sqlite|db/i.test(`${entry.id} ${entry.package}`) ? "data.db" : ".";
  const args: string[] = [...(entry.rules.default_args ?? [])];
  for (const flag of entry.rules.require_flags ?? []) {
    if (args.includes(flag)) continue;
    args.push(flag, placeholder);
  }
  while (args.filter((arg) => !arg.startsWith("-")).length < (entry.rules.min_args ?? 0)) args.push(placeholder);
  const command = entry.runtime === "npm" ? ["npx", "-y", entry.package, ...args] : ["uvx", entry.package, ...args];
  return {
    id: entry.id,
    title: entry.title,
    why: entry.why,
    runtime: entry.runtime,
    package: entry.package,
    version: entry.pin,
    versions: entry.versions,
    command,
    localPagesOnly: entry.rules.local_urls === true,
    ...account,
  };
}

async function withEngineMcpRegistrationLock<Result>(
  state: EngineMcpServerState,
  workspaceId: string,
  operation: () => Promise<Result>,
): Promise<Result> {
  const previous = state.registrationTailByWorkspace.get(workspaceId) ?? Promise.resolve();
  let release: () => void = () => undefined;
  const turn = new Promise<void>((resolve) => {
    release = resolve;
  });
  const tail = previous.then(() => turn);
  state.registrationTailByWorkspace.set(workspaceId, tail);
  await previous;
  try {
    return await operation();
  } finally {
    release();
    if (state.registrationTailByWorkspace.get(workspaceId) === tail) {
      state.registrationTailByWorkspace.delete(workspaceId);
    }
  }
}

// Reuse verified clients and fence necessary replacements against local prompt
// admission. A health observation alone is not proof of config delivery.
async function registerRuntimeMcpEntry(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  url: URL,
  headers: Record<string, string>,
  name: string,
  mcpConfig: Record<string, unknown>,
): Promise<EngineMcpRegistrationResult> {
  // Explicit disabling still takes effect immediately.
  if (mcpConfig.enabled === false) return postMcpEntryWithRetry(config, workspace, url, headers, name, mcpConfig);
  try {
    const response = await loopbackFetch(url, { headers, signal: AbortSignal.timeout(5_000) });
    if (!response.ok) throw new Error("MCP status probe failed");
    const statuses: unknown = JSON.parse(await readBoundedEngineMcpRegistrationResponse(response));
    if (!isRecord(statuses)) throw new Error("Invalid MCP status response");
    const live = statuses[name];
    if (isRecord(live) && live.status === "connected") {
      const recorded = inspectEngineMcpRegistrationDetails(config, workspace, name, mcpConfig);
      const receipt = activeEngineMcpServerState(config)?.registrationByWorkspace.get(workspace.id)?.get(name);
      if (recorded.status === "connected" && receipt?.configDelivered) {
        // OpenCode's add endpoint replaces and closes even an unchanged client.
        // Keep the client already captured by a model turn or in-flight tool.
        return { name, status: "connected", source: "engine_status", errorSummary: null, failure: null };
      }
      const activityUrl = new URL(url);
      activityUrl.pathname = "/session/status";
      const activity = await loopbackFetch(activityUrl, { headers, signal: AbortSignal.timeout(5_000) });
      if (!activity.ok) throw new Error("Session activity probe failed");
      const sessions: unknown = JSON.parse(await readBoundedEngineMcpRegistrationResponse(activity));
      if (!isRecord(sessions)) throw new Error("Invalid session activity response");
      if (Object.values(sessions).some((session) => !isRecord(session) || session.type !== "idle")) {
        // The directory fence also covers prompt admission, so a task cannot
        // start between this activity check and replacing its client's tools.
        return {
          name, status: "failed", source: "transport_failure", errorSummary: null,
          failure: { name, status: 503, deferredForActivity: true, message: "MCP replacement deferred until active tasks finish" },
        };
      }
    }
  } catch {
    // Unknown liveness must not turn a background refresh into a destructive
    // replacement. Let the existing deferred-sync path retry the probe.
    return {
      name, status: "failed", source: "transport_failure", errorSummary: null,
      failure: { name, status: 503, message: "Could not verify MCP connection activity before registration" },
    };
  }
  return postMcpEntryWithRetry(config, workspace, url, headers, name, mcpConfig);
}

// POST one MCP entry to the engine, retrying once on 5xx/network errors.
async function postMcpEntryWithRetry(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  url: URL,
  headers: Record<string, string>,
  name: string,
  mcpConfig: Record<string, unknown>,
): Promise<EngineMcpRegistrationResult> {
  let failure: EngineMcpSyncFailure | null = null;
  for (let attempt = 0; attempt < 2; attempt += 1) {
    if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, engineMcpSyncRetryDelayMs()));
    try {
      // Runtime MCP registration targets the managed loopback engine.
      const response = await loopbackFetch(url, {
        method: "POST",
        headers,
        body: JSON.stringify({ name, config: mcpConfig }),
        signal: AbortSignal.timeout(15_000),
      });
      enginePoolForConfig(config)?.reportRequestSuccess(url.origin);
      if (response.ok) {
        // OpenCode's dynamic registration endpoint historically treats every
        // 2xx response as accepted delivery and Cloud readiness verifies the
        // actual state by polling GET /mcp. Parse the response only as optional
        // diagnostics evidence: an absent or malformed status must fail closed
        // to `not-recorded` without turning accepted delivery into a failure.
        const registration = await parseEngineMcpRegistrationStatus(response, name);
        return {
          name,
          status: registration.status,
          source: registration.status ? "engine_status" : null,
          errorSummary: registration.errorSummary,
          failure: null,
        };
      }
      await response.body?.cancel().catch(() => undefined);
      failure = {
        name,
        status: response.status,
        registrationStatus: "failed",
        message: "OmniRush rejected the MCP registration request",
      };
      if (response.status < 500) return { name, status: "failed", source: "transport_failure", errorSummary: null, failure };
    } catch (error) {
      enginePoolForConfig(config)?.reportRequestFailure(url.origin, error, workspace);
      failure = {
        name,
        registrationStatus: "failed",
        message: "OmniRush MCP registration request failed",
      };
    }
  }
  return {
    name,
    status: "failed",
    source: "transport_failure",
    errorSummary: null,
    failure: failure ?? {
      name,
      registrationStatus: "failed",
      message: "OmniRush MCP registration request failed",
    },
  };
}

const ENGINE_MCP_REGISTRATION_RESPONSE_MAX_BYTES = 64 * 1024;

export type EngineMcpRegistrationStatus =
  | "connected"
  | "disabled"
  | "failed"
  | "needs-auth"
  | "needs-client-registration";
export type EngineMcpRegistrationSource = "transport_failure" | "engine_status";

export type EngineMcpRegistrationInspection = {
  status: EngineMcpRegistrationStatus | "not-recorded";
  source: EngineMcpRegistrationSource | null;
  recordAgeMs: number | null;
  errorSummary: string | null;
};

type EngineMcpRegistrationResult = {
  name: string;
  status: EngineMcpRegistrationStatus | null;
  source: EngineMcpRegistrationSource | null;
  errorSummary: string | null;
  failure: EngineMcpSyncFailure | null;
};

type ParsedEngineMcpRegistrationStatus = {
  status: EngineMcpRegistrationStatus | null;
  errorSummary: string | null;
};

type EngineMcpDeferredSync = {
  timer: ReturnType<typeof setTimeout>;
  connectionIdentity: string;
  generation: number;
  onlyNames?: string[];
};

async function parseEngineMcpRegistrationStatus(
  response: Response,
  name: string,
): Promise<ParsedEngineMcpRegistrationStatus> {
  let text: string;
  try {
    text = await readBoundedEngineMcpRegistrationResponse(response);
  } catch {
    return { status: null, errorSummary: null };
  }

  let body: unknown;
  try {
    body = JSON.parse(text) as unknown;
  } catch {
    return { status: null, errorSummary: null };
  }
  if (!isRecord(body) || !Object.hasOwn(body, name)) return { status: null, errorSummary: null };
  const entry = body[name];
  if (!isRecord(entry)) return { status: null, errorSummary: null };
  const status = normalizeEngineMcpRegistrationStatus(entry.status);
  return {
    status,
    errorSummary: sanitizeEngineMcpRegistrationErrorSummary(entry.error, status),
  };
}

function sanitizeEngineMcpRegistrationErrorSummary(
  error: unknown,
  status: EngineMcpRegistrationStatus | null,
): string | null {
  if (status !== "failed" && status !== "needs-client-registration") return null;
  if (typeof error !== "string") return null;
  const sanitized = sanitizeDiagnosticString(error).trim().slice(0, 400);
  return sanitized || null;
}

function normalizeEngineMcpRegistrationStatus(status: unknown): EngineMcpRegistrationStatus | null {
  switch (status) {
    case "connected":
    case "disabled":
    case "failed":
      return status;
    case "needs_auth":
      return "needs-auth";
    case "needs_client_registration":
      return "needs-client-registration";
    default:
      return null;
  }
}

async function readBoundedEngineMcpRegistrationResponse(response: Response): Promise<string> {
  const contentLength = response.headers.get("content-length");
  if (contentLength !== null) {
    const parsedLength = Number(contentLength);
    if (Number.isFinite(parsedLength) && parsedLength > ENGINE_MCP_REGISTRATION_RESPONSE_MAX_BYTES) {
      await response.body?.cancel().catch(() => undefined);
      throw new Error("OmniRush MCP registration response exceeded the size limit");
    }
  }
  if (!response.body) return "";

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  const chunks: string[] = [];
  let bytesRead = 0;
  try {
    while (true) {
      const chunk = await reader.read();
      if (chunk.done) break;
      bytesRead += chunk.value.byteLength;
      if (bytesRead > ENGINE_MCP_REGISTRATION_RESPONSE_MAX_BYTES) {
        await reader.cancel().catch(() => undefined);
        throw new Error("OmniRush MCP registration response exceeded the size limit");
      }
      chunks.push(decoder.decode(chunk.value, { stream: true }));
    }
    chunks.push(decoder.decode());
    return chunks.join("");
  } finally {
    reader.releaseLock();
  }
}

// Read lazily so tests can shrink the delay at runtime.
function engineMcpSyncRetryDelayMs(): number {
  const parsed = Number(process.env.OMNIRUSH_MCP_SYNC_RETRY_DELAY_MS ?? "750");
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : 750;
}

function engineMcpDeferredSyncDelayMs(): number {
  const parsed = Number(process.env.OMNIRUSH_MCP_SYNC_DEFERRED_DELAY_MS ?? "12000");
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : 12_000;
}

function hasRetryableMcpSyncFailure(failures: EngineMcpSyncFailure[]): boolean {
  return failures.some((failure) => failure.status === undefined || failure.status >= 500);
}

function cancelDeferredEngineMcpSync(state: EngineMcpServerState, workspaceId: string): void {
  const previous = state.deferredSyncByWorkspace.get(workspaceId);
  if (!previous) return;
  clearTimeout(previous.timer);
  state.deferredSyncByWorkspace.delete(workspaceId);
}

function scheduleDeferredEngineMcpSync(input: {
  config: ServerConfig;
  state: EngineMcpServerState;
  workspace: WorkspaceInfo;
  connectionIdentity: string;
  onlyNames?: string[];
}): void {
  cancelDeferredEngineMcpSync(input.state, input.workspace.id);
  const generation = input.state.generation;
  const onlyNames = input.onlyNames ? [...input.onlyNames] : undefined;
  const timer = setTimeout(() => {
    const state = activeEngineMcpServerState(input.config, input.state);
    if (!state || state.generation !== generation) return;
    const current = state.deferredSyncByWorkspace.get(input.workspace.id);
    if (!current || current.generation !== generation) return;
    state.deferredSyncByWorkspace.delete(input.workspace.id);
    if (engineMcpConnectionIdentity(input.config, input.workspace) !== input.connectionIdentity) return;
    if (state.syncStateByWorkspace.get(input.workspace.id)?.status === "ok") return;
    createServerLogger(input.config).log(
      "info",
      `Running deferred engine MCP sync for workspace ${input.workspace.id}.`,
      { "workspace.id": input.workspace.id },
    );
    void syncRuntimeMcpToOpencodeEngine(
      input.config,
      input.workspace,
      current.onlyNames,
      { throwOnFailure: false, deferred: true },
      state,
    ).catch((error) => {
      createServerLogger(input.config).log(
        "warn",
        `Deferred engine MCP sync failed for workspace ${input.workspace.id}.`,
        {
          "workspace.id": input.workspace.id,
          "mcp.failure.code": "deferred_runtime_mcp_sync_failed",
          "mcp.failure.message": error instanceof Error ? error.message : String(error),
        },
      );
    });
  }, engineMcpDeferredSyncDelayMs());
  input.state.deferredSyncByWorkspace.set(input.workspace.id, {
    timer,
    connectionIdentity: input.connectionIdentity,
    generation,
    ...(onlyNames ? { onlyNames } : {}),
  });
}

export type EngineMcpSyncFailure = {
  name: string;
  status?: number;
  deferredForActivity?: boolean;
  registrationStatus?: EngineMcpRegistrationStatus;
  message?: string;
};
export type EngineMcpSyncResult = {
  status: "ok" | "failed" | "skipped";
  syncedNames: string[];
  failures: EngineMcpSyncFailure[];
};
export type EngineMcpSyncState = { status: "ok" | "failed"; at: number; failures: EngineMcpSyncFailure[] };

type EngineMcpRegistrationRecord = {
  fingerprint: string;
  configDelivered: boolean;
  status: EngineMcpRegistrationStatus;
  source: EngineMcpRegistrationSource;
  errorSummary: string | null;
  registrationIdentity: string;
  generation: number;
  recordedAt: number;
};

type TrustedOpencodeProcessIdentity = {
  endpoint: string;
  identityHash: string;
  generation: number;
  isAlive: () => boolean;
};

type EngineMcpServerState = {
  generation: number;
  syncStateByWorkspace: Map<string, EngineMcpSyncState>;
  refreshSyncQueue: LatestTrailingWorkQueue<string, WorkspaceMcpRefreshRequest>;
  registrationTailByWorkspace: Map<string, Promise<void>>;
  registrationByWorkspace: Map<string, Map<string, EngineMcpRegistrationRecord>>;
  engineIdentityByWorkspace: Map<string, string>;
  deferredSyncByWorkspace: Map<string, EngineMcpDeferredSync>;
};

const ENGINE_MCP_REGISTRATION_MAX_AGE_MS = 15 * 60_000;
// Registration status is point-in-time evidence from a dynamic POST /mcp,
// not a durable statement about a later engine process. Scope it to one
// OmniRush.ai server generation and expire it even when the endpoint is stable.
const engineMcpServerStateByConfig = new WeakMap<ServerConfig, EngineMcpServerState>();
const trustedOpencodeProcessByConfig = new WeakMap<ServerConfig, TrustedOpencodeProcessIdentity>();
let nextEngineMcpServerGeneration = 0;
let nextTrustedOpencodeProcessGeneration = 0;

function normalizedOpencodeProcessEndpoint(baseUrl: string): string | null {
  try {
    const url = new URL(baseUrl);
    url.pathname = "/global/health";
    url.search = "";
    url.hash = "";
    return url.toString();
  } catch {
    return null;
  }
}

function clearEngineMcpServerEvidence(state: EngineMcpServerState): void {
  for (const deferred of state.deferredSyncByWorkspace.values()) clearTimeout(deferred.timer);
  state.syncStateByWorkspace.clear();
  state.registrationByWorkspace.clear();
  state.engineIdentityByWorkspace.clear();
  state.deferredSyncByWorkspace.clear();
}

/**
 * Bind diagnostics evidence to one OpenCode process generation owned by this
 * OmniRush.ai server. The opaque identity is hashed immediately and never
 * reported. External engines without a trusted per-boot identity still hot
 * sync normally, but their cached registration result cannot authorize a
 * credentialed diagnostics probe.
 */
export function registerTrustedOpencodeProcess(
  config: ServerConfig,
  input: { baseUrl: string; identity: string; isAlive: () => boolean },
): void {
  const endpoint = normalizedOpencodeProcessEndpoint(input.baseUrl.trim());
  const identity = input.identity.trim();
  if (!endpoint || !identity) {
    clearTrustedOpencodeProcess(config);
    return;
  }
  const previous = trustedOpencodeProcessByConfig.get(config);
  const identityHash = hashToken(identity);
  const next: TrustedOpencodeProcessIdentity = {
    endpoint,
    identityHash,
    generation: previous?.endpoint === endpoint && previous.identityHash === identityHash
      ? previous.generation
      : ++nextTrustedOpencodeProcessGeneration,
    isAlive: input.isAlive,
  };
  if (previous?.endpoint !== next.endpoint || previous.identityHash !== next.identityHash) {
    const state = engineMcpServerStateByConfig.get(config);
    if (state) clearEngineMcpServerEvidence(state);
  }
  trustedOpencodeProcessByConfig.set(config, next);
}

/**
 * Build the engine pool for a config and register it.
 *
 * Lives here so the pool can reuse server-private helpers (in-place reload,
 * busy probe, post-refresh MCP sync) without exporting them; the startup path
 * only supplies what it already knows about the spawn.
 */
export function createEnginePoolForConfig(input: {
  config: ServerConfig;
  template: EngineSpawnTemplate;
  handle: Parameters<EnginePool["adoptPrimary"]>[0]["handle"];
  fingerprint: string;
  registryId: string | null;
  trustedIdentity: string | null;
}): EnginePool {
  const { config } = input;
  const logger = createServerLogger(config);
  // Thread approvals live in OmniRush.ai because the engine forgets an "always"
  // reply whenever this pool rebuilds an instance or rolls over.
  let threadApprovals: ThreadApprovalReplayer | null = null;
  const pool = new EnginePool({
    config,
    template: input.template,
    hooks: {
      onDisposed: () => threadApprovals?.stop(),
      reloadInPlace: (poolConfig, workspace, options) =>
        reloadOpencodeEngineInPlace(poolConfig, workspace, undefined, options),
      engineBusy: (poolConfig, workspace) => engineHasActiveSessions(poolConfig, workspace, true),
      onPrimaryLost: (poolConfig) => requeueTaskRecoveryAfterEngineLoss(poolConfig),
      // Turn observers still reading a closed engine read the sessions from the one that took over.
      onEngineReplaced: (closedBaseUrl, replacement) => {
        captureServicesByServer.get(config)?.engineReplaced(closedBaseUrl, {
          baseUrl: replacement.baseUrl,
          authorization: buildEngineAuthProbeHeader(replacement.username, replacement.password),
        });
      },
      postRefreshSync: async (poolConfig, workspace) => {
        await postEngineRefreshSync(poolConfig, workspace, activeEngineMcpServerState(poolConfig));
        await syncAllWorkspacesRuntimeMcpToEngine(poolConfig);
      },
      prepareStandby: async (poolConfig, standby) => {
        const env = envServiceForConfig(poolConfig);
        if (!env) return;
        const result = await syncManagedProviderAuth({
          config: poolConfig,
          env,
          logger: toManagedProviderAuthLogger(logger),
          target: standby,
        });
        logger.log("info", "Engine standby seeded with managed provider credentials.", {
          "engine.rollover.generation": standby.generationId,
          "provider.auth.delivered": result.delivered.length,
          "provider.auth.skipped": result.skipped.length,
          "provider.auth.failed": result.failed.length,
        });
      },
      writeRuntimeConfigFile: (poolConfig) => writeOmniRushRuntimeConfigFile(poolConfig),
      registerTrusted: (poolConfig, generation) => registerTrustedOpencodeProcess(poolConfig, generation),
      clearTrusted: (poolConfig, identity) => clearTrustedOpencodeProcess(poolConfig, identity),
      logger,
    },
  });
  pool.adoptPrimary({
    handle: input.handle,
    fingerprint: input.fingerprint,
    registryId: input.registryId,
    trustedIdentity: input.trustedIdentity,
  });
  setEnginePoolForConfig(config, pool);
  threadApprovals = startThreadApprovalReplayer({
    config,
    primary: () => pool.connections().find((entry) => entry.role === "primary") ?? null,
    // The engine reports an instance by its canonical path (macOS resolves
    // /tmp and /var through /private), so compare canonical forms.
    workspaceIdForDirectory: async (directory) => {
      const reported = await realpath(normalizeOpencodeDirectory(directory)).catch(() => normalizeOpencodeDirectory(directory));
      for (const workspace of config.workspaces) {
        const owned = resolveOpencodeDirectory(workspace);
        if (!owned) continue;
        if (owned === reported || (await realpath(owned).catch(() => owned)) === reported) return workspace.id;
      }
      return null;
    },
    logger,
  });
  return pool;
}

export function clearTrustedOpencodeProcess(config: ServerConfig, expectedIdentity?: string): void {
  const current = trustedOpencodeProcessByConfig.get(config);
  if (!current) return;
  if (expectedIdentity && current.identityHash !== hashToken(expectedIdentity.trim())) return;
  trustedOpencodeProcessByConfig.delete(config);
  const state = engineMcpServerStateByConfig.get(config);
  if (state) clearEngineMcpServerEvidence(state);
}

function beginEngineMcpServerState(config: ServerConfig): EngineMcpServerState {
  const previous = engineMcpServerStateByConfig.get(config);
  const refreshSyncQueue = previous?.refreshSyncQueue ?? new LatestTrailingWorkQueue(
    runWorkspaceMcpRefreshSync,
    (workspaceId, error) => {
      createServerLogger(config).log("error", `Workspace MCP refresh queue crashed for ${workspaceId}.`, {
        "workspace.id": workspaceId,
        "mcp.failure.code": "workspace_mcp_refresh_queue_exception",
        "mcp.failure.message": error instanceof Error ? error.message : String(error),
      });
    },
  );
  const registrationTailByWorkspace = previous?.registrationTailByWorkspace ?? new Map<string, Promise<void>>();
  if (previous) invalidateEngineMcpServerState(config, previous);
  const state: EngineMcpServerState = {
    generation: ++nextEngineMcpServerGeneration,
    syncStateByWorkspace: new Map(),
    refreshSyncQueue,
    registrationTailByWorkspace,
    registrationByWorkspace: new Map(),
    engineIdentityByWorkspace: new Map(),
    deferredSyncByWorkspace: new Map(),
  };
  engineMcpServerStateByConfig.set(config, state);
  return state;
}

function activeEngineMcpServerState(
  config: ServerConfig,
  candidate?: EngineMcpServerState | null,
): EngineMcpServerState | undefined {
  if (candidate === null) return undefined;
  const active = engineMcpServerStateByConfig.get(config);
  if (!active || (candidate && active !== candidate)) return undefined;
  return candidate ?? active;
}

function invalidateEngineMcpServerState(config: ServerConfig, state: EngineMcpServerState): void {
  clearEngineMcpServerEvidence(state);
  if (engineMcpServerStateByConfig.get(config) === state) {
    engineMcpServerStateByConfig.delete(config);
  }
}

function invalidateEngineMcpWorkspace(state: EngineMcpServerState, workspaceId: string): void {
  const deferred = state.deferredSyncByWorkspace.get(workspaceId);
  if (deferred) clearTimeout(deferred.timer);
  state.syncStateByWorkspace.delete(workspaceId);
  state.registrationByWorkspace.delete(workspaceId);
  state.engineIdentityByWorkspace.delete(workspaceId);
  state.deferredSyncByWorkspace.delete(workspaceId);
}

function reconcileEngineMcpWorkspaceIdentity(
  state: EngineMcpServerState,
  workspaceId: string,
  engineIdentity: string | null,
): void {
  const previous = state.engineIdentityByWorkspace.get(workspaceId);
  if (!engineIdentity) {
    invalidateEngineMcpWorkspace(state, workspaceId);
    return;
  }
  if (previous && previous !== engineIdentity) {
    invalidateEngineMcpWorkspace(state, workspaceId);
  }
  state.engineIdentityByWorkspace.set(workspaceId, engineIdentity);
}

function engineMcpRegistrationMaxAgeMs(): number {
  const configured = Number(process.env.OMNIRUSH_MCP_REGISTRATION_MAX_AGE_MS);
  if (!Number.isFinite(configured) || configured < 1) return ENGINE_MCP_REGISTRATION_MAX_AGE_MS;
  return Math.min(ENGINE_MCP_REGISTRATION_MAX_AGE_MS, Math.round(configured));
}

const MCP_REGISTRATION_FINGERPRINT_MAX_DEPTH = 32;
const MCP_REGISTRATION_FINGERPRINT_MAX_NODES = 10_000;

function hasBoundedMcpRegistrationStructure(value: unknown): boolean {
  const stack: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];
  const visited = new Set<object>();
  let nodes = 0;
  try {
    while (stack.length > 0) {
      const current = stack.pop();
      if (!current) break;
      nodes += 1;
      if (nodes > MCP_REGISTRATION_FINGERPRINT_MAX_NODES) return false;
      if (current.depth > MCP_REGISTRATION_FINGERPRINT_MAX_DEPTH) return false;
      if (typeof current.value !== "object" || current.value === null) continue;
      if (visited.has(current.value)) return false;
      visited.add(current.value);
      const children = Array.isArray(current.value)
        ? current.value
        : Object.values(current.value);
      for (const child of children) {
        stack.push({ value: child, depth: current.depth + 1 });
      }
    }
    return true;
  } catch {
    return false;
  }
}

function serializeStableMcpRegistrationValue(value: unknown): string {
  if (Array.isArray(value)) {
    return `[${value.map(serializeStableMcpRegistrationValue).join(",")}]`;
  }
  if (isRecord(value)) {
    return `{${Object.entries(value)
      .sort(([left], [right]) => left.localeCompare(right))
      .map(([key, child]) => `${JSON.stringify(key)}:${serializeStableMcpRegistrationValue(child)}`)
      .join(",")}}`;
  }
  return JSON.stringify(value) ?? "null";
}

function stableMcpRegistrationValue(value: unknown): string | null {
  if (!hasBoundedMcpRegistrationStructure(value)) return null;
  try {
    return serializeStableMcpRegistrationValue(value);
  } catch {
    return null;
  }
}

function mcpRegistrationFingerprint(config: Record<string, unknown>): string | null {
  const stableValue = stableMcpRegistrationValue(config);
  return stableValue === null ? null : hashToken(stableValue);
}

function engineMcpConnectionIdentity(config: ServerConfig, workspace: WorkspaceInfo): string | null {
  const connection = resolveWorkspaceOpencodeConnection(config, workspace);
  const baseUrl = connection.baseUrl?.trim() ?? "";
  if (!baseUrl) return null;
  try {
    const url = new URL(baseUrl);
    url.pathname = "/mcp";
    url.search = "";
    url.hash = "";
    const directory = resolveOpencodeDirectory(workspace);
    if (directory) url.searchParams.set("directory", directory);
    const stableIdentity = stableMcpRegistrationValue({
      endpoint: url.toString(),
      authorization: connection.authHeader ?? null,
    });
    return stableIdentity === null ? null : hashToken(stableIdentity);
  } catch {
    return null;
  }
}

function trustedOpencodeProcessIdentity(config: ServerConfig, workspace: WorkspaceInfo): string | null {
  const trusted = trustedOpencodeProcessByConfig.get(config);
  if (!trusted) return null;

  let isAlive = false;
  try {
    isAlive = trusted.isAlive();
  } catch {
    isAlive = false;
  }
  if (!isAlive) {
    clearTrustedOpencodeProcess(config);
    return null;
  }

  const connection = resolveWorkspaceOpencodeConnection(config, workspace);
  const endpoint = normalizedOpencodeProcessEndpoint(connection.baseUrl?.trim() ?? "");
  if (!endpoint || endpoint !== trusted.endpoint) return null;

  const stableIdentity = stableMcpRegistrationValue({
    generation: trusted.generation,
    identityHash: trusted.identityHash,
  });
  return stableIdentity === null ? null : hashToken(stableIdentity);
}

function engineMcpRegistrationIdentity(config: ServerConfig, workspace: WorkspaceInfo): string | null {
  const connectionIdentity = engineMcpConnectionIdentity(config, workspace);
  const processIdentity = trustedOpencodeProcessIdentity(config, workspace);
  if (!connectionIdentity || !processIdentity) return null;
  const stableIdentity = stableMcpRegistrationValue({ connectionIdentity, processIdentity });
  return stableIdentity === null ? null : hashToken(stableIdentity);
}

function recordEngineMcpSyncResult(
  config: ServerConfig,
  serverState: EngineMcpServerState | null,
  workspace: WorkspaceInfo,
  connectionIdentity: string,
  registrationIdentity: string | null,
  result: {
    entries: Array<[string, Record<string, unknown>]>;
    registrations?: EngineMcpRegistrationResult[];
    failures: EngineMcpSyncFailure[];
    replace: boolean;
  },
): void {
  const state = activeEngineMcpServerState(config, serverState);
  if (!state) return;
  const currentConnectionIdentity = engineMcpConnectionIdentity(config, workspace);
  if (currentConnectionIdentity !== connectionIdentity) {
    invalidateEngineMcpWorkspace(state, workspace.id);
    return;
  }
  reconcileEngineMcpWorkspaceIdentity(state, workspace.id, connectionIdentity);
  const currentRegistrationIdentity = engineMcpRegistrationIdentity(config, workspace);
  // The liveness check above can revoke trust and clear the state. Restore the
  // transport identity before recording the non-sensitive sync outcome.
  reconcileEngineMcpWorkspaceIdentity(state, workspace.id, connectionIdentity);
  const workspaceId = workspace.id;
  const syncedNames = result.entries.map(([name]) => name);
  const previous = state.syncStateByWorkspace.get(workspaceId);
  // Partial syncs (onlyNames) shouldn't clear recorded failures for entries
  // they didn't touch; merge by name instead.
  const remaining = result.replace
    ? []
    : (previous?.failures ?? []).filter((failure) => !syncedNames.includes(failure.name));
  const merged = [...remaining, ...result.failures];
  const recordedAt = Date.now();
  state.syncStateByWorkspace.set(workspaceId, {
    status: merged.length > 0 ? "failed" : "ok",
    at: recordedAt,
    failures: merged,
  });

  if (!registrationIdentity || currentRegistrationIdentity !== registrationIdentity) {
    state.registrationByWorkspace.delete(workspaceId);
    return;
  }

  const registrations = result.replace
    ? new Map<string, EngineMcpRegistrationRecord>()
    : new Map(state.registrationByWorkspace.get(workspaceId) ?? []);
  const registrationByName = new Map(result.registrations?.map((registration) => [registration.name, registration]));
  for (const [name, mcpConfig] of result.entries) {
    const fingerprint = mcpRegistrationFingerprint(mcpConfig);
    const registration = registrationByName.get(name);
    if (fingerprint === null || !registration?.status || !registration.source) {
      registrations.delete(name);
      continue;
    }
    registrations.set(name, {
      fingerprint,
      configDelivered: registration.failure === null,
      status: registration.status,
      source: registration.source,
      errorSummary: registration.errorSummary,
      registrationIdentity,
      generation: state.generation,
      recordedAt,
    });
  }
  state.registrationByWorkspace.set(workspaceId, registrations);
}

function engineMcpSyncStateInState(
  config: ServerConfig,
  serverState: EngineMcpServerState,
  workspace: WorkspaceInfo,
): EngineMcpSyncState | null {
  const state = activeEngineMcpServerState(config, serverState);
  if (!state) return null;
  const engineIdentity = engineMcpConnectionIdentity(config, workspace);
  reconcileEngineMcpWorkspaceIdentity(state, workspace.id, engineIdentity);
  if (!engineIdentity) return null;
  return state.syncStateByWorkspace.get(workspace.id) ?? null;
}

function inspectEngineMcpRegistrationInState(
  config: ServerConfig,
  serverState: EngineMcpServerState,
  workspace: WorkspaceInfo,
  name: string,
  mcpConfig: Record<string, unknown>,
): EngineMcpRegistrationInspection {
  const state = activeEngineMcpServerState(config, serverState);
  if (!state) return notRecordedEngineMcpRegistration();
  const connectionIdentity = engineMcpConnectionIdentity(config, workspace);
  reconcileEngineMcpWorkspaceIdentity(state, workspace.id, connectionIdentity);
  if (!connectionIdentity) return notRecordedEngineMcpRegistration();
  const registrationIdentity = engineMcpRegistrationIdentity(config, workspace);
  if (!registrationIdentity) {
    state.registrationByWorkspace.delete(workspace.id);
    return notRecordedEngineMcpRegistration();
  }
  const registrations = state.registrationByWorkspace.get(workspace.id);
  const registration = registrations?.get(name);
  if (!registration) return notRecordedEngineMcpRegistration();
  const currentFingerprint = mcpRegistrationFingerprint(mcpConfig);
  const ageMs = Date.now() - registration.recordedAt;
  if (
    registration.generation !== state.generation
    || registration.registrationIdentity !== registrationIdentity
    || !Number.isFinite(ageMs)
    || ageMs < 0
    || ageMs > engineMcpRegistrationMaxAgeMs()
    || currentFingerprint === null
    || registration.fingerprint !== currentFingerprint
  ) {
    registrations?.delete(name);
    return notRecordedEngineMcpRegistration();
  }
  return {
    status: registration.status,
    source: registration.source,
    recordAgeMs: Math.round(ageMs),
    errorSummary: registration.errorSummary,
  };
}

function notRecordedEngineMcpRegistration(): EngineMcpRegistrationInspection {
  return { status: "not-recorded", source: null, recordAgeMs: null, errorSummary: null };
}

export function inspectEngineMcpRegistration(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  name: string,
  mcpConfig: Record<string, unknown>,
): EngineMcpRegistrationStatus | "not-recorded" {
  return inspectEngineMcpRegistrationDetails(config, workspace, name, mcpConfig).status;
}

export function inspectEngineMcpRegistrationDetails(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  name: string,
  mcpConfig: Record<string, unknown>,
): EngineMcpRegistrationInspection {
  const state = activeEngineMcpServerState(config);
  if (!state) return notRecordedEngineMcpRegistration();
  return inspectEngineMcpRegistrationInState(config, state, workspace, name, mcpConfig);
}

export function refreshEngineMcpRegistrationFromLiveStatus(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  name: string,
  mcpConfig: Record<string, unknown>,
  liveStatus: unknown,
  liveError: unknown = null,
): boolean {
  const status = normalizeEngineMcpRegistrationStatus(liveStatus);
  if (!status) return false;
  const state = activeEngineMcpServerState(config);
  if (!state) return false;
  const connectionIdentity = engineMcpConnectionIdentity(config, workspace);
  reconcileEngineMcpWorkspaceIdentity(state, workspace.id, connectionIdentity);
  if (!connectionIdentity) return false;
  const registrationIdentity = engineMcpRegistrationIdentity(config, workspace);
  if (!registrationIdentity) {
    state.registrationByWorkspace.delete(workspace.id);
    return false;
  }
  const fingerprint = mcpRegistrationFingerprint(mcpConfig);
  if (fingerprint === null) {
    state.registrationByWorkspace.get(workspace.id)?.delete(name);
    return false;
  }
  const registrations = new Map(state.registrationByWorkspace.get(workspace.id) ?? []);
  const previous = registrations.get(name);
  registrations.set(name, {
    fingerprint,
    // A health probe observes status, not the engine's effective credentials.
    // It must not manufacture a delivery receipt for a changed desired config.
    configDelivered: previous?.configDelivered === true
      && previous.fingerprint === fingerprint
      && previous.registrationIdentity === registrationIdentity
      && previous.generation === state.generation,
    status,
    source: "engine_status",
    errorSummary: sanitizeEngineMcpRegistrationErrorSummary(liveError, status),
    registrationIdentity,
    generation: state.generation,
    recordedAt: Date.now(),
  });
  state.registrationByWorkspace.set(workspace.id, registrations);
  return true;
}

function deleteEngineMcpRegistration(
  config: ServerConfig,
  serverState: EngineMcpServerState,
  workspace: WorkspaceInfo,
  name: string,
): void {
  const state = activeEngineMcpServerState(config, serverState);
  if (!state) return;
  reconcileEngineMcpWorkspaceIdentity(state, workspace.id, engineMcpConnectionIdentity(config, workspace));
  state.registrationByWorkspace.get(workspace.id)?.delete(name);
}

function logPersistedCloudMcpReconcileResult(input: {
  config: ServerConfig;
  workspace: WorkspaceInfo;
  trigger: WorkspaceMcpRefreshTrigger;
  health: CloudMcpHealth;
}): void {
  if (!input.health.desired.present || input.health.usable) return;
  const failure = input.health.firstFailure;
  createServerLogger(input.config).log(
    "warn",
    `Cloud MCP ${input.trigger} reconciliation left connected service tools unavailable for workspace ${input.workspace.id}.`,
    {
      "workspace.id": input.workspace.id,
      "mcp.name": "omnirush-cloud",
      "mcp.trigger": input.trigger,
      "mcp.failure.code": failure?.code ?? "unknown",
      "mcp.failure.stage": failure?.stage ?? "unknown",
      "mcp.failure.retryable": failure?.retryable ?? null,
      "mcp.failure.message": failure?.message ?? "Cloud MCP health remained unusable after reconciliation.",
    },
  );
}

function logRuntimeMcpSyncError(input: {
  config: ServerConfig;
  workspace: WorkspaceInfo;
  trigger: WorkspaceMcpRefreshTrigger;
  error: unknown;
}): void {
  createServerLogger(input.config).log(
    "error",
    `Runtime MCP ${input.trigger} sync crashed for workspace ${input.workspace.id}.`,
    {
      "workspace.id": input.workspace.id,
      "mcp.trigger": input.trigger,
      "mcp.failure.code": "runtime_mcp_sync_exception",
      "mcp.failure.message": input.error instanceof Error ? input.error.message : String(input.error),
    },
  );
}

function logDetachedPostEngineRefreshSyncError(input: {
  config: ServerConfig;
  workspace: WorkspaceInfo;
  error: unknown;
}): void {
  createServerLogger(input.config).log(
    "error",
    `Detached post-refresh MCP sync crashed for workspace ${input.workspace.id}.`,
    {
      "workspace.id": input.workspace.id,
      "mcp.trigger": "engine_reload",
      "mcp.failure.code": "detached_post_refresh_sync_exception",
      "mcp.failure.message": input.error instanceof Error ? input.error.message : String(input.error),
    },
  );
}

function logPersistedCloudMcpReconcileError(input: {
  config: ServerConfig;
  workspace: WorkspaceInfo;
  trigger: WorkspaceMcpRefreshTrigger;
  error: unknown;
}): void {
  createServerLogger(input.config).log(
    "error",
    `Cloud MCP ${input.trigger} reconciliation crashed for workspace ${input.workspace.id}.`,
    {
      "workspace.id": input.workspace.id,
      "mcp.name": "omnirush-cloud",
      "mcp.trigger": input.trigger,
      "mcp.failure.code": "cloud_mcp_reconcile_exception",
      "mcp.failure.message": input.error instanceof Error ? input.error.message : String(input.error),
    },
  );
}

// Re-push every workspace's runtime-DB MCPs into the engine. Used at startup:
// the runtime config file injected via OPENCODE_CONFIG covers workspaces[0]
// only, so other workspaces' runtime MCPs are invisible to the engine until
// something re-syncs them. Best-effort.
export async function syncAllWorkspacesRuntimeMcpToEngine(config: ServerConfig): Promise<void> {
  await migrateOmniRushCloudMcpRuntimeConfig(config);
  await migrateWorkspaceRuntimeConfigToEngineGlobal(config);
  const serverState = activeEngineMcpServerState(config);
  for (const workspace of config.workspaces) {
    await enqueueWorkspaceMcpRefreshSync({ config, workspace, serverState, trigger: "startup" });
  }
}

// Counterpart of syncRuntimeMcpToOpencodeEngine for removals: tell the engine
// to drop the MCP's client so deleted MCPs stop serving tools immediately
// instead of lingering until the next engine restart. Best-effort.
async function disconnectMcpFromOpencodeEngine(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  name: string,
): Promise<void> {
  const connection = resolveWorkspaceOpencodeConnection(config, workspace);
  const baseUrl = connection.baseUrl?.trim() ?? "";
  if (!baseUrl) return;

  const url = new URL(baseUrl);
  url.pathname = `/mcp/${encodeURIComponent(name)}/disconnect`;
  url.search = "";
  const directory = resolveOpencodeDirectory(workspace);
  if (directory) url.searchParams.set("directory", directory);
  const headers: Record<string, string> = {};
  if (connection.authHeader) headers.Authorization = connection.authHeader;

  // MCP disconnect targets the managed loopback engine.
  const response = await loopbackFetch(url, { method: "POST", headers, signal: AbortSignal.timeout(15_000) });
  if (!response.ok) {
    const body = parseOpencodeErrorBody(await response.text());
    throw new ApiError(502, "opencode_mcp_disconnect_failed", `Failed to disconnect MCP ${name} from the engine`, {
      status: response.status,
      body,
    });
  }
}

async function readEngineMcpNames(
  config: ServerConfig,
  workspace: WorkspaceInfo,
): Promise<string[]> {
  const connection = resolveWorkspaceOpencodeConnection(config, workspace);
  const baseUrl = connection.baseUrl?.trim() ?? "";
  if (!baseUrl) return [];
  const url = new URL(baseUrl);
  url.pathname = "/mcp";
  url.search = "";
  const directory = resolveOpencodeDirectory(workspace);
  if (directory) url.searchParams.set("directory", directory);
  const headers: Record<string, string> = {};
  if (connection.authHeader) headers.Authorization = connection.authHeader;
  const response = await loopbackFetch(url, { headers, signal: AbortSignal.timeout(10_000) });
  if (!response.ok) return [];
  const payload: unknown = await response.json().catch(() => null);
  const values = isRecord(payload) && Array.isArray(payload.data)
    ? payload.data
    : isRecord(payload)
      ? Object.entries(payload).map(([name, status]) => ({ name, status }))
      : [];
  return values.flatMap((entry) => {
    if (!isRecord(entry) || typeof entry.name !== "string" || !entry.name.trim()) return [];
    return [entry.name];
  });
}

async function requireApproval(
  ctx: RequestContext,
  input: Omit<ApprovalRequest, "id" | "createdAt" | "actor">,
): Promise<void> {
  const actor = ctx.actor ?? { type: "remote" };
  const result = await ctx.approvals.requestApproval({ ...input, actor });
  if (!result.allowed) {
    throw new ApiError(403, "write_denied", "Write request denied", {
      requestId: result.id,
      reason: result.reason,
    });
  }
}

async function exportWorkspace(
  config: ServerConfig,
  workspace: WorkspaceInfo,
  options?: { sensitiveMode?: WorkspaceExportSensitiveMode },
) {
  const sensitiveMode = options?.sensitiveMode ?? "auto";
  const rawOpencode = await readOpencodeConfig(workspace.path);
  let opencode = sanitizePortableOpencodeConfig(rawOpencode);
  const omnirush = sanitizeOmniRushTemplateConfig(await readOmniRushConfigForWorkspace(config, workspace));
  const skills = await listSkills(workspace.path, false);
  const commands = await listCommands(workspace.path, "workspace");
  let files = await listPortableFiles(workspace.path);
  const warnings = collectWorkspaceExportWarnings({ opencode: rawOpencode, files });
  if (warnings.length && sensitiveMode === "auto") {
    throw new ApiError(
      409,
      "workspace_export_requires_decision",
      "This workspace includes sensitive config. Choose whether to exclude it or include it before exporting.",
      { warnings },
    );
  }
  if (sensitiveMode === "exclude") {
    const sanitized = stripSensitiveWorkspaceExportData({ opencode, files });
    opencode = sanitized.opencode;
    files = sanitized.files;
  }
  const skillContents = await Promise.all(
    skills.map(async (skill) => ({
      name: skill.name,
      description: skill.description,
      content: await readFile(skill.path, "utf8"),
    })),
  );
  const commandContents = await Promise.all(
    commands.map(async (command) => ({
      name: command.name,
      description: command.description,
      template: command.template,
    })),
  );

  return {
    workspaceId: workspace.id,
    exportedAt: Date.now(),
    opencode,
    omnirush,
    skills: skillContents,
    commands: commandContents,
    ...(files.length ? { files } : {}),
  };
}

function parseWorkspaceExportSensitiveMode(input: string | null): WorkspaceExportSensitiveMode {
  const trimmed = (input ?? "").trim();
  if (!trimmed) return "auto";
  if (trimmed === "auto" || trimmed === "include" || trimmed === "exclude") {
    return trimmed;
  }
  throw new ApiError(400, "invalid_workspace_export_sensitive_mode", `Invalid workspace export sensitive mode: ${trimmed}`);
}

/**
 * The capture policy a chat's uploads keep, in its pin at its first prompt
 * (the uploader's settled policy, after its startSession); a strict-session
 * bind sends it. Without a capture service nothing of the chat is uploaded:
 * "none". Unsettled (null): the pin waits for the next prompt. Never holds the
 * prompt up: under enforce a model request before it is pinned gets a
 * retryable local error and goes once it is.
 */
async function pinChatCapturePolicy(config: ServerConfig, capture: CaptureService | undefined, sessionId: string): Promise<void> {
  const boxes = boxServiceFor(config);
  if (boxes.chatPin(sessionId)?.capturePolicy) return;
  const policy = capture ? await capture.sessionPolicy(sessionId).catch(() => null) : "none";
  if (policy) await boxes.setCapturePolicy(sessionId, policy);
}

/** A chat that started in the box, when the box cannot run now (it never moves to this computer). */
function pinnedBoxMessage(why: string): string {
  return `This chat runs in the sandbox, which can't start right now (${why.replace(/\.$/, "")}). Try again, or start a new chat.`;
}

/**
 * Whether a prompt request names an omnirush.ai model whose new chats start on
 * this computer and cannot be switched: the server's local_box.model_start
 * when it says (start "native", not switchable), else the catalog `modes`
 * without "box" (Kimi). Such a chat is exempt from the box
 * (box/service.ts beforePrompt).
 */
async function promptsNativeOnlyModel(config: ServerConfig, body: string | ArrayBuffer | undefined): Promise<boolean> {
  if (body === undefined) return false;
  let parsed: unknown;
  try {
    parsed = JSON.parse(typeof body === "string" ? body : new TextDecoder().decode(body));
  } catch {
    return false;
  }
  const model = isRecord(parsed) && isRecord(parsed.model) ? parsed.model : null;
  if (!model || model.providerID !== "omnirush" || typeof model.modelID !== "string") return false;
  const start = serverModelStart(serverLocalBox(runtimeStorageDir(config)), model.modelID);
  if (start) return start.start === "native" && !start.switchable;
  const entry = (await readOmniRushModelCatalog(config)).find((candidate) => candidate.id === model.modelID);
  return Boolean(entry?.modes) && !modelAllowedIn(entry, "box") && modelAllowedIn(entry, "native");
}