Skip to content

A desktop coding agent with free access to frontier models.

TypeScript
24.5 KB
Raw Blame
import { readFile } from "node:fs/promises";
import { basename, dirname, resolve } from "node:path";
import { recordAudit } from "../audit.js";
import { ApiError } from "../errors.js";
import { writeFileAtomic } from "../atomic-write.js";
import { inheritWorkspaceOpencodeConnection, resolveWorkspaceOpencodeConnection } from "../opencode-connection.js";
import { externalFetch } from "../server-fetch.js";
import type { ServerConfig, WorkspaceInfo } from "../types.js";
import { ensureDir, exists, shortId } from "../utils.js";
import { defaultWorkspaceOmniRushConfig, ensureWorkspaceFiles } from "../workspace-init.js";
import { seedOmniRushWorkspaceConfigIfEmpty } from "../omnirush-workspace-config-store.js";
import { workspaceIdForPath, workspaceIdForRemote } from "../workspaces.js";
import { directoryMatchKey } from "../session-list-fallback.js";
import { addRoute, type RequestContext, type Route } from "./registry.js";

type JsonResponse = (data: unknown, status?: number) => Response;
type ReadJsonBody = (request: Request) => Promise<Record<string, unknown>>;
type ParseOptionalBoolean = (value: string | null, name: string) => boolean | undefined;

interface RegisterWorkspaceRoutesOptions {
  routes: Route[];
  config: ServerConfig;
  onWorkspacesChanged: () => void;
  jsonResponse: JsonResponse;
  readJsonBody: ReadJsonBody;
  readOptionalJsonBody: ReadJsonBody;
  parseOptionalBoolean: ParseOptionalBoolean;
  ensureWritable: (config: ServerConfig) => void;
  resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;
  serializeWorkspace: (workspace: ServerConfig["workspaces"][number]) => unknown;
  /**
   * Dispose-free re-attach of the workspace's runtime MCPs via the engine's
   * dynamic push. The injected engine config file is workspace-independent,
   * so activation never reloads or disposes an engine instance.
   */
  syncWorkspaceRuntimeMcp: (config: ServerConfig, workspace: WorkspaceInfo) => Promise<void>;
  /**
   * Stops everything that may still write into a workspace being removed: its
   * running sessions are aborted and its engine instance (file watcher, tool
   * processes, open handles) is released. Best effort; never throws.
   */
  stopWorkspaceWork?: (config: ServerConfig, workspace: WorkspaceInfo) => Promise<void>;
  /** A local workspace was added or made active: its sandbox starts now, in the background (box/service.ts opened). */
  onWorkspaceOpened?: (config: ServerConfig, workspace: WorkspaceInfo) => void;
}

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

function readStringField(value: unknown, key: string): string {
  if (!isRecord(value)) return "";
  const field = value[key];
  return typeof field === "string" ? field.trim() : "";
}

function normalizeRemoteDirectory(value: unknown): string {
  if (typeof value !== "string") return "";
  return value.trim().replace(/\\/g, "/").replace(/\/+$/, "");
}

function parseOmniRushWorkspaceIdFromUrl(input: string | null | undefined): string | null {
  const raw = input?.trim() ?? "";
  if (!raw) return null;
  try {
    const url = new URL(raw);
    const segments = url.pathname.split("/").filter(Boolean);
    const workspaceIndex = segments.indexOf("workspace");
    const legacyIndex = segments.indexOf("w");
    const mountIndex = workspaceIndex >= 0 ? workspaceIndex : legacyIndex;
    return mountIndex >= 0 && segments[mountIndex + 1]
      ? decodeURIComponent(segments[mountIndex + 1])
      : null;
  } catch {
    const match = raw.match(/\/(?:workspace|w)\/([^/?#]+)/);
    if (!match?.[1]) return null;
    try {
      return decodeURIComponent(match[1]);
    } catch {
      return match[1];
    }
  }
}

function stripOmniRushWorkspaceMount(input: string | null | undefined): string | null {
  const raw = input?.trim() ?? "";
  if (!raw) return null;
  try {
    const url = new URL(raw);
    const segments = url.pathname.split("/").filter(Boolean);
    const workspaceIndex = segments.indexOf("workspace");
    const legacyIndex = segments.indexOf("w");
    const mountIndex = workspaceIndex >= 0 ? workspaceIndex : legacyIndex;
    if (mountIndex >= 0 && segments[mountIndex + 1]) {
      const prefix = segments.slice(0, mountIndex).join("/");
      url.pathname = prefix ? `/${prefix}` : "/";
    }
    return url.toString().replace(/\/+$/, "");
  } catch {
    return raw.replace(/\/(?:workspace|w)\/[^/?#]+.*$/, "").replace(/\/+$/, "") || raw;
  }
}

function omnirushRemoteWorkspaceId(hostUrl: string, workspaceId: string | null | undefined): string {
  const remoteWorkspaceId = workspaceId?.trim() || parseOmniRushWorkspaceIdFromUrl(hostUrl);
  return remoteWorkspaceId ? `rem_${remoteWorkspaceId}` : workspaceIdForRemote(hostUrl, null);
}

function workspaceDirectoryCandidates(workspace: Record<string, unknown>): string[] {
  const opencode = isRecord(workspace.opencode) ? workspace.opencode : {};
  return [workspace.directory, workspace.path, opencode.directory]
    .map(normalizeRemoteDirectory)
    .filter(Boolean);
}

function selectOmniRushWorkspaceForConnection(list: unknown, directory: string | null): Record<string, unknown> | null {
  if (!isRecord(list)) return null;
  const rawItems = Array.isArray(list.items)
    ? list.items
    : Array.isArray(list.workspaces)
      ? list.workspaces
      : [];
  const items = rawItems.filter(isRecord);
  if (!items.length) return null;

  const expectedDirectory = normalizeRemoteDirectory(directory);
  if (expectedDirectory) {
    return items.find((item) => workspaceDirectoryCandidates(item).includes(expectedDirectory)) ?? null;
  }

  const activeId = readStringField(list, "activeId");
  return (activeId ? items.find((item) => readStringField(item, "id") === activeId) : null) ?? items[0] ?? null;
}

function omnirushWorkspaceDisplayName(workspace: Record<string, unknown>): string | null {
  return readStringField(workspace, "displayName")
    || readStringField(workspace, "omnirushWorkspaceName")
    || readStringField(workspace, "name")
    || readStringField(workspace, "id")
    || null;
}

async function fetchOmniRushWorkspaceList(hostUrl: string, token: string, hostToken: string): Promise<unknown> {
  const url = `${hostUrl.replace(/\/+$/, "")}/workspaces`;
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), 8_000);
  const headers = new Headers();
  if (token) headers.set("Authorization", `Bearer ${token}`);
  if (hostToken) headers.set("X-OmniRush-Host-Token", hostToken);

  try {
    const response = await externalFetch(url, { headers, signal: controller.signal });
    if (!response.ok) {
      throw new ApiError(
        502,
        "omnirush_workspace_discovery_failed",
        `OmniRush.ai workspace discovery failed (${response.status} ${response.statusText || "HTTP error"})`,
      );
    }
    return await response.json();
  } catch (error) {
    if (error instanceof ApiError) throw error;
    throw new ApiError(502, "omnirush_workspace_discovery_failed", "OmniRush.ai workspace discovery failed", {
      error: String(error),
    });
  } finally {
    clearTimeout(timeout);
  }
}

async function discoverOmniRushWorkspace(input: {
  hostUrl: string;
  token: string;
  hostToken: string;
  directory: string | null;
}): Promise<Record<string, unknown> | null> {
  const list = await fetchOmniRushWorkspaceList(input.hostUrl, input.token, input.hostToken);
  return selectOmniRushWorkspaceForConnection(list, input.directory);
}

function ensurePlainObject(value: unknown): Record<string, unknown> {
  if (!isRecord(value)) return {};
  return value;
}

async function readServerConfigFile(configPath: string): Promise<Record<string, unknown>> {
  if (!(await exists(configPath))) {
    return {};
  }

  try {
    const raw = await readFile(configPath, "utf8");
    return ensurePlainObject(JSON.parse(raw));
  } catch (error) {
    throw new ApiError(422, "invalid_json", "Failed to parse server config", {
      path: configPath,
      error: String(error),
    });
  }
}

function serializeWorkspaceConfigEntry(workspace: WorkspaceInfo): Record<string, unknown> {
  const isLocalWorkspace = workspace.workspaceType !== "remote";
  return {
    id: workspace.id,
    path: workspace.path,
    name: workspace.name,
    preset: workspace.preset,
    workspaceType: workspace.workspaceType,
    ...(workspace.remoteType ? { remoteType: workspace.remoteType } : {}),
    ...(!isLocalWorkspace && workspace.baseUrl ? { baseUrl: workspace.baseUrl } : {}),
    ...(!isLocalWorkspace && workspace.directory ? { directory: workspace.directory } : {}),
    ...(workspace.displayName ? { displayName: workspace.displayName } : {}),
    ...(workspace.omnirushHostUrl ? { omnirushHostUrl: workspace.omnirushHostUrl } : {}),
    ...(workspace.omnirushToken ? { omnirushToken: workspace.omnirushToken } : {}),
    ...(workspace.omnirushWorkspaceId ? { omnirushWorkspaceId: workspace.omnirushWorkspaceId } : {}),
    ...(workspace.omnirushWorkspaceName ? { omnirushWorkspaceName: workspace.omnirushWorkspaceName } : {}),
    ...(workspace.sandboxBackend ? { sandboxBackend: workspace.sandboxBackend } : {}),
    ...(workspace.sandboxRunId ? { sandboxRunId: workspace.sandboxRunId } : {}),
    ...(workspace.sandboxContainerName ? { sandboxContainerName: workspace.sandboxContainerName } : {}),
    ...(!isLocalWorkspace && workspace.opencodeUsername ? { opencodeUsername: workspace.opencodeUsername } : {}),
    ...(!isLocalWorkspace && workspace.opencodePassword ? { opencodePassword: workspace.opencodePassword } : {}),
    ...(workspace.task ? { task: workspace.task } : {}),
  };
}

async function persistServerWorkspaceState(config: ServerConfig): Promise<boolean> {
  const configPath = config.configPath?.trim() ?? "";
  if (!configPath) return false;

  const parsed = await readServerConfigFile(configPath);
  const next = {
    ...parsed,
    workspaces: config.workspaces.map(serializeWorkspaceConfigEntry),
    authorizedRoots: Array.from(new Set(config.authorizedRoots.map((root) => resolve(root)))),
  };

  await ensureDir(dirname(configPath));
  // Retried while Windows (antivirus, indexer, a concurrent reader) holds
  // the file for a moment: a registry change must not be lost to that.
  await writeFileAtomic(configPath, `${JSON.stringify(next, null, 2)}\n`);
  return true;
}

/**
 * Registers a local folder as a workspace (the POST /workspaces/local flow):
 * its runtime config row, its authorized root, the saved registry and the
 * audit line. The caller announces the change (onWorkspacesChanged).
 */
export async function addLocalWorkspace(
  config: ServerConfig,
  input: { folderPath: string; name: string; preset: string; actor?: RequestContext["actor"]; task?: WorkspaceInfo["task"]; platform?: NodeJS.Platform },
): Promise<{ workspace: WorkspaceInfo; persisted: boolean }> {
  const { preset } = input;
  // Another spelling of a folder already added (letter case on Windows and macOS, as a trailing slash
  // anywhere) is that workspace: a second one for the same folder hangs its chats.
  const requested = resolve(input.folderPath);
  const existing = config.workspaces.find((entry) => entry.workspaceType !== "remote" && entry.path
    && directoryMatchKey(entry.path, input.platform) === directoryMatchKey(requested, input.platform));
  const workspacePath = existing?.path ?? requested;
  const name = existing?.name ?? input.name;
  await ensureDir(workspacePath);
  await ensureWorkspaceFiles(workspacePath, preset);

  const workspaceId = existing?.id ?? workspaceIdForPath(workspacePath);
  // Seed the per-workspace omnirush config in the runtime DB (replaces the
  // legacy `.opencode/omnirush.json` file). No-op if a row already exists.
  await seedOmniRushWorkspaceConfigIfEmpty(
    config,
    workspaceId,
    defaultWorkspaceOmniRushConfig(workspacePath, preset),
  );

  const workspace: WorkspaceInfo = {
    id: workspaceId,
    name,
    path: workspacePath,
    preset,
    workspaceType: "local",
    ...inheritWorkspaceOpencodeConnection(config),
    ...(input.task ? { task: input.task } : {}),
  };

  config.workspaces = [workspace, ...config.workspaces.filter((entry) => entry.id !== workspace.id)];
  if (!config.authorizedRoots.some((root) => resolve(root) === workspacePath)) {
    config.authorizedRoots = [...config.authorizedRoots, workspacePath];
  }
  const persisted = await persistServerWorkspaceState(config);

  await recordAudit(workspace.path, {
    id: shortId(),
    workspaceId: workspace.id,
    actor: input.actor ?? { type: "host" },
    action: "workspace.create",
    target: workspace.path,
    summary: `Created workspace ${name}`,
    timestamp: Date.now(),
  });
  return { workspace, persisted };
}

/** Removes a local workspace from the registry (not its folder); the caller announces the change. */
export async function forgetLocalWorkspace(config: ServerConfig, workspaceId: string): Promise<boolean> {
  const workspace = config.workspaces.find((entry) => entry.id === workspaceId);
  if (!workspace) return false;
  config.workspaces = config.workspaces.filter((entry) => entry.id !== workspaceId);
  config.authorizedRoots = config.authorizedRoots.filter((root) => resolve(root) !== resolve(workspace.path));
  await persistServerWorkspaceState(config);
  return true;
}

export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions): void {
  const {
    routes,
    config,
    onWorkspacesChanged,
    jsonResponse,
    readJsonBody,
    readOptionalJsonBody,
    parseOptionalBoolean,
    ensureWritable,
    resolveWorkspace,
    serializeWorkspace,
    syncWorkspaceRuntimeMcp,
    onWorkspaceOpened,
  } = options;

  const resolveWorkspaceForRegistry = async (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, path: workspace.path?.trim() ?? "" };
    }
    return resolveWorkspace(config, id);
  };

  addRoute(routes, "POST", "/workspaces/local", "host", async (ctx) => {
    ensureWritable(config);
    const body = await readJsonBody(ctx.request);
    const folderPath = typeof body.folderPath === "string" ? body.folderPath.trim() : "";
    const name = typeof body.name === "string" && body.name.trim() ? body.name.trim() : basename(folderPath || "Workspace");
    const preset = typeof body.preset === "string" && body.preset.trim() ? body.preset.trim() : "starter";

    if (!folderPath) {
      throw new ApiError(400, "invalid_payload", "folderPath is required");
    }

    const { workspace, persisted } = await addLocalWorkspace(config, { folderPath, name, preset, actor: ctx.actor });
    onWorkspacesChanged();
    onWorkspaceOpened?.(config, workspace);

    return jsonResponse({
      activeId: workspace.id,
      workspaces: config.workspaces.map(serializeWorkspace),
      persisted,
    }, 201);
  });

  addRoute(routes, "POST", "/workspaces/remote", "host", async (ctx) => {
    ensureWritable(config);
    const body = await readJsonBody(ctx.request);
    const baseUrl = readStringField(body, "baseUrl");
    if (!baseUrl) {
      throw new ApiError(400, "invalid_payload", "baseUrl is required");
    }
    if (!/^https?:\/\//i.test(baseUrl)) {
      throw new ApiError(400, "invalid_payload", "baseUrl must start with http:// or https://");
    }

    const remoteType = readStringField(body, "remoteType") === "opencode" ? "opencode" : "omnirush";
    const directory = readStringField(body, "directory") || null;
    const displayName = readStringField(body, "displayName") || null;
    const rawOmniRushHostUrl = readStringField(body, "omnirushHostUrl") || null;
    const omnirushHostUrl = remoteType === "omnirush"
      ? stripOmniRushWorkspaceMount(rawOmniRushHostUrl ?? baseUrl)
      : rawOmniRushHostUrl;
    const omnirushToken = readStringField(body, "omnirushToken");
    const omnirushHostToken = readStringField(body, "omnirushHostToken");
    const sandboxBackend = readStringField(body, "sandboxBackend");
    const sandboxRunId = readStringField(body, "sandboxRunId");
    const sandboxContainerName = readStringField(body, "sandboxContainerName");
    let omnirushWorkspaceId = remoteType === "omnirush"
      ? readStringField(body, "omnirushWorkspaceId")
        || parseOmniRushWorkspaceIdFromUrl(rawOmniRushHostUrl)
        || parseOmniRushWorkspaceIdFromUrl(baseUrl)
      : "";
    let omnirushWorkspaceName = readStringField(body, "omnirushWorkspaceName") || null;

    if (remoteType === "omnirush" && !omnirushWorkspaceId) {
      const discovered = await discoverOmniRushWorkspace({
        hostUrl: omnirushHostUrl ?? baseUrl,
        token: omnirushToken,
        hostToken: omnirushHostToken,
        directory,
      });
      omnirushWorkspaceId = discovered ? readStringField(discovered, "id") : "";
      omnirushWorkspaceName = discovered ? omnirushWorkspaceDisplayName(discovered) : omnirushWorkspaceName;
      if (!omnirushWorkspaceId) {
        throw new ApiError(
          400,
          "omnirush_workspace_not_found",
          directory
            ? `OmniRush.ai server has no workspace matching ${directory}.`
            : "OmniRush.ai server returned no workspaces.",
        );
      }
    }

    const workspace: WorkspaceInfo = {
      id: remoteType === "omnirush"
        ? omnirushRemoteWorkspaceId(omnirushHostUrl ?? baseUrl, omnirushWorkspaceId)
        : workspaceIdForRemote(baseUrl, directory),
      name: displayName ?? omnirushWorkspaceName ?? "Remote workspace",
      path: directory ?? "",
      preset: "remote",
      workspaceType: "remote",
      remoteType,
      baseUrl: remoteType === "omnirush" ? (omnirushHostUrl ?? baseUrl) : baseUrl,
      ...(directory ? { directory } : {}),
      ...(displayName ? { displayName } : {}),
      ...(remoteType === "omnirush" && omnirushHostUrl ? { omnirushHostUrl } : {}),
      ...(omnirushToken ? { omnirushToken } : {}),
      ...(remoteType === "omnirush" && omnirushWorkspaceId ? { omnirushWorkspaceId } : {}),
      ...(remoteType === "omnirush" && omnirushWorkspaceName ? { omnirushWorkspaceName } : {}),
      ...(sandboxBackend ? { sandboxBackend } : {}),
      ...(sandboxRunId ? { sandboxRunId } : {}),
      ...(sandboxContainerName ? { sandboxContainerName } : {}),
    };

    config.workspaces = [workspace, ...config.workspaces.filter((entry) => entry.id !== workspace.id)];
    const persisted = await persistServerWorkspaceState(config);
    onWorkspacesChanged();

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "host" },
      action: "workspace.create",
      target: workspace.path || workspace.baseUrl || "workspace",
      summary: `Created remote workspace ${workspace.name}`,
      timestamp: Date.now(),
    });

    return jsonResponse({
      activeId: workspace.id,
      workspaces: config.workspaces.map(serializeWorkspace),
      persisted,
    }, 201);
  });

  addRoute(routes, "PATCH", "/workspaces/:id/display-name", "host", async (ctx) => {
    ensureWritable(config);
    const workspace = await resolveWorkspaceForRegistry(ctx.params.id);
    const body = await readJsonBody(ctx.request);
    const nextDisplayName = typeof body.displayName === "string" && body.displayName.trim()
      ? body.displayName.trim()
      : undefined;

    config.workspaces = config.workspaces.map((entry) =>
      entry.id === workspace.id
        ? {
            ...entry,
            displayName: nextDisplayName,
            name: nextDisplayName ?? entry.name,
          }
        : entry,
    );

    const persisted = await persistServerWorkspaceState(config);
    onWorkspacesChanged();

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "host" },
      action: "workspace.rename",
      target: workspace.path || workspace.baseUrl || "workspace",
      summary: `Updated workspace display name${nextDisplayName ? ` to ${nextDisplayName}` : ""}`,
      timestamp: Date.now(),
    });

    return jsonResponse({
      activeId: config.workspaces[0]?.id ?? null,
      workspaces: config.workspaces.map(serializeWorkspace),
      persisted,
    });
  });

  addRoute(routes, "POST", "/workspaces/:id/activate", "host", async (ctx) => {
    const workspace = await resolveWorkspaceForRegistry(ctx.params.id);
    const queryPersist = parseOptionalBoolean(ctx.url.searchParams.get("persist"), "persist");
    const body = queryPersist === undefined ? await readOptionalJsonBody(ctx.request) : {};
    const persist = queryPersist ?? (body.persist === true);
    if (persist) ensureWritable(config);
    const wasActive = config.workspaces[0]?.id === workspace.id;
    config.workspaces = [
      workspace,
      ...config.workspaces.filter((entry) => entry.id !== workspace.id),
    ];
    const persisted = persist ? await persistServerWorkspaceState(config) : false;
    if (persist) onWorkspacesChanged();
    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "host" },
      action: "workspace.activate",
      target: "workspace",
      summary: "Switched active workspace",
      timestamp: Date.now(),
    });
    // The injected engine config file is workspace-independent, so activation
    // never disposes or reloads an engine instance. Fire-and-forget re-attach
    // of the activated workspace's runtime MCPs via the dynamic push.
    if (!wasActive && workspace.workspaceType === "local" && resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim()) {
      void syncWorkspaceRuntimeMcp(config, workspace).catch(() => undefined);
    }
    if (workspace.workspaceType === "local") onWorkspaceOpened?.(config, workspace);
    return jsonResponse({ activeId: workspace.id, workspace: serializeWorkspace(workspace), persisted });
  });

  addRoute(routes, "DELETE", "/workspaces/:id", "host", async (ctx) => {
    ensureWritable(config);

    // Only the registry entry: resolving the workspace would bootstrap it,
    // recreating a folder the person already deleted, and a folder that is
    // gone or locked must never block its removal.
    const workspaceId = ctx.params.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") await options.stopWorkspaceWork?.(config, workspace);

    const previousWorkspaces = config.workspaces;
    const previousAuthorizedRoots = config.authorizedRoots;
    config.workspaces = config.workspaces.filter((entry) => entry.id !== workspace.id);
    const deleted = previousWorkspaces.length !== config.workspaces.length;

    if (deleted && workspace.workspaceType === "local") {
      // Only remove exact matches; authorizedRoots can contain broader entries.
      config.authorizedRoots = config.authorizedRoots.filter((root) => resolve(root) !== resolve(workspace.path));
    }
    let persisted: boolean;
    try {
      persisted = await persistServerWorkspaceState(config);
    } catch (error) {
      // Not saved: the next start would bring the workspace back, so it stays
      // listed now too and the person sees the failure instead.
      config.workspaces = previousWorkspaces;
      config.authorizedRoots = previousAuthorizedRoots;
      throw new ApiError(500, "workspace_registry_write_failed", "The workspace could not be removed: saving the workspace list failed", {
        cause: error instanceof Error ? error.message : String(error),
      });
    }
    onWorkspacesChanged();

    await recordAudit(workspace.path, {
      id: shortId(),
      workspaceId: workspace.id,
      actor: ctx.actor ?? { type: "host" },
      action: "workspace.delete",
      target: "workspace",
      summary: "Deleted workspace from OmniRush.ai server",
      timestamp: Date.now(),
    }).catch(() => undefined); // The removal is saved; a failed audit line must not report it as failed.

    const active = config.workspaces[0] ?? null;
    return jsonResponse({
      ok: true,
      deleted,
      persisted,
      activeId: active?.id ?? null,
      items: config.workspaces.map(serializeWorkspace),
      workspaces: config.workspaces.map(serializeWorkspace),
    });
  });
}