Skip to content

A desktop coding agent with free access to frontier models.

TypeScript
27.6 KB
Raw Blame
/**
 * Everything the embedded server captures about sessions, under one owner:
 * the session uploader, the project archive and the turn observers. The
 * server runs it on a worker thread (capture-worker.ts, driven through
 * capture-client.ts), so reading, hashing and scrubbing files, building JSON
 * and tar streams, compressing and sealing never hold the main event loop
 * that serves the app; where no worker can start it runs in-process with the
 * same behaviour. Every call takes and returns plain data, so the same calls
 * cross the thread boundary unchanged.
 */
import { createMediaRewriter } from "./computer-use/media-capture.js";
import type { ApprovalMode } from "./approval-mode.js";
import type { ContextOptions } from "./context/index.js";
import { defaultRedactionPolicy } from "./context/redact-policy.js";
import { readPromptAttachments, promptBodyForTrace, v2PromptBodyForTrace } from "./session-upload-attachments.js";
import {
  readSessionTranscript,
  createSessionObservers,
  currentEngineTarget,
  engineReplaced,
  observeUploadedSession,
  setEngineMessageRewrite,
  followToolStart, followContextToolEvents, followFilesUsedCalls,
  projectArchiveEngineReads,
  promptDispatched,
  turnEndedAt,
  type EngineReplacement,
  type EngineTarget,
  type SessionObservers,
} from "./session-upload-observer.js";
import type { CaptureStopOptions } from "./capture-protocol.js";
import type { CommandEventType } from "./command-events.js";
import { ARCHIVE_STATE_DIRECTORY, SessionArchiver, type FilesUsedStatus, type SessionArchiverOptions } from "./session-archive/index.js";
import { archiveOwner } from "./session-archive/account-park.js";
import { ProjectArchiveLifecycle, type ArchiveLifecycleLog, type LateWrites } from "./session-archive/lifecycle.js";
import { START_GATE_MS } from "./session-archive/capture-v2.js";
import { settleLateWriters, type SettleResult } from "./session-archive/late-writes.js";
import { isAbsolute, join, relative, sep } from "node:path";
import { boxSnapshotsDir } from "./box/box.js";
import type { BoxCaptureInfo } from "./box/service.js";
import { sandboxFilesUsed, type FilesUsedSandbox } from "./session-archive/files-used-sandbox.js";
import { SessionUploader, type RecoveredTurn, type TraceCapabilities, type UploadMetrics, type UploadRequestOptions, type UploadWebVisit } from "./session-uploader.js";

export type { EngineReplacement, EngineTarget } from "./session-upload-observer.js";

export type CaptureLog = ArchiveLifecycleLog;

/** Prompt bodies larger than this are not parsed for the trace (nor for attachments). */
const MAX_TRACED_REQUEST_BYTES = 4 * 1024 * 1024;
/** An app quit gives the turns still open this long in all to be settled from the engine. */
const QUIT_SETTLE_BUDGET_MS = 5_000;
/** A recovered turn asks for its engine again after these waits (the engine may still be starting). */
const RECOVERY_TARGET_DELAYS_MS = [0, 2_000, 5_000, 15_000, 30_000, 60_000];

/**
 * A prompt's wait for the turn before's background processes (late-writes.ts):
 * the engines' processes, never waited for (with this process, whose
 * descendants they usually are). Left out (no wait) in a sandbox or a remote
 * workspace, whose processes are not this machine's.
 */
export type LateWritesGate = { exclude: number[] };

/** A captured engine request, as the "engine.request" trace event and the prompt's attachments are built from it. */
export type PromptRecord = {
  method: string;
  path: string;
  /** The request body; null when there is none or it is larger than a traced body may be. */
  body: Uint8Array | null;
  engine: "v1" | "v2";
  /** The workspace root, where attached files copied into the workspace are read from. */
  root: string;
  /** A prompt dispatch: its file parts become "attachment" events. */
  attachments: boolean;
  /**
   * When a prompt dispatch went out (epoch milliseconds, taken before the
   * engine saw it): a turn of the session still being followed ends here.
   */
  dispatchedAt?: number;
  /** A prompt that started a turn while the engine was not plainly idle: why (turn-steer.ts), on its "engine.request" event. */
  turnStart?: string;
};

export type CaptureHostOptions = {
  /** The session uploader state dir (the archive keeps its files under it too). */
  stateDir: string;
  appVersion: string;
  engineVersion: string;
  log: CaptureLog;
  /** The signed-in account's id (null: not known now); spooled uploads are stamped with it. */
  accountId?: () => Promise<string | null>;
  /**
   * The engine holding a chat of this workspace, for settling a turn a
   * previous process left open; null when there is none (remote, unknown,
   * or the engine does not have the chat).
   */
  engineTarget?: (sessionId: string, workspaceId: string) => Promise<EngineTarget | null>;
  /** GET /omnirush/me/sessions/{id}/integrity with the device bearer. */
  sessionIntegrity?: (sessionId: string, options?: { summary?: boolean; turns?: number }) => Promise<Response>;
  sessionUploader: {
    upload?: (sessionId: string, compressed: Uint8Array, signal?: AbortSignal, request?: UploadRequestOptions) => Promise<Response>;
    uploadFile?: (sessionId: string, path: string, size: number, signal?: AbortSignal, request?: UploadRequestOptions) => Promise<Response>;
    capabilities?: () => Promise<TraceCapabilities>;
    refreshAccessToken?: () => Promise<string | null>;
    fetch?: (input: string, init?: RequestInit) => Promise<Response>;
    gatewayUrl?: string;
    accessToken?: string;
    /** Capture context (context/): false turns it off, an object overrides its options. */
    context?: false | Partial<ContextOptions>;
  };
  /** The install log's raw folder and wrapper folder (install-log-host.ts), when the engines have them. */
  installLog?: { raw: string; bin: string } | null;
  /** The install log of chats in a Linux sandbox (box/install-log.ts): its own raw folder, POSIX wrappers. */
  boxInstallLog?: { raw: string; bin: string } | null;
  archive: Pick<SessionArchiverOptions, "request" | "refreshAccessToken" | "fetch" | "gatewayUrl" | "accessToken" | "folderGate"> & {
    /** Archiving is on for this device (OMNIRUSH_ARCHIVE_ENABLED) and an account is connected. */
    enabled: boolean;
    /** App data, config and cache directories: pruned under a project root, never archived as one. */
    excludedDirs: string[];
    baseIdleMs?: number;
    baseMaxDeferMs?: number;
  };
  /** A finished session's last upload settled (the in-process `hasSession` mirror of a worker follows it). */
  onSessionClosed?: (sessionId: string) => void;
};

export type CaptureDiagnostics = {
  metrics: UploadMetrics;
  cache: { roots: number; entries: number };
};

function outsideRoot(root: string, path: string): boolean {
  const rel = relative(root, path);
  return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel);
}

function requestPayload(body: Uint8Array | null): unknown {
  if (!body || body.byteLength > MAX_TRACED_REQUEST_BYTES) return undefined;
  try {
    return JSON.parse(new TextDecoder().decode(body));
  } catch {
    return undefined;
  }
}

export class CaptureHost {
  private readonly accountId: CaptureHostOptions["accountId"];
  readonly sessionUploader: SessionUploader;
  readonly archive: ProjectArchiveLifecycle;
  private readonly observers: SessionObservers = createSessionObservers();
  /** Each started session's workspace root, for the turn's file record (session-archive/turn-files.ts). */
  private readonly sessionRoots = new Map<string, string>();
  /** The state dir and the app's data/config/cache dirs: never reported or recorded as a touched file. */
  private readonly appDirs: string[];
  private readonly stateDir: string;
  private readonly engineTarget?: CaptureHostOptions["engineTarget"];
  /** When each session's latest prompt was dispatched (archiveStartGate): the turn before's processes started since. */
  private readonly promptAt = new Map<string, number>();
  /** The latest prompt's wait for the turn before's background processes, when it found any ("turn.late"). */
  private readonly lateSettles = new Map<string, SettleResult>();
  /** Chats in a Linux sandbox: their files used outside the project are read in the container (one view per container). */
  private readonly boxViews = new Map<string, FilesUsedSandbox>();
  private readonly boxChats = new Map<string, string>();
  private readonly log: CaptureLog;

  constructor(options: CaptureHostOptions) {
    this.accountId = options.accountId;
    this.engineTarget = options.engineTarget;
    this.log = options.log;
    this.sessionUploader = new SessionUploader({
      ...options.sessionUploader,
      stateDir: options.stateDir,
      appVersion: options.appVersion,
      engineVersion: options.engineVersion,
      log: options.log,
      ...(options.accountId ? { accountId: options.accountId } : {}),
      ...(options.sessionIntegrity ? { sessionIntegrity: options.sessionIntegrity } : {}),
      // A turn a crashed process or worker left open is settled from the engine's messages.
      onRecoveredTurn: (turn) => void this.recoverTurn(turn),
      // A new chat pins the server's capture switch, read first if not known yet (the archiver's key probe).
      settleCapturePolicy: () => this.archive.settleCapturePolicy(),
      // Parts the server is missing are re-sent from the engine's transcript.
      repairTranscript: (chat) => this.transcript(chat),
      // Capture context (context/); OMNIRUSH_CAPTURE_CONTEXT=0 turns it off.
      context: options.sessionUploader?.context ?? {},
      ...(options.installLog ? { installLog: options.installLog } : {}),
      ...(options.boxInstallLog ? { boxInstallLog: options.boxInstallLog } : {}),
      ...(options.onSessionClosed ? { onSessionClosed: options.onSessionClosed } : {}),
      // The touched-files archive hears of every path a session touches, here on the same thread.
      onPathTouched: (sessionId, path) => {
        // A chat in a box: a path outside the project names a file in the container, not on this
        // machine; the box's turn checkpoints carry those.
        const root = this.sessionRoots.get(sessionId);
        if (root && this.sessionUploader.inBox(sessionId) && isAbsolute(path) && outsideRoot(root, path)) return;
        this.archive.pathTouched(sessionId, path);
      },
      // Capture v2: a binary file is never sent as text; the project archive keeps it byte for byte.
      onBinaryFile: (sessionId, path) => this.archive.binaryFile(sessionId, path),
    });
    const { enabled, excludedDirs, folderGate, baseIdleMs, baseMaxDeferMs, ...auth } = options.archive;
    this.appDirs = [options.stateDir, ...excludedDirs];
    this.stateDir = options.stateDir;
    this.archive = new ProjectArchiveLifecycle({
      archiver: new SessionArchiver({
        stateDir: options.stateDir,
        excludedDirs,
        // The Linux sandbox's turn checkpoints (box/service.ts saves them there).
        sandboxSnapshotsDir: boxSnapshotsDir(options.stateDir),
        filesUsedSandbox: (sessionId) => {
          const container = this.boxChats.get(sessionId);
          return container ? this.boxViews.get(container) ?? null : null;
        },
        folderGate,
        log: options.log,
        ...auth,
        // Through the gateway broker, the account behind the device bearer (claimAccount()).
        ...(auth.request && options.accountId ? { accountId: options.accountId } : {}),
      }),
      enabled: enabled && this.sessionUploader.enabled,
      accountMissing: !this.sessionUploader.enabled,
      log: options.log,
      // A turn's pre_tool state took what the turn before's background processes wrote after it ended.
      onLateWrites: (late) => this.recordLateWrites(late),
      // What became of each session's base: recorded in its uploads, so no missing base goes unexplained.
      onProjectArchive: (sessionId, outcome) => this.sessionUploader.recordProjectArchive(sessionId, outcome),
      onTurnArchive: (sessionId, result) => this.sessionUploader.archiveTurnChecked(sessionId, result),
      ...(baseIdleMs !== undefined ? { baseIdleMs } : {}),
      ...(baseMaxDeferMs !== undefined ? { baseMaxDeferMs } : {}),
    });
    this.archive.start();
    // Image data URLs in tool results become media references as messages are read (computer-use/media-capture.ts).
    setEngineMessageRewrite(createMediaRewriter({
      stateDir: options.stateDir,
      onFiles: (sessionId, files) => this.archive.mediaFiles(sessionId, files),
      onComputerUse: (sessionId) => this.sessionUploader.markComputerUse(sessionId),
    }));
  }

  startSession(sessionId: string, workspaceId: string, root: string, turnsBefore = 0): void {
    this.sessionRoots.set(sessionId, root);
    this.sessionUploader.startSession(sessionId, workspaceId, root, { turnsBefore });
  }

  /** A Claude chat (opencode-plugins/claude-provider): its uploads name Claude Code, run in the box under this engine. */
  markClaude(sessionId: string, version: string): void {
    this.sessionUploader.markClaude(sessionId, version);
  }

  /** A chat pinned to another provider's model: a refused Claude pick never makes its uploads name Claude Code. */
  markNotClaude(sessionId: string): void {
    this.sessionUploader.markNotClaude(sessionId);
  }

  /** The app's permission mode, named in the setup record of the sessions started after it (sent before each startSession). */
  permissionMode(mode: ApprovalMode | null): void {
    this.sessionUploader.setPermissionMode(mode);
  }

  /** A tracked chat's capture policy once settled (null: not tracked, or not settled yet). */
  async sessionPolicy(sessionId: string): Promise<string | null> {
    // An untracked chat (its uploads off): the policy a session starting now gets.
    return this.sessionUploader.hasSession(sessionId) ? await this.sessionUploader.settledPolicy(sessionId) : defaultRedactionPolicy();
  }

  /** The capture policy the server's binding keeps for the chat. */
  holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed", seq: number): void {
    this.sessionUploader.holdUploads(sessionId, state, seq);
  }

  pinPolicy(sessionId: string, policy: string): void {
    this.sessionUploader.pinPolicy(sessionId, policy);
  }

  /** The chat's prompts run in its project's box (or no longer: null); sent before its startSession. */
  boxSession(sessionId: string, box: BoxCaptureInfo | null): void {
    this.sessionUploader.setBox(sessionId, box);
    if (!box) {
      this.boxChats.delete(sessionId);
      return;
    }
    this.boxChats.set(sessionId, box.container);
    if (!this.boxViews.has(box.container)) {
      const view = sandboxFilesUsed({ container: box.container, manifest: { home: "/root", workspaces: [box.croot] }, cwd: box.root, hostHome: null, docker: box.runtimeBin, dockerArgs: box.runtimeArgs, exec: box.exec, log: this.log });
      if (view) this.boxViews.set(box.container, view);
    }
  }

  recordTrace(sessionId: string, type: string, data?: unknown): void {
    this.sessionUploader.recordTrace(sessionId, type, data);
  }

  flushTrace(sessionId: string, finalTrace?: unknown): void {
    this.sessionUploader.flushTrace(sessionId, finalTrace);
  }

  finishSession(sessionId: string, finalTrace?: unknown): void {
    this.sessionUploader.finishSession(sessionId, finalTrace);
    this.archive.sessionEnded(sessionId);
    this.forgetSession(sessionId);
  }

  private forgetSession(sessionId: string): void {
    this.observers.lastMessageIds.delete(sessionId);
    this.observers.turnEnds?.delete(sessionId);
    this.sessionRoots.delete(sessionId);
    this.promptAt.delete(sessionId);
    this.lateSettles.delete(sessionId);
  }

  /** "turn.late": files the turn before's background processes wrote after it ended, taken into this turn's start. */
  private recordLateWrites(late: LateWrites): void {
    const settled = this.lateSettles.get(late.sessionId);
    this.sessionUploader.recordTrace(late.sessionId, "turn.late", {
      late_from_turn: late.turn > 1 ? late.turn - 1 : null,
      turn: late.turn,
      after_end_at: new Date(late.after).toISOString(),
      tool_start_at: new Date(late.toolStartAt).toISOString(),
      waited_ms: settled?.waitedMs ?? 0,
      settled: settled?.settled ?? true,
      paths: late.paths,
      processes: settled?.processes ?? [],
    });
  }

  /** The "engine.request" event of a captured request and, for a prompt dispatch, one "attachment" event per attached file. */
  recordPrompt(sessionId: string, prompt: PromptRecord): void {
    // The turn this prompt follows takes its end snapshot first, ahead of this prompt's own.
    if (prompt.dispatchedAt !== undefined) promptDispatched(this.observers, this.sessionUploader, sessionId, prompt.dispatchedAt);
    const payload = requestPayload(prompt.body);
    this.sessionUploader.recordTrace(sessionId, "engine.request", {
      method: prompt.method,
      path: prompt.path,
      body: prompt.engine === "v2" ? v2PromptBodyForTrace(payload) : promptBodyForTrace(payload),
      ...(prompt.turnStart ? { turn_start: prompt.turnStart } : {}),
    });
    if (!prompt.attachments) return;
    void readPromptAttachments(payload, prompt.root).then((attachments) => {
      for (const attachment of attachments) this.sessionUploader.recordAttachment(sessionId, attachment);
    }).catch(() => undefined);
  }

  captureSnapshot(sessionId: string, trigger: "prompt" | "turn_completed", outcome?: "aborted"): void {
    this.sessionUploader.captureSnapshot(sessionId, trigger, outcome);
  }

  /** A prompt steered the running turn (turn-steer.ts): its "turn.steer" event. */
  steerTurn(sessionId: string, steer: Record<string, unknown>): void {
    this.sessionUploader.steerTurn(sessionId, steer);
  }

  /** An undo / redo / review / fix the person ran (command-events.ts): its additive event. */
  recordCommand(sessionId: string, type: CommandEventType, data: Record<string, unknown>): void {
    this.sessionUploader.recordCommand(sessionId, type, data);
  }

  /**
   * The engine took a steer: the running turn goes on, followed by its
   * observer. A turn no observer follows (its observation ended) is followed
   * from here; a followed one is left as it is, so the steer never counts as
   * a request of its own (a turn after this one).
   */
  followSteer(sessionId: string, target: EngineTarget): void {
    if (this.observers.sessions.has(sessionId)) return;
    this.observeSession(sessionId, target);
  }

  recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean {
    return this.sessionUploader.recordWebVisit(sessionId, visit);
  }

  /** A prompt was dispatched: the project archive's session start (a base once per session, see lifecycle.ts). */
  archiveSessionStarted(sessionId: string, root: string, target: EngineTarget): void {
    this.archive.sessionStarted({ sessionId, root, engine: projectArchiveEngineReads(() => currentEngineTarget(this.observers, target), sessionId) });
    // Capture v2: this turn's first tool call takes the folder's state (in the background).
    followToolStart({ observers: this.observers, archive: this.archive, sessionId, target });
    // Capture context: each tool call's start and end, for the network observer.
    followContextToolEvents({ observers: this.observers, context: this.sessionUploader.contextOf(sessionId), sessionId, target });
    // Files used: each tool call's end, so its temp files are kept before a later call deletes them.
    followFilesUsedCalls({ observers: this.observers, archive: this.archive, sessionId, target });
  }

  /**
   * Call while a prompt is held, before it reaches the engine. When the
   * session's turn before has ended (the engine went idle), the background
   * processes that turn left running in the workspace get to finish writing
   * first, at most LATE_WRITES_CAP_MS after it ended (late-writes.ts), so the
   * turn's end snapshot and archive delta, taken as this prompt cuts it, hold
   * those writes. A prompt typed into a running turn waits for nothing.
   * Then capture v2's session-start manifest, before the first prompt
   * reaches the engine (lifecycle.ts startGate).
   */
  async archiveStartGate(sessionId: string, root: string, lateWrites?: LateWritesGate | null): Promise<void> {
    const previousStart = this.promptAt.get(sessionId);
    const endedAt = turnEndedAt(this.observers, sessionId);
    this.lateSettles.delete(sessionId);
    if (lateWrites && previousStart !== undefined && endedAt !== null && endedAt >= previousStart) {
      const settled = await settleLateWriters({ root, since: previousStart, exclude: [process.pid, ...lateWrites.exclude], endedAt });
      if (settled.processes.length > 0) {
        this.lateSettles.set(sessionId, settled);
        this.sessionUploader.recordTrace(sessionId, "turn.settle", { waited_ms: settled.waitedMs, settled: settled.settled, processes: settled.processes });
      }
    }
    this.promptAt.set(sessionId, Date.now());
    // The turn before ended since its prompt (not a prompt into a running turn): its delta is taken first (lifecycle startGate).
    const previousEnded = previousStart !== undefined && endedAt !== null && endedAt >= previousStart;
    // With the session uploader's start scan (a new session, startSession called first): both read the folder before the prompt.
    await Promise.all([this.archive.startGate(sessionId, root, { previousEnded }), this.sessionUploader.startScanned(sessionId, START_GATE_MS)]);
  }

  /** An engine was closed and `replacement` took over its sessions: observations reading it move there. */
  engineReplaced(closedBaseUrl: string, replacement: EngineReplacement): void {
    engineReplaced(this.observers, closedBaseUrl, replacement);
  }

  /** The engine accepted a captured request: follow the session until its turn settles. */
  observeSession(sessionId: string, target: EngineTarget, recovered = false): void {
    const root = this.sessionRoots.get(sessionId);
    void observeUploadedSession({
      sessionUploader: this.sessionUploader,
      archive: this.archive,
      ...(root ? { turnFiles: { root, archive: this.archive, excludedDirs: this.appDirs } } : {}),
      observers: this.observers,
      sessionId,
      target,
      ...(recovered ? { recovered } : {}),
    });
  }

  /**
   * A turn a previous process (or worker) left open: the chat resumes here
   * and its observer settles the turn from the engine's messages, or follows
   * it to its end when it is still running. Without an engine that has the
   * chat, its messages wait for its next prompt (the checkpoint did not move).
   */
  private async recoverTurn(turn: RecoveredTurn): Promise<void> {
    if (!this.engineTarget) return;
    const stopped = this.observers.controller.signal;
    // The chat was resumed meanwhile (the app's own task recovery, or the user): its
    // observer settles the interrupted turn with the next one; the trace says it was recovered.
    const resumed = (): boolean => {
      if (!this.sessionUploader.hasSession(turn.sessionId)) return false;
      this.sessionUploader.recordTrace(turn.sessionId, "collector.recovered", { reason: "restart", turn_open: true, settled_by: "resumed_chat" });
      return true;
    };
    for (const delay of RECOVERY_TARGET_DELAYS_MS) {
      if (delay > 0) await new Promise((resolvePromise) => setTimeout(resolvePromise, delay).unref?.());
      if (stopped.aborted || resumed()) return;
      const target = await this.engineTarget(turn.sessionId, turn.workspaceId).catch(() => null);
      if (stopped.aborted || resumed()) return;
      if (!target) continue;
      this.startSession(turn.sessionId, turn.workspaceId, turn.root);
      this.observeSession(turn.sessionId, target, true);
      return;
    }
  }

  /** Files used, for the app's one-time notice: what omnirush.ai says. */
  filesUsedStatus(): Promise<FilesUsedStatus> {
    return this.archive.filesUsedStatus();
  }

  /** The session was deleted in the engine. */
  sessionDeleted(sessionId: string): void {
    this.sessionUploader.recordTrace(sessionId, "session.deleted");
    this.sessionUploader.finishSession(sessionId);
    this.archive.sessionEnded(sessionId);
    this.forgetSession(sessionId);
  }

  /**
   * The user signed out: nothing more is captured or sent in this app run.
   * What is queued stays on disk for that account (stamped with it): its
   * next sign-in sends it, another account never does (account-park.ts).
   */
  async signOut(): Promise<void> {
    const owner = await archiveOwner(join(this.stateDir, ARCHIVE_STATE_DIRECTORY)).catch(() => null);
    await this.archive.signOut();
    await this.sessionUploader.keepSpoolFor(owner).catch(() => undefined);
  }

  /** Uploads and project archives queued now (for "Sending N pending uploads…" before a sign-out). */
  async pendingUploads(): Promise<{ uploads: number; archives: number }> {
    const [spool, archives] = await Promise.all([
      this.sessionUploader.spoolStatus().catch(() => ({ entries: 0 })),
      this.archive.pendingStatus().catch(() => ({ jobs: 0 })),
    ]);
    return { uploads: spool.entries, archives: archives.jobs };
  }

  /**
   * Before a sign-out: sends what is queued, for at most `budgetMs`. What is
   * not sent by then stays queued (signOut() keeps it for the account).
   */
  async flushPending(budgetMs: number): Promise<{ before: number; after: number }> {
    const count = async () => {
      const pending = await this.pendingUploads();
      return pending.uploads + pending.archives;
    };
    const before = await count();
    if (before > 0) {
      let timer: ReturnType<typeof setTimeout> | undefined;
      await Promise.race([
        Promise.all([this.sessionUploader.drainSpool().catch(() => undefined), this.archive.drainNow().catch(() => undefined)]),
        new Promise((resolvePromise) => {
          timer = setTimeout(resolvePromise, Math.max(0, Math.min(budgetMs, 30_000)));
          timer.unref?.();
        }),
      ]).finally(() => clearTimeout(timer));
    }
    return { before, after: before > 0 ? await count() : 0 };
  }

  /**
   * Server shutdown: in-flight archive uploads abort first, then every
   * session's trace and end snapshot go out, next to the project archive's
   * final archives (unless `archiveFinals` is false: the account is gone).
   */
  async stop(options: CaptureStopOptions = { archiveFinals: true }): Promise<void> {
    // Turns still open get their messages and their end first, within a bounded budget.
    await this.settleOpenTurns(QUIT_SETTLE_BUDGET_MS);
    const archiveStopped = this.archive.stop({ finals: options.archiveFinals });
    this.observers.controller.abort();
    await this.sessionUploader.stop().catch(() => undefined);
    await archiveStopped;
  }

  /** A chat's whole transcript from the engine that has it; null without one. */
  private async transcript(chat: RecoveredTurn): Promise<unknown[][] | null> {
    const target = this.engineTarget ? await this.engineTarget(chat.sessionId, chat.workspaceId).catch(() => null) : null;
    return target ? readSessionTranscript(target, chat.sessionId, this.observers.controller.signal) : null;
  }

  /** Settles every followed turn as the engine has it now, waiting at most `budgetMs`. */
  private async settleOpenTurns(budgetMs: number): Promise<void> {
    const open = [...this.observers.sessions.values()].map((session) => session.settleNow?.().catch(() => undefined));
    if (open.length === 0) return;
    let timer: ReturnType<typeof setTimeout> | undefined;
    await Promise.race([
      Promise.allSettled(open),
      new Promise((resolvePromise) => {
        timer = setTimeout(resolvePromise, budgetMs);
        timer.unref?.();
      }),
    ]);
    clearTimeout(timer);
  }

  /** Resolves once every queued capture, upload and archive step has settled (tests, profiling). */
  async idle(): Promise<void> {
    await this.sessionUploader.idleAll();
    await this.archive.settled();
  }

  diagnostics(): CaptureDiagnostics {
    return { metrics: { ...this.sessionUploader.metrics }, cache: this.sessionUploader.cacheStatus() };
  }
}