Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

154 KB
Raw Blame
/**
 * Server-hosted ACP threads: one spawned agent subprocess per thread, bridged to clients over
 * `/collab/thread`. Markdown writes reuse `AgentSessionManager` sessions keyed by `acp-<uuid>`, so
 * each edit lands under a per-session frozen origin (precedent #24) in the `agent-*` namespace.
 */

import type { ChildProcess } from 'node:child_process';
import { readFile, realpath, stat } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
import { Readable, Writable } from 'node:stream';
import { pathToFileURL } from 'node:url';
import {
  client as acpClient,
  methods as acpMethods,
  type ClientConnection,
  type ContentBlock,
  type InitializeResponse,
  type McpServer,
  type McpServerStdio,
  ndJsonStream,
  type PermissionOption,
  PROTOCOL_VERSION,
  type PromptCapabilities,
  type RequestPermissionResponse,
  type SessionConfigOption,
  type SessionNotification,
  type SessionUpdate,
  type SetSessionConfigOptionRequest,
  type SetSessionConfigOptionResponse,
  type StopReason,
  type ToolCallUpdate,
  type WriteTextFileResponse,
} from '@agentclientprotocol/sdk';
import {
  AGENT_ICON_COLORS,
  agentIdForAcpAgent,
  colorFromSeed,
  currentMcpServerName,
  type EditorId,
  type HostSnapshot,
  iconFromClientName,
  OK_HOSTED_AGENT_ENV,
  OkCliCommand,
} from '@inkeep/open-knowledge-core';
import type {
  AttachmentPart,
  BrowserUnavailableReason,
  PiBridgeThreadState,
  PiBridgeWriteAction,
  PiTrustWriteAction,
  QueuedMessage,
  SteerMessage,
  ThreadAgentInfo,
  ThreadAuthTerminalLaunch,
  ThreadChatGrant,
  ThreadEvent,
  ThreadFailureDetail,
  ThreadInfo,
  ThreadServerFrame,
  ThreadStatus,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { THREAD_REOPEN_OP_TIMEOUT_MS } from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { asRecord } from '@inkeep/open-knowledge-core/acp/tool-call-input';
import { toBroadcasterKey } from '../agent-id.ts';
import type { AgentPresenceBroadcaster } from '../agent-presence.ts';
import { observeReadiness } from '../agent-registry-gate.ts';
import type { AgentSessionManager } from '../agent-sessions.ts';
import { resolveBundledSkillDir } from '../build-skill-zip.ts';
import {
  isConfigDoc,
  isEditableTextDoc,
  isExcalidrawDoc,
  isMermaidDoc,
  isSystemDoc,
} from '../cc1-broadcast.ts';
import { tracedRm } from '../fs-traced.ts';
import { resolveOnPath } from '../git-preflight.ts';
import type { LocalApiDispatch } from '../http/local-api-dispatch.ts';
import type { PinoLogger } from '../logger.ts';
import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';
import { RUNTIME_VERSION } from '../version-constants.ts';
import { isWithin } from './archive.ts';
import { buildPromptBlocks } from './attachment-blocks.ts';
import {
  AGENT_BROWSER_MCP_PACKAGE,
  agentBrowserInstallLaunch,
  agentBrowserMcpServer,
  agentGetsBrowser,
  type BrowserCallEvidence,
  type BrowserPackageData,
  browserNpxRunnable,
  identifyBrowserCall,
  needsReportedToolCall,
  npmCacheOf,
  prepareAgentBrowserFolders,
  type ResolvedBrowserNpx,
  removeAgentBrowserFolders,
  resolveBrowserNpx,
} from './browser-mcp.ts';
import {
  ACQUISITION_DETAIL_MAX_CHARS,
  createDiagnosticStderrCapture,
  redactDiagnostic,
} from './diagnostics.ts';
import { writeDocumentThroughRoute } from './document-write.ts';
import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';
import { exitFailureDetail } from './exit-diagnosis.ts';
import {
  AgentLaunchError,
  agentSpawnPath,
  brokenInterpreterHint,
  declinedRepairHint,
  ensureNpmPackageInstalled,
  envPath,
  expiredFallbackHint,
  expiredIncompatibleNodeHint,
  expiredRepairHint,
  incompatibleManagedRuntimeHint,
  incompatibleNodeHint,
  isPathQualified,
  type NpxCacheEntry,
  npxInstallRefused,
  packageAcquisitionFailure,
  preflightLaunch,
  probeInterpreterHealth,
  probeNpxNodeCompatibility,
  type ResolvedLaunch,
  refusedNpxPackage,
  resolveCustomLaunch,
  resolveRegistryLaunch,
  rewriteLaunchToManagedRuntime,
  spawnAcpAgent,
  staleNpxCacheEntry,
  terminateAgentTree,
  undeletableManagedRuntimeHint,
  unrepairableManagedRuntimeHint,
  withLoginShellPath,
  withPreferredLoginShellPath,
} from './launch.ts';
import { isAcpLaunchFailureReason, recordAcpLaunchFailure } from './launch-failure-log.ts';
import {
  getSharedLoginShellPathProvider,
  resetSharedLoginShellPathProvider,
} from './login-shell-path.ts';
import {
  cleanupManagedRuntimeStaging,
  describeRuntime,
  ensureManagedRuntime,
  findManagedRuntime,
  type ManagedRuntime,
  type ManagedRuntimeKind,
  quarantineManagedRuntime,
  runtimeDownloadSupported,
  runtimeForInterpreter,
} from './managed-runtime.ts';
import { contextWindowChangeFor } from './model-discovery/context-window-change.ts';
import {
  applyLaunchContextWindow,
  launchContextMechanism,
} from './model-discovery/launch-context.ts';
import { type AcpPermissionStore, offeredPermissionOptions } from './permissions.ts';
import { PROJECT_SKILL_ENTRY, stageProjectSkill } from './project-skill-staging.ts';
import { readOnlyShellCommand } from './read-only-shell.ts';
import {
  ACP_AGENT_EDITOR_IDS,
  type AcpRegistry,
  type CustomAgentEntry,
  loadCustomAgents,
  registryPlatformKey,
} from './registry.ts';
import {
  type TerminalAuthBase,
  terminalAuthBaseFor,
  terminalAuthLaunch,
  threadAuthMethods,
} from './terminal-auth.ts';
import { AcpTerminalSet } from './terminals.ts';
import {
  acpThreadStoreRoots,
  type PersistedThreadMeta,
  ThreadPersistenceStore,
} from './thread-persistence.ts';
import { clampThreadTitle, deriveThreadTitle } from './thread-title.ts';

export const MAX_ACP_THREADS = 8;
export const MAX_QUEUED_PROMPTS = 20;
const EVENT_LOG_LIMIT = 5_000;
const DEFAULT_IDLE_REAP_MS = 60 * 60 * 1000;
const REAP_SWEEP_MS = 5 * 60 * 1000;
const PERMISSION_TIMEOUT_MS = 10 * 60 * 1000;
const CONSENT_TIMEOUT_MS = 5 * 60 * 1000;

const BLOCKING_CONSENT_TIMEOUT_MS = Math.floor(THREAD_REOPEN_OP_TIMEOUT_MS / 2);
const RUNTIME_PROGRESS_THROTTLE_MS = 400;
const KILL_GRACE_MS = 5_000;
const DESTROY_KILL_GRACE_MS = 2_000;
const EVENT_FLUSH_MS = 25;
const REPLAY_CHUNK_SIZE = 512;
const DEFAULT_UNWATCHED_TURN_CANCEL_MS = 10 * 60 * 1000;
const DEFAULT_UNWATCHED_TURN_KILL_MS = 20 * 60 * 1000;
const DEFAULT_STEER_STALL_MS = 10_000;
const DEFAULT_TURN_STALL_MS = 3 * 60 * 1000;
const DEFAULT_AUTHENTICATE_TIMEOUT_MS = 5 * 60 * 1000;
const DEFAULT_BROWSER_INSTALL_WAIT_MS = 2 * 60 * 1000;
const STDERR_TAIL_LINES = 40;
const CRASH_REPORT_STATUSES: ReadonlySet<ThreadStatus> = new Set([
  'ready',
  'auth_required',
  'authenticating',
]);
const SIGN_IN_OUTPUT_LINES = 6;
const RESUME_REPLAY_QUIESCENCE_MS = 300;
const RESUME_REPLAY_MAX_WAIT_MS = 3_000;
const AUTH_REQUIRED_CODE = -32000;

type AcquisitionPolicy = 'reuse' | 'reacquire';

type NpxLaunchRecovery = 'available' | 'spent';

const NPX_CACHE_CLEAR_COOLDOWN_MS = 5 * 60 * 1000;

export const ACP_ENVIRONMENT_NOTE =
  'Note on your environment: you are running inside the OpenKnowledge app, ' +
  'connected over ACP (Agent Client Protocol) — not inside your own terminal app. ' +
  "Your host CLI's terminal UI is not present, so its built-in slash commands " +
  '(such as /tasks or /bashes) and keyboard shortcuts (such as Ctrl+O) do not ' +
  'exist here; never recommend them. The only slash commands available to the ' +
  'user are the ones you advertise over ACP.';

export interface ProjectSkillNoteInput {
  skillPath: string;
  inline?: boolean;
}

export function buildEnvironmentNote(skill: ProjectSkillNoteInput | null): string {
  if (skill === null) return ACP_ENVIRONMENT_NOTE;
  const pointer =
    skill.inline === true
      ? 'This project uses OpenKnowledge. Its agent skill (SKILL.md) is attached to this message. ' +
        'Follow it before editing any markdown here; it overrides generic markdown habits. ' +
        'If you already have the `open-knowledge` skill loaded, skip it.'
      : `This project uses OpenKnowledge. Its agent skill is at \`${skill.skillPath}\`. ` +
        'Read it before editing any markdown here; it overrides generic markdown habits, ' +
        'and you may read its `references/` files by path when it points to them. ' +
        'If you already have the `open-knowledge` skill loaded, skip the read.';
  return `${ACP_ENVIRONMENT_NOTE}\n\n${pointer}`;
}

const INLINE_SKILL_AGENT_IDS: ReadonlySet<string> = new Set(['gemini']);

export function deliversSkillInline(agentRef: {
  source: 'registry' | 'custom';
  id: string;
}): boolean {
  return agentRef.source === 'registry' && INLINE_SKILL_AGENT_IDS.has(agentRef.id);
}

interface StagedProjectSkill {
  skillPath: string;
  inlineText: string | null;
}

export function inlineSkillBlock(
  skillPath: string,
  text: string,
  capabilities: PromptCapabilities | null | undefined,
): ContentBlock {
  if (capabilities?.embeddedContext !== true) {
    return {
      type: 'text',
      text: `\n\n--- OpenKnowledge skill: ${PROJECT_SKILL_ENTRY} ---\n${text}\n--- End skill ---`,
    };
  }
  return {
    type: 'resource',
    resource: { uri: pathToFileURL(skillPath).href, text, mimeType: 'text/markdown' },
  };
}

export class ThreadOpError extends Error {
  readonly code:
    | 'unknown-thread'
    | 'unknown-agent'
    | 'capacity'
    | 'spawn-failed'
    | 'install-failed'
    | 'not-ready'
    | 'resume-unsupported'
    | 'agent-exited';
  constructor(code: ThreadOpError['code'], message: string) {
    super(message);
    this.name = 'ThreadOpError';
    this.code = code;
  }
}

class RuntimeConsentRefusedError extends AgentLaunchError {
  readonly refusal: 'declined' | 'timeout';
  constructor(refusal: 'declined' | 'timeout', message: string) {
    super('command-not-found', message);
    this.name = 'RuntimeConsentRefusedError';
    this.refusal = refusal;
  }
}

class AuthenticateTimeoutError extends Error {
  constructor() {
    super('authenticate timed out');
    this.name = 'AuthenticateTimeoutError';
  }
}

class PromptCancelledBeforeDispatchError extends Error {
  constructor() {
    super('prompt build cancelled before dispatch');
    this.name = 'PromptCancelledBeforeDispatchError';
  }
}

function threadRestartedDuringSignIn(): ThreadOpError {
  return new ThreadOpError('not-ready', 'the thread was restarted during the sign-in');
}

type Subscriber = (frame: ThreadServerFrame) => void;

interface PendingConsent {
  resolve: (decision: 'granted' | 'declined' | 'timeout' | 'closed') => void;
  timer: ReturnType<typeof setTimeout>;
}

interface LaunchTicket {
  initialPrompt: { content: string; attachments?: readonly AttachmentPart[] } | null;
}

interface ThreadRecord {
  info: ThreadInfo;
  docName?: string;
  agentRef: { source: 'registry' | 'custom'; id: string };
  confirmedContextWindow?: number | null;
  launchSettings?: {
    config?: Record<string, string | boolean>;
    modeId?: string;
    contextWindow?: number;
  };
  cwd: string;
  child: ChildProcess | null;
  conn: ClientConnection | null;
  lastInit: InitializeResponse | null;
  terminalAuthBase: TerminalAuthBase | null;
  agentLaunchPath?: string;
  agentNpmCache?: string | null;
  sessionId: string | null;
  sessionBeforeRestart: {
    sessionId: string | null;
    resumable: ThreadInfo['resumable'];
    contextWindow: ThreadInfo['contextWindow'];
  } | null;
  agentSessionId: string;
  events: ThreadEvent[];
  baseSeq: number;
  logResolved: boolean;
  logResolution: Promise<void> | null;
  midTurnOnDisk: boolean;
  resumeInFlight: boolean;
  authInFlight: boolean;
  launchTicket: LaunchTicket | null;
  suppressUpdates: boolean;
  lastSuppressedAt: number;
  subscribers: Set<Subscriber>;
  pendingPermissions: Map<
    string,
    {
      resolve: (response: RequestPermissionResponse) => void;
      timer: ReturnType<typeof setTimeout>;
      offeredOptionIds: ReadonlySet<string>;
    }
  >;
  reportedToolCalls: Map<string, BrowserCallEvidence>;
  toolCallReportWaiters: Map<string, Array<() => void>>;
  browserInjected: boolean;
  browserNotice: BrowserUnavailableReason | null;
  pendingRuntimeConsent: Map<string, PendingConsent>;
  pendingPiBridgeConsent: Map<string, PendingConsent>;
  piBridgeDeclined: boolean;
  lastPiBridgeStatus: PiBridgeThreadState | null;
  stderrTail: string[];
  drainStderr: (() => Promise<void>) | null;
  authStderr: string[] | null;
  terminals: AcpTerminalSet | null;
  turnActive: boolean;
  cancelRequested: boolean;
  steerStallTimer: ReturnType<typeof setTimeout> | null;
  stallTimer: ReturnType<typeof setTimeout> | null;
  turnStartedAt: number | null;
  agentActivityAt: number;
  unwatchedSince: number | null;
  unwatchedCancelSent: boolean;
  pendingBroadcast: ThreadEvent[];
  pendingBroadcastFromSeq: number;
  flushTimer: ReturnType<typeof setTimeout> | null;
  closed: boolean;
  hadUserMessage: boolean;
  titleHint?: string;
  envNotePending: boolean;
  projectSkill: StagedProjectSkill | null;
  chatGrants: Set<ThreadChatGrant>;
}

export interface HarnessManagedMcpEntryHit {
  editorId: EditorId;
  scope: 'project' | 'user';
  configPath: string;
}

export type PiAcpBridgeProbe = {
  cwd: string;
  bridgePath: string;
  trustPath: string;
} & (
  | { project: 'unavailable'; error: string }
  | {
      project: 'ready';
      canonicalCwd: string;
      bridge: 'absent' | 'own-current' | 'own-stale' | 'foreign' | 'unreadable';
      trust: 'trusted' | 'untrusted' | 'unreadable';
      bridgeLoadable: boolean;
      otherExtensions: readonly string[];
    }
);

export interface PiAcpBridgeEnsureResult {
  ok: boolean;
  bridgePath: string;
  bridge: PiBridgeWriteAction;
  trust: PiTrustWriteAction;
  error?: string;
}

type PiBridgeOutcome = 'loadable' | 'unavailable' | 'unknown';

function isPiBridgeAgent(agentRef: { source: 'registry' | 'custom'; id: string }): boolean {
  return agentRef.source === 'registry' && ACP_AGENT_EDITOR_IDS[agentRef.id] === 'pi';
}

export interface AcpThreadManagerOptions {
  contentDir: string;
  localDir: string;
  globalDir: string | null;
  registry: AcpRegistry;
  permissions: AcpPermissionStore;
  sessionManager: AgentSessionManager;
  agentPresenceBroadcaster?: AgentPresenceBroadcaster | null;
  localApi?: LocalApiDispatch;
  isExcludedPath: (relPath: string) => boolean;
  isIgnoredPath: (relPosix: string) => boolean;
  getLoadedDocText?: (docName: string) => string | null;
  getServerUrl?: () => string;
  getMcpStdioCommand?: () => OkMcpStdioCommand | null | undefined;
  probeHarnessManagedMcpEntry?: (
    editorId: EditorId,
    cwd: string,
  ) => HarnessManagedMcpEntryHit | null | Promise<HarnessManagedMcpEntryHit | null>;
  probePiAcpBridge?: (cwd: string) => PiAcpBridgeProbe | Promise<PiAcpBridgeProbe>;
  hostSnapshot?: () => Promise<HostSnapshot>;
  ensurePiAcpBridge?: (
    cwd: string,
    approvedCanonicalCwd: string,
  ) => PiAcpBridgeEnsureResult | Promise<PiAcpBridgeEnsureResult>;
  runtimeInstall?: {
    root?: string;
    fetchImpl?: typeof fetch;
  };
  resolveLoginShellPath?: () => Promise<string | null>;
  projectSkillSourceDir?: string | null;
  terminalAuthAvailable?: boolean;
  log: PinoLogger;
  maxThreads?: number;
  idleReapMs?: number;
  steerStallMs?: number;
  authenticateTimeoutMs?: number;
  unwatchedTurnCancelMs?: number;
  unwatchedTurnKillMs?: number;
  turnStallMs?: number;
  autoApproveOkTools?: () => boolean;
  agentBrowserTools?: () => boolean;
  resolveBrowserNpx?: typeof resolveBrowserNpx;
  ensureBrowserPackage?: typeof ensureNpmPackageInstalled;
  browserInstallWaitMs?: number;
}

export interface OkMcpStdioCommand {
  command: string;
  args: string[];
  env?: Record<string, string>;
}

export function buildOkMcpStdioCommand(
  localOpCliArgs: readonly string[] | undefined,
  port: number,
  deps?: {
    resolveCommand?: (name: string) => string | null;
    log?: PinoLogger;
    env?: Readonly<Record<string, string | undefined>>;
  },
): OkMcpStdioCommand {
  const server = OkCliCommand.resolve({
    host: localOpCliArgs === undefined ? undefined : { cliArgs: localOpCliArgs },
    ...(deps?.env === undefined ? {} : { env: deps.env }),
  }).stdioServer(['mcp', '--port', String(port)]);
  const { command, args } = server;
  const channel = Object.keys(server.env).length > 0 ? { env: server.env } : {};
  if (command.includes('/') || command.includes('\\')) return { command, args, ...channel };
  const resolved = (deps?.resolveCommand ?? ((name) => resolveOnPath(name, agentSpawnPath())))(
    command,
  );
  if (resolved === null) {
    deps?.log?.warn(
      { command },
      '[acp-threads] OK MCP stdio command did not resolve on PATH — injecting the bare name, which fails for harnesses that spawn MCP children under a minimal PATH',
    );
    return { command, args, ...channel };
  }
  return { command: resolved, args, ...channel };
}

export type OkMcpHostedMarker = 'http-header' | 'stdio-entry-env' | 'unknown' | 'none';

interface InterpreterProbeFailure {
  kind: 'unhealthy' | 'incompatible';
  detail: string;
}

export class AcpThreadManager {
  private readonly opts: AcpThreadManagerOptions;
  private readonly threads = new Map<string, ThreadRecord>();
  private readonly reapTimer: ReturnType<typeof setInterval>;
  private readonly maxThreads: number;
  private readonly idleReapMs: number;
  private readonly steerStallMs: number;
  private readonly authenticateTimeoutMs: number;
  private readonly unwatchedTurnCancelMs: number;
  private readonly unwatchedTurnKillMs: number;
  private readonly turnStallMs: number;
  private readonly browserInstallWaitMs: number;
  private readonly persistence: ThreadPersistenceStore;
  private readonly npxCacheClears = new Map<string, number>();
  private readonly resolveLoginShellPath: () => Promise<string | null>;
  private readonly healthyInterpreters = new Set<string>();
  private projectSkillStaging: Promise<string> | null = null;
  private destroyed = false;
  private initialized = false;

  constructor(opts: AcpThreadManagerOptions) {
    this.opts = opts;
    this.resolveLoginShellPath =
      opts.resolveLoginShellPath ?? (() => getSharedLoginShellPathProvider(opts.log)());
    this.maxThreads = opts.maxThreads ?? MAX_ACP_THREADS;
    this.idleReapMs = opts.idleReapMs ?? DEFAULT_IDLE_REAP_MS;
    this.steerStallMs = opts.steerStallMs ?? DEFAULT_STEER_STALL_MS;
    this.authenticateTimeoutMs = opts.authenticateTimeoutMs ?? DEFAULT_AUTHENTICATE_TIMEOUT_MS;
    this.unwatchedTurnCancelMs = opts.unwatchedTurnCancelMs ?? DEFAULT_UNWATCHED_TURN_CANCEL_MS;
    this.unwatchedTurnKillMs = opts.unwatchedTurnKillMs ?? DEFAULT_UNWATCHED_TURN_KILL_MS;
    this.turnStallMs = opts.turnStallMs ?? DEFAULT_TURN_STALL_MS;
    this.browserInstallWaitMs = opts.browserInstallWaitMs ?? DEFAULT_BROWSER_INSTALL_WAIT_MS;
    const [primaryDir, legacyDir = null] = acpThreadStoreRoots(opts.globalDir, opts.localDir);
    this.persistence = new ThreadPersistenceStore({
      primaryDir,
      legacyDir,
      cwd: opts.globalDir !== null ? opts.contentDir : null,
      log: opts.log,
    });
    this.reapTimer = setInterval(() => this.reapIdleThreads(), REAP_SWEEP_MS);
    this.reapTimer.unref?.();
  }

  async init(): Promise<void> {
    if (this.initialized) return;
    this.initialized = true;
    void this.resolveLoginShellPath().catch(() => {});
    await this.persistence.init();
    const metas = await this.persistence.scan();
    for (const meta of metas) {
      const threadId = meta.info.threadId;
      if (this.threads.has(threadId)) continue;
      this.threads.set(threadId, rehydratedRecord(meta));
    }
    if (metas.length > 0) {
      this.opts.log.info({ count: metas.length }, '[acp-threads] rehydrated archived threads');
    }
  }

  listThreads(): ThreadInfo[] {
    return [...this.threads.values()].map((t) => ({ ...t.info }));
  }

  private liveThreadCount(): number {
    let count = 0;
    for (const t of this.threads.values()) {
      if (t.info.archived !== true) count += 1;
    }
    return count;
  }

  getInfo(threadId: string): ThreadInfo | undefined {
    const t = this.threads.get(threadId);
    return t === undefined ? undefined : { ...t.info };
  }

  async subscribe(threadId: string, sinceSeq: number, sink: Subscriber): Promise<ThreadInfo> {
    const t = this.mustGet(threadId);
    await this.ensureLogResolved(t);
    const from = Math.max(sinceSeq, 0);
    sink({ op: 'subscribed', threadId, fromSeq: from, info: { ...t.info } });
    let diskCursor = from;
    while (diskCursor < t.baseSeq) {
      const target = t.baseSeq;
      await this.persistence.whenIdle(threadId);
      await this.persistence.readEvents(threadId, diskCursor, target, (chunkFrom, events) => {
        sink({ op: 'events', threadId, fromSeq: chunkFrom, events });
      });
      diskCursor = target;
    }
    this.flushBroadcast(t);
    const memFrom = Math.max(from, t.baseSeq);
    const end = t.baseSeq + t.events.length;
    for (let chunkStart = memFrom; chunkStart < end; chunkStart += REPLAY_CHUNK_SIZE) {
      const chunkEnd = Math.min(chunkStart + REPLAY_CHUNK_SIZE, end);
      sink({
        op: 'events',
        threadId,
        fromSeq: chunkStart,
        events: t.events.slice(chunkStart - t.baseSeq, chunkEnd - t.baseSeq),
      });
    }
    t.subscribers.add(sink);
    t.unwatchedSince = null;
    t.unwatchedCancelSent = false;
    return { ...t.info };
  }

  private ensureLogResolved(t: ThreadRecord): Promise<void> {
    if (t.logResolved) return Promise.resolve();
    t.logResolution ??= (async () => {
      try {
        const resolved = await this.persistence.resolveEventLog(t.info.threadId);
        t.baseSeq = resolved.count;
        t.midTurnOnDisk = resolved.midTurn;
        t.info.lastSeq = resolved.count - 1;
        t.logResolved = true;
      } catch (err) {
        t.logResolution = null;
        this.opts.log.error(
          { err, threadId: t.info.threadId },
          '[acp-threads] durable log resolution failed',
        );
        throw err;
      }
    })();
    return t.logResolution;
  }

  unsubscribe(threadId: string, sink: Subscriber): void {
    const t = this.threads.get(threadId);
    if (t === undefined) return;
    t.subscribers.delete(sink);
    if (t.subscribers.size === 0 && t.unwatchedSince === null) {
      t.unwatchedSince = Date.now();
    }
  }

  async createThread(params: {
    agent: { source: 'registry' | 'custom'; id: string };
    prompt?: string;
    attachments?: readonly AttachmentPart[];
    docName?: string;
    titleHint?: string;
    settings?: {
      config?: Record<string, string | boolean>;
      modeId?: string;
      contextWindow?: number;
    };
  }): Promise<ThreadInfo> {
    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    if (this.liveThreadCount() >= this.maxThreads) {
      throw new ThreadOpError('capacity', `maximum of ${this.maxThreads} concurrent agent threads`);
    }

    const { info: agentInfo, custom } = await this.resolveAgentInfo(params.agent);

    // STOP: this await must stay ABOVE the capacity re-check below. The check
    await observeReadiness({
      site: 'acp-thread',
      agentId: custom === null ? (agentIdForAcpAgent(agentInfo.id) ?? agentInfo.id) : agentInfo.id,
      mode: 'acp',
      log: this.opts.log,
      snapshot: this.opts.hostSnapshot,
    });

    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    if (this.liveThreadCount() >= this.maxThreads) {
      throw new ThreadOpError('capacity', `maximum of ${this.maxThreads} concurrent agent threads`);
    }
    const threadId = crypto.randomUUID();
    const now = Date.now();
    const record: ThreadRecord = {
      info: {
        threadId,
        agent: agentInfo,
        title: agentInfo.name,
        status: 'spawning',
        createdAt: now,
        lastActivityAt: now,
        promptCapabilities: null,
        modes: null,
        configOptions: null,
        availableCommands: null,
        lastSeq: -1,
        archived: false,
        resumable: false,
      },
      docName: params.docName,
      agentRef: { source: params.agent.source, id: params.agent.id },
      launchSettings: params.settings,
      cwd: this.opts.contentDir,
      child: null,
      conn: null,
      lastInit: null,
      terminalAuthBase: null,
      sessionId: null,
      sessionBeforeRestart: null,
      agentSessionId: `acp-${threadId}`,
      events: [],
      baseSeq: 0,
      logResolved: true,
      logResolution: null,
      midTurnOnDisk: false,
      resumeInFlight: false,
      authInFlight: false,
      launchTicket: null,
      suppressUpdates: false,
      lastSuppressedAt: 0,
      subscribers: new Set(),
      pendingPermissions: new Map(),
      reportedToolCalls: new Map(),
      toolCallReportWaiters: new Map(),
      browserInjected: false,
      browserNotice: null,
      pendingRuntimeConsent: new Map(),
      pendingPiBridgeConsent: new Map(),
      piBridgeDeclined: false,
      lastPiBridgeStatus: null,
      stderrTail: [],
      drainStderr: null,
      authStderr: null,
      terminals: null,
      turnActive: false,
      cancelRequested: false,
      steerStallTimer: null,
      stallTimer: null,
      turnStartedAt: null,
      agentActivityAt: now,
      unwatchedSince: now,
      unwatchedCancelSent: false,
      pendingBroadcast: [],
      pendingBroadcastFromSeq: 0,
      flushTimer: null,
      closed: false,
      hadUserMessage: false,
      titleHint: params.titleHint,
      envNotePending: false,
      projectSkill: null,
      chatGrants: new Set(),
    };
    this.threads.set(threadId, record);
    const hasContent =
      (params.prompt !== undefined && params.prompt !== '') ||
      (params.attachments !== undefined && params.attachments.length > 0);
    const ticket = beginLaunch(
      record,
      hasContent ? { content: params.prompt ?? '', attachments: params.attachments } : null,
    );
    this.emitStatus(record, 'spawning');

    void this.startThread(record, ticket, params, custom).catch((err) => {
      this.opts.log.error({ err, threadId }, '[acp-threads] thread start failed');
      if (isCurrentLaunch(record, ticket)) {
        this.emitStatus(record, 'error', err instanceof Error ? err.message : String(err));
      }
    });

    return { ...record.info };
  }

  private async resolveAgentInfo(agent: {
    source: 'registry' | 'custom';
    id: string;
  }): Promise<{ info: ThreadAgentInfo; custom: CustomAgentEntry | null }> {
    if (agent.source === 'custom') {
      const custom = (await loadCustomAgents(this.opts.localDir, this.opts.log)).find(
        (c) => c.id === agent.id,
      );
      if (custom === undefined) {
        throw new ThreadOpError('unknown-agent', `no custom agent '${agent.id}'`);
      }
      return { info: { id: custom.id, name: custom.name, source: 'custom' }, custom };
    }
    let manifest: Awaited<ReturnType<AcpRegistry['getAgent']>>;
    try {
      manifest = await this.opts.registry.getAgent(agent.id);
    } catch (err) {
      throw new ThreadOpError(
        'install-failed',
        `agent registry unavailable: ${err instanceof Error ? err.message : String(err)}`,
      );
    }
    if (manifest === undefined) {
      throw new ThreadOpError('unknown-agent', `agent '${agent.id}' is not in the registry`);
    }
    return {
      info: {
        id: manifest.id,
        name: manifest.name,
        iconUrl: manifest.icon,
        source: 'registry',
        version: manifest.version,
      },
      custom: null,
    };
  }

  private async stageProjectSkillFor(record: ThreadRecord): Promise<StagedProjectSkill | null> {
    const source = this.opts.projectSkillSourceDir;
    if (source === null) return null;
    const logContext = { threadId: record.info.threadId, agentId: record.info.agent.id };
    let dir: string;
    try {
      this.projectSkillStaging ??= stageProjectSkill({
        localDir: this.opts.localDir,
        sourceDir: source ?? resolveBundledSkillDir('project', { checkDesktop: false }),
        log: this.opts.log,
        logContext: { localDir: this.opts.localDir },
      }).finally(() => {
        this.projectSkillStaging = null;
      });
      dir = await this.projectSkillStaging;
    } catch (err) {
      this.opts.log.warn({ err, ...logContext }, '[acp-threads] skill staging failed');
      return null;
    }
    if (!isWithin(record.cwd, dir)) {
      this.opts.log.info(
        { ...logContext, cwd: record.cwd, skillDir: dir },
        '[acp-threads] skill staged above agent cwd',
      );
    }
    const skillPath = join(dir, PROJECT_SKILL_ENTRY);
    if (!deliversSkillInline(record.agentRef)) return { skillPath, inlineText: null };
    try {
      return { skillPath, inlineText: await readFile(skillPath, 'utf8') };
    } catch (err) {
      this.opts.log.warn(
        { err, ...logContext, skillPath },
        '[acp-threads] skill inline read failed; skipping skill delivery',
      );
      return null;
    }
  }

  private async connectAgent(
    record: ThreadRecord,
    ticket: LaunchTicket,
    custom: CustomAgentEntry | null,
    acquisition: AcquisitionPolicy = 'reuse',
    consentBudgetMs: number,
    npxLaunchRecovery: NpxLaunchRecovery = 'available',
  ): Promise<{ conn: ClientConnection; init: InitializeResponse; launch: ResolvedLaunch } | null> {
    let launch: ResolvedLaunch | null;
    if (custom !== null) {
      launch = await this.ensureLaunchable(
        record,
        ticket,
        resolveCustomLaunch(custom),
        consentBudgetMs,
      );
    } else {
      const manifest = await this.opts.registry.getAgent(record.agentRef.id);
      if (manifest === undefined) throw new ThreadOpError('unknown-agent', 'agent vanished');
      try {
        launch = await resolveRegistryLaunch(
          manifest,
          registryPlatformKey(),
          this.opts.log,
          undefined,
          (candidate) => this.ensureLaunchable(record, ticket, candidate, consentBudgetMs),
          {
            reacquire: acquisition === 'reacquire',
            install: true,
            onAcquiring: () => {
              if (isCurrentLaunch(record, ticket)) this.emitStatus(record, 'installing');
            },
            onResolved: ({ acquired, outcome, source, elapsedMs }) =>
              this.opts.log.info(
                {
                  threadId: record.info.threadId,
                  agentId: record.info.agent.id,
                  package: acquired,
                  outcome,
                  source,
                  elapsedMs,
                },
                '[acp-threads] agent package acquired',
              ),
          },
        );
      } catch (err) {
        if (
          err instanceof AgentLaunchError &&
          err.npxCacheEntry !== undefined &&
          npxLaunchRecovery === 'available' &&
          (await this.clearStaleNpxCacheEntry(record, ticket, err.npxCacheEntry))
        ) {
          return this.connectAgent(record, ticket, custom, 'reacquire', consentBudgetMs, 'spent');
        }
        throw err;
      }
    }
    if (launch === null || !isCurrentLaunch(record, ticket)) return null;

    const loginShellPath = await this.resolveLoginShellPath().catch(() => null);
    if (!isCurrentLaunch(record, ticket)) return null;

    const projectSkill = await this.stageProjectSkillFor(record);
    if (!isCurrentLaunch(record, ticket)) return null;
    record.projectSkill = projectSkill;

    const terminals = new AcpTerminalSet({
      defaultCwd: record.cwd,
      emit: (event) => this.appendEvent(record, event),
      log: this.opts.log,
      loginShellPath,
    });

    record.terminalAuthBase = terminalAuthBaseFor(launch);
    record.agentLaunchPath = envPath(launch.env);
    record.agentNpmCache = npmCacheOf(launch.env);
    launch = applyLaunchContextWindow(
      launch,
      record.agentRef.id,
      record.launchSettings?.contextWindow ?? null,
    );

    this.emitStatus(record, 'spawning');
    const child = launch.kind === 'npx' ? spawnAcpAgent(launch) : spawnAcpAgent(launch, record.cwd);
    record.child = child;
    record.terminals = terminals;
    const processClosed = new Promise<void>((resolveClosed) =>
      child.once('close', () => resolveClosed()),
    );
    let stderrDrained: Promise<void> | undefined;
    const drainStderr = (): Promise<void> => {
      if (
        child.exitCode === null &&
        child.signalCode === null &&
        child.stdout?.readableEnded !== true &&
        child.stdout?.destroyed !== true
      ) {
        return Promise.resolve();
      }
      stderrDrained ??= new Promise<void>((resolveDrain) => {
        const timer = setTimeout(resolveDrain, 1_000);
        timer.unref();
        void processClosed.then(() => {
          clearTimeout(timer);
          resolveDrain();
        });
      });
      return stderrDrained;
    };
    record.drainStderr = drainStderr;
    let startupStderr = '';
    let rawStartupStderr = '';
    let capturingStartup = true;
    const diagnosticCapture = createDiagnosticStderrCapture(
      (line) => {
        if (capturingStartup)
          startupStderr = `${startupStderr}${line}\n`.slice(-ACQUISITION_DETAIL_MAX_CHARS);
        if (line.trim() === '') return;
        record.stderrTail.push(line.slice(0, 500));
        if (record.stderrTail.length > STDERR_TAIL_LINES) record.stderrTail.shift();
      },
      (rawLine) => {
        if (capturingStartup)
          rawStartupStderr = `${rawStartupStderr}${rawLine}\n`.slice(-ACQUISITION_DETAIL_MAX_CHARS);
      },
    );
    const launchKind = launch.kind;
    let launchSuperseded = false;
    const npxLaunchRecoveryPending = (): boolean =>
      launchKind === 'npx' &&
      capturingStartup &&
      npxLaunchRecovery === 'available' &&
      (staleNpxCacheEntry(rawStartupStderr) !== null || npxInstallRefused(rawStartupStderr));
    const launchStatusMuted = (): boolean =>
      launchSuperseded || npxLaunchRecoveryPending() || !isCurrentLaunch(record, ticket);

    child.stderr?.setEncoding('utf8');
    child.stderr?.on('data', diagnosticCapture.write);
    child.stderr?.on('end', diagnosticCapture.end);
    child.stderr?.on('data', (chunk: string) => {
      for (const line of chunk.split('\n')) {
        if (line.trim() === '') continue;
        if (record.authStderr !== null) {
          record.authStderr.push(line.slice(0, 500));
          if (record.authStderr.length > SIGN_IN_OUTPUT_LINES) record.authStderr.shift();
          record.info.signInOutput = [...record.authStderr];
          this.broadcastInfo(record);
        }
      }
    });
    child.on('error', (err) => {
      if (launchStatusMuted()) return;
      this.emitStatus(record, 'error', `agent failed to start: ${err.message}`, {
        reason: 'connect',
        agentMessage: err.message,
      });
    });
    child.on('exit', (code, signal) => {
      if (record.child !== child) return;
      const reportsCrash = CRASH_REPORT_STATUSES.has(record.info.status);
      record.child = null;
      this.failPendingPermissions(record);
      this.failPendingConsents(record);
      terminals.disposeAll().catch((err: unknown) => {
        this.opts.log.warn(
          { err, threadId: record.info.threadId },
          '[acp-threads] terminal cleanup on agent exit failed',
        );
      });
      void stderrTailDetail(record)
        .then((tail) => {
          if (record.terminals !== terminals) return;
          if (isThreadClosed(record)) return;
          if (launchStatusMuted()) return;
          if (record.info.status === 'error') {
            this.failPendingPermissions(record);
            return;
          }
          const headline = `agent exited (${signal ?? code ?? 'unknown'})`;
          this.opts.log.warn(
            {
              threadId: record.info.threadId,
              agentId: record.info.agent.id,
              code,
              signal,
              machineDetail: tail,
            },
            '[acp-threads] agent exited unexpectedly',
          );
          this.emitStatus(
            record,
            'exited',
            headline,
            reportsCrash ? exitFailureDetail({ exitCode: code, signal, tail }) : undefined,
          );
          this.failPendingPermissions(record);
        })
        .catch((err: unknown) => {
          this.opts.log.error(
            { err, threadId: record.info.threadId },
            '[acp-threads] exit diagnostics failed',
          );
        });
    });

    if (child.stdin === null || child.stdout === null) {
      throw new ThreadOpError('spawn-failed', 'agent process has no stdio');
    }
    const stream = ndJsonStream(
      Writable.toWeb(child.stdin),
      Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>,
    );

    const conn = acpClient({ name: 'open-knowledge' })
      .onRequest(acpMethods.client.session.requestPermission, (ctx) =>
        this.handlePermissionRequest(
          record,
          ctx.params.toolCall,
          ctx.params.options,
          ctx.params._meta,
        ),
      )
      .onRequest(acpMethods.client.fs.readTextFile, async (ctx) => {
        this.touchTurnActivity(record);
        try {
          return await this.handleFsRead(
            ctx.params.path,
            ctx.params.line ?? null,
            ctx.params.limit ?? null,
          );
        } catch (err) {
          this.opts.log.warn(
            {
              err,
              threadId: record.info.threadId,
              agentId: record.info.agent.id,
              path: ctx.params.path,
            },
            '[acp-threads] agent file read failed',
          );
          throw err;
        }
      })
      .onRequest(acpMethods.client.fs.writeTextFile, async (ctx) => {
        try {
          return await this.handleFsWrite(record, ctx.params.path, ctx.params.content);
        } catch (err) {
          this.opts.log.warn(
            {
              err,
              threadId: record.info.threadId,
              agentId: record.info.agent.id,
              path: ctx.params.path,
            },
            '[acp-threads] agent file write failed',
          );
          throw err;
        }
      })
      .onRequest(acpMethods.client.terminal.create, (ctx) => {
        this.touchTurnActivity(record);
        return terminals.create(ctx.params);
      })
      .onRequest(acpMethods.client.terminal.output, (ctx) => {
        this.touchTurnActivity(record);
        return terminals.output(ctx.params.terminalId);
      })
      .onRequest(acpMethods.client.terminal.waitForExit, (ctx) => {
        this.touchTurnActivity(record);
        return terminals.waitForExit(ctx.params.terminalId);
      })
      .onRequest(acpMethods.client.terminal.kill, async (ctx) => {
        this.touchTurnActivity(record);
        await terminals.kill(ctx.params.terminalId);
        return {};
      })
      .onRequest(acpMethods.client.terminal.release, async (ctx) => {
        this.touchTurnActivity(record);
        await terminals.release(ctx.params.terminalId);
        return {};
      })
      .onNotification(acpMethods.client.session.update, (ctx) =>
        this.handleSessionUpdate(record, ctx.params),
      )
      .connect(stream);
    record.conn = conn;
    const settleClosedConnection = async (failure: { err: unknown } | null): Promise<void> => {
      await drainStderr();
      if (record.conn !== conn || launchStatusMuted()) return;
      if (failure !== null) {
        this.opts.log.warn(
          { err: failure.err, threadId: record.info.threadId },
          '[acp-threads] agent connection closed with error',
        );
      }
      if (record.info.status === 'exited' || record.info.status === 'error') return;
      if (failure === null) {
        this.emitStatus(record, 'exited', 'agent connection closed');
        return;
      }
      const { err } = failure;
      this.emitStatus(
        record,
        'error',
        `agent connection failed: ${err instanceof Error ? err.message : String(err)}`,
      );
    };
    conn.closed.then(
      () => settleClosedConnection(null),
      (err: unknown) => settleClosedConnection({ err }),
    );

    let init: InitializeResponse;
    try {
      init = await conn.agent.request(acpMethods.agent.initialize, {
        protocolVersion: PROTOCOL_VERSION,
        clientInfo: { name: 'open-knowledge', title: 'Open Knowledge', version: RUNTIME_VERSION },
        clientCapabilities: {
          fs: { readTextFile: true, writeTextFile: true },
          terminal: true,
          ...(this.opts.terminalAuthAvailable === true ? { auth: { terminal: true } } : {}),
          session: { configOptions: { boolean: {} } },
        },
      });
    } catch (err) {
      this.opts.log.warn(
        { err, threadId: record.info.threadId },
        '[acp-threads] initialize failed',
      );
      if (launch.kind === 'npx' || launch.kind === 'uvx') {
        await drainStderr();
        const acquisitionFailure = packageAcquisitionFailure(launch, startupStderr, err);
        if (acquisitionFailure !== null) throw acquisitionFailure;
      }
      const staleEntry =
        launchKind === 'npx' && npxLaunchRecovery === 'available'
          ? staleNpxCacheEntry(rawStartupStderr)
          : null;
      if (staleEntry !== null && (await this.clearStaleNpxCacheEntry(record, ticket, staleEntry))) {
        launchSuperseded = true;
        return this.connectAgent(record, ticket, custom, 'reacquire', consentBudgetMs, 'spent');
      }
      if (
        launchKind === 'npx' &&
        npxLaunchRecovery === 'available' &&
        npxInstallRefused(rawStartupStderr) &&
        (await this.discardRefusedNpxLaunch(record, ticket, launch))
      ) {
        launchSuperseded = true;
        return this.connectAgent(record, ticket, custom, 'reacquire', consentBudgetMs, 'spent');
      }
      throw new ThreadOpError('spawn-failed', `initialize failed: ${agentErrorMessage(err)}`);
    } finally {
      capturingStartup = false;
      startupStderr = '';
      rawStartupStderr = '';
    }
    if (!isCurrentLaunch(record, ticket)) return null;
    record.lastInit = init;
    record.info.promptCapabilities = init.agentCapabilities?.promptCapabilities ?? {};
    this.emitInfo(record);
    return { conn, init, launch };
  }

  private async discardRefusedNpxLaunch(
    record: ThreadRecord,
    ticket: LaunchTicket,
    launch: ResolvedLaunch,
  ): Promise<boolean> {
    if (!isCurrentLaunch(record, ticket)) return false;
    this.opts.log.warn(
      {
        threadId: record.info.threadId,
        agentId: record.info.agent.id,
        package: refusedNpxPackage(launch.args),
      },
      '[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch',
    );
    await this.discardFailedLaunch(record);
    return isCurrentLaunch(record, ticket);
  }

  private async clearStaleNpxCacheEntry(
    record: ThreadRecord,
    ticket: LaunchTicket,
    entryDir: NpxCacheEntry,
  ): Promise<boolean> {
    const logContext = {
      threadId: record.info.threadId,
      agentId: record.info.agent.id,
      npxCacheEntry: redactDiagnostic(entryDir),
    };
    const outcome = await this.removeStaleNpxCacheEntry(entryDir, logContext);
    if (outcome === 'kept') return false;
    if (!isCurrentLaunch(record, ticket)) {
      if (outcome === 'removed') {
        this.opts.log.warn(
          logContext,
          '[acp-threads] cleared a stale npx cache entry; the launch was closed or superseded, so the agent is not relaunched',
        );
      }
      return false;
    }
    this.opts.log.warn(
      logContext,
      outcome === 'recently-removed'
        ? '[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again'
        : '[acp-threads] cleared a stale npx cache entry; relaunching the agent',
    );
    await this.discardFailedLaunch(record);
    return isCurrentLaunch(record, ticket);
  }

  private async removeStaleNpxCacheEntry(
    entryDir: NpxCacheEntry,
    logContext: Record<string, unknown>,
  ): Promise<'removed' | 'recently-removed' | 'kept'> {
    const clearedAt = this.npxCacheClears.get(entryDir);
    if (clearedAt !== undefined && Date.now() - clearedAt < NPX_CACHE_CLEAR_COOLDOWN_MS) {
      return 'recently-removed';
    }
    const claimedAt = Date.now();
    this.npxCacheClears.set(entryDir, claimedAt);
    const releaseClaim = (): void => {
      if (this.npxCacheClears.get(entryDir) === claimedAt) this.npxCacheClears.delete(entryDir);
    };
    for (const file of ['package.json', 'concurrency.lock']) {
      const code = await stat(join(entryDir, file)).then(
        () => 'present',
        (err: NodeJS.ErrnoException) => err.code ?? 'unknown',
      );
      if (code !== 'ENOENT') {
        this.opts.log.warn(
          { ...logContext, file, code },
          '[acp-threads] leaving an npx cache entry alone',
        );
        releaseClaim();
        return 'kept';
      }
    }
    try {
      await tracedRm(entryDir, { recursive: true, force: true });
    } catch (err) {
      this.opts.log.warn(
        { err, ...logContext },
        '[acp-threads] stale npx cache entry could not be cleared',
      );
      releaseClaim();
      return 'kept';
    }
    return 'removed';
  }

  private async discardFailedLaunch(t: ThreadRecord): Promise<void> {
    t.drainStderr = null;
    t.stderrTail = [];
    await this.stopAgentProcess(t, '[acp-threads] terminal cleanup before relaunch failed');
  }

  private async stopAgentProcess(t: ThreadRecord, terminalCleanupWarning: string): Promise<void> {
    const child = t.child;
    const conn = t.conn;
    const terminals = t.terminals;
    t.child = null;
    t.conn = null;
    t.terminals = null;
    try {
      conn?.close();
    } catch {}
    await terminals?.disposeAll().catch((err: unknown) => {
      this.opts.log.warn({ err, threadId: t.info.threadId }, terminalCleanupWarning);
    });
    if (child !== null) {
      await terminateAgentTree(child, { graceMs: KILL_GRACE_MS });
    }
  }

  private async ensureLaunchable(
    record: ThreadRecord,
    ticket: LaunchTicket,
    launch: ResolvedLaunch,
    consentBudgetMs: number,
  ): Promise<ResolvedLaunch | null> {
    let candidate: ResolvedLaunch;
    try {
      await preflightLaunch(launch);
      candidate = await this.withLoginShellPathIfEligible(launch);
    } catch (err) {
      if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;
      const viaLoginShell = await this.retryWithLoginShellPath(launch);
      if (viaLoginShell === null)
        return this.fallbackToManagedRuntime(
          record,
          ticket,
          launch,
          err,
          undefined,
          consentBudgetMs,
        );
      candidate = viaLoginShell;
    }
    if (!isCurrentLaunch(record, ticket)) return null;
    return this.ensureInterpreterRuns(record, ticket, candidate, consentBudgetMs);
  }

  private async ensureInterpreterRuns(
    record: ThreadRecord,
    ticket: LaunchTicket,
    launch: ResolvedLaunch,
    consentBudgetMs: number,
  ): Promise<ResolvedLaunch | null> {
    if (launch.kind !== 'npx' && launch.kind !== 'uvx') return launch;
    const failure = await this.probeInterpreterOnce(launch);
    if (!isCurrentLaunch(record, ticket)) return null;
    if (failure === null) return launch;

    if (failure.kind === 'incompatible') {
      const preferred = await this.withPreferredLoginShellPathIfEligible(launch);
      if (!isCurrentLaunch(record, ticket)) return null;
      if (envPath(preferred.env) !== envPath(launch.env)) {
        try {
          await preflightLaunch(preferred);
          const preferredFailure = await this.probeInterpreterOnce(preferred);
          if (!isCurrentLaunch(record, ticket)) return null;
          if (preferredFailure === null) {
            this.opts.log.info(
              { threadId: record.info.threadId, agentId: record.info.agent.id },
              '[acp-threads] compatible Node resolved via the preferred login-shell PATH',
            );
            return preferred;
          }
          this.opts.log.debug(
            {
              threadId: record.info.threadId,
              agentId: record.info.agent.id,
              cmd: preferred.cmd,
              kind: preferred.kind,
              failureKind: preferredFailure.kind,
              detail: preferredFailure.detail,
            },
            '[acp-threads] preferred login-shell PATH did not provide a compatible Node',
          );
        } catch (err) {
          if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;
        }
      }
    }

    this.opts.log.warn(
      {
        threadId: record.info.threadId,
        agentId: record.info.agent.id,
        cmd: launch.cmd,
        kind: launch.kind,
        failureKind: failure.kind,
        detail: failure.detail,
      },
      '[acp-threads] interpreter cannot run this agent — offering the managed runtime',
    );
    const incompatible = failure.kind === 'incompatible';
    const declined = new AgentLaunchError(
      'command-not-found',
      incompatible
        ? incompatibleNodeHint(launch, failure.detail)
        : brokenInterpreterHint(launch, failure.detail),
    );
    const expired = new AgentLaunchError(
      'command-not-found',
      incompatible
        ? expiredIncompatibleNodeHint(launch, failure.detail)
        : expiredFallbackHint(launch, declined.message),
    );
    return this.fallbackToManagedRuntime(
      record,
      ticket,
      launch,
      declined,
      { declined, expired },
      consentBudgetMs,
    );
  }

  private async fallbackToManagedRuntime(
    record: ThreadRecord,
    ticket: LaunchTicket,
    launch: ResolvedLaunch,
    cause: AgentLaunchError,
    refusalCauses: { declined: AgentLaunchError; expired: AgentLaunchError } | undefined,
    consentBudgetMs: number,
  ): Promise<ResolvedLaunch | null> {
    if (launch.kind !== 'npx' && launch.kind !== 'uvx') throw cause;
    const runtimeKind = runtimeForInterpreter(launch.kind);
    if (!runtimeDownloadSupported(runtimeKind)) throw cause;
    const runtime = await this.provideManagedRuntime(
      record,
      ticket,
      runtimeKind,
      refusalCauses === undefined ? 'missing' : 'broken',
      consentBudgetMs,
    ).catch((err: unknown) => {
      if (refusalCauses !== undefined && err instanceof RuntimeConsentRefusedError) {
        throw err.refusal === 'timeout' ? refusalCauses.expired : refusalCauses.declined;
      }
      throw err;
    });
    if (runtime === null) return null;
    const rewritten = rewriteLaunchToManagedRuntime(launch, runtime);
    await preflightLaunch(rewritten);
    const brokenManaged = await this.probeInterpreterOnce(rewritten);
    if (brokenManaged === null) return rewritten;
    if (brokenManaged.kind === 'incompatible') {
      throw new AgentLaunchError(
        'install-failed',
        incompatibleManagedRuntimeHint(brokenManaged.detail),
      );
    }
    return this.repairManagedRuntime(
      record,
      ticket,
      launch,
      runtimeKind,
      brokenManaged.detail,
      consentBudgetMs,
    );
  }

  private async repairManagedRuntime(
    record: ThreadRecord,
    ticket: LaunchTicket,
    launch: ResolvedLaunch,
    runtimeKind: ManagedRuntimeKind,
    detail: string,
    consentBudgetMs: number,
  ): Promise<ResolvedLaunch | null> {
    if (!isCurrentLaunch(record, ticket)) return null;
    const logContext = {
      threadId: record.info.threadId,
      agentId: record.info.agent.id,
      runtime: runtimeKind,
      detail,
    };
    this.opts.log.warn(
      logContext,
      "[acp-threads] OK's own managed runtime failed to run — replacing it",
    );
    const cleared = await quarantineManagedRuntime(
      runtimeKind,
      this.opts.log,
      this.opts.runtimeInstall?.root,
    );
    if (!cleared) {
      throw new AgentLaunchError('install-failed', undeletableManagedRuntimeHint(launch, detail));
    }

    const fresh = await this.provideManagedRuntime(
      record,
      ticket,
      runtimeKind,
      'damaged',
      consentBudgetMs,
    ).catch((err: unknown) => {
      if (err instanceof RuntimeConsentRefusedError) {
        throw new AgentLaunchError(
          'command-not-found',
          err.refusal === 'timeout' ? expiredRepairHint(launch) : declinedRepairHint(launch),
        );
      }
      throw err;
    });
    if (fresh === null) return null;
    const rewritten = rewriteLaunchToManagedRuntime(launch, fresh);
    await preflightLaunch(rewritten);
    const stillBroken = await this.probeInterpreterOnce(rewritten);
    if (stillBroken === null) return rewritten;
    this.opts.log.error(
      { ...logContext, detail: stillBroken.detail },
      '[acp-threads] a freshly downloaded managed runtime failed to run',
    );
    throw new AgentLaunchError(
      'install-failed',
      stillBroken.kind === 'incompatible'
        ? incompatibleManagedRuntimeHint(stillBroken.detail)
        : unrepairableManagedRuntimeHint(rewritten, stillBroken.detail),
    );
  }

  private async probeInterpreterOnce(
    launch: ResolvedLaunch,
  ): Promise<InterpreterProbeFailure | null> {
    const healthKey = JSON.stringify([launch.cmd, envPath(launch.env) ?? '']);
    if (this.healthyInterpreters.has(healthKey)) return null;
    const unhealthyDetail = await probeInterpreterHealth(launch, undefined, this.opts.log);
    if (unhealthyDetail !== null) return { kind: 'unhealthy', detail: unhealthyDetail };
    if (launch.kind === 'npx') {
      const incompatibleDetail = await probeNpxNodeCompatibility(launch, undefined, this.opts.log);
      if (incompatibleDetail !== null) {
        return { kind: 'incompatible', detail: incompatibleDetail };
      }
    }
    this.healthyInterpreters.add(healthKey);
    return null;
  }

  private async retryWithLoginShellPath(launch: ResolvedLaunch): Promise<ResolvedLaunch | null> {
    const retry = await this.withLoginShellPathIfEligible(launch);
    if (envPath(retry.env) === envPath(launch.env)) return null;
    try {
      await preflightLaunch(retry);
    } catch (err) {
      if (!(err instanceof AgentLaunchError)) throw err;
      this.opts.log.debug(
        { cmd: launch.cmd, kind: launch.kind },
        '[acp] login-shell PATH did not resolve the command either',
      );
      return null;
    }
    this.opts.log.info(
      { cmd: launch.cmd, kind: launch.kind },
      '[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer',
    );
    return retry;
  }

  private async withLoginShellPathIfEligible(launch: ResolvedLaunch): Promise<ResolvedLaunch> {
    if (launch.pathFromOverlay || isPathQualified(launch.cmd)) return launch;
    const loginShellPath = await this.resolveLoginShellPath().catch(() => null);
    if (loginShellPath === null) return launch;
    return withLoginShellPath(launch, loginShellPath);
  }

  private async withPreferredLoginShellPathIfEligible(
    launch: ResolvedLaunch,
  ): Promise<ResolvedLaunch> {
    if (launch.pathFromOverlay || isPathQualified(launch.cmd)) return launch;
    const loginShellPath = await this.resolveLoginShellPath().catch(() => null);
    if (loginShellPath === null) return launch;
    return withPreferredLoginShellPath(launch, loginShellPath);
  }

  private async provideManagedRuntime(
    record: ThreadRecord,
    ticket: LaunchTicket,
    runtimeKind: ManagedRuntimeKind,
    reason: 'missing' | 'broken' | 'damaged',
    consentBudgetMs: number,
  ): Promise<ManagedRuntime | null> {
    const root = this.opts.runtimeInstall?.root;
    await cleanupManagedRuntimeStaging(runtimeKind, this.opts.log, root);
    const existing = await findManagedRuntime(runtimeKind, root).catch(() => null);
    if (existing !== null) return existing;
    if (!isCurrentLaunch(record, ticket)) return null;

    const decision = await this.requestRuntimeConsent(record, runtimeKind, reason, consentBudgetMs);
    if (decision === 'closed' || !isCurrentLaunch(record, ticket)) return null;
    if (decision !== 'granted') {
      throw new RuntimeConsentRefusedError(
        decision,
        decision === 'timeout' ? expiredRuntimeHint(runtimeKind) : declinedRuntimeHint(runtimeKind),
      );
    }

    try {
      const runtime = await this.downloadRuntime(record, ticket, runtimeKind);
      return isCurrentLaunch(record, ticket) ? runtime : null;
    } catch (err) {
      const name = describeRuntime(runtimeKind).displayName;
      throw new AgentLaunchError(
        'install-failed',
        `couldn't install ${name}: ${err instanceof Error ? err.message : String(err)}`,
      );
    }
  }

  private requestRuntimeConsent(
    record: ThreadRecord,
    runtimeKind: ManagedRuntimeKind,
    reason: 'missing' | 'broken' | 'damaged',
    consentBudgetMs: number,
  ): Promise<'granted' | 'declined' | 'timeout' | 'closed'> {
    const requestId = crypto.randomUUID();
    const d = describeRuntime(runtimeKind);
    this.appendEvent(record, {
      kind: 'runtime_consent_request',
      requestId,
      runtime: runtimeKind,
      displayName: d.displayName,
      provides: d.provides,
      version: d.version,
      approxSizeMB: d.approxSizeMB,
      sourceHost: d.sourceHost,
      agentName: record.info.agent.name,
      reason,
      ts: Date.now(),
    });
    return new Promise((resolvePromise) => {
      const timer = setTimeout(() => {
        record.pendingRuntimeConsent.delete(requestId);
        this.appendEvent(record, {
          kind: 'runtime_consent_resolved',
          requestId,
          decision: 'timeout',
          ts: Date.now(),
        });
        resolvePromise('timeout');
      }, consentBudgetMs);
      timer.unref?.();
      record.pendingRuntimeConsent.set(requestId, { resolve: resolvePromise, timer });
    });
  }

  respondRuntimeConsent(
    threadId: string,
    requestId: string,
    outcome: { kind: 'granted' } | { kind: 'declined' },
  ): void {
    const t = this.mustGet(threadId);
    const pending = t.pendingRuntimeConsent.get(requestId);
    if (pending === undefined) return;
    t.pendingRuntimeConsent.delete(requestId);
    clearTimeout(pending.timer);
    const decision = outcome.kind === 'granted' ? 'granted' : 'declined';
    this.appendEvent(t, {
      kind: 'runtime_consent_resolved',
      requestId,
      decision,
      ts: Date.now(),
    });
    pending.resolve(decision);
  }

  private async downloadRuntime(
    record: ThreadRecord,
    ticket: LaunchTicket,
    runtimeKind: ManagedRuntimeKind,
  ): Promise<ManagedRuntime> {
    this.emitStatus(record, 'installing');
    let lastProgressAt = 0;
    return ensureManagedRuntime(runtimeKind, this.opts.log, {
      root: this.opts.runtimeInstall?.root,
      fetchImpl: this.opts.runtimeInstall?.fetchImpl,
      onProgress: (p) => {
        const now = Date.now();
        if (now - lastProgressAt < RUNTIME_PROGRESS_THROTTLE_MS) return;
        lastProgressAt = now;
        if (!isCurrentLaunch(record, ticket)) return;
        this.appendEvent(record, {
          kind: 'runtime_install_progress',
          runtime: runtimeKind,
          phase: 'downloading',
          receivedBytes: p.receivedBytes,
          totalBytes: p.totalBytes ?? undefined,
          ts: now,
        });
      },
    });
  }

  private async buildMcpServers(
    record: ThreadRecord,
    ticket: LaunchTicket,
    init: InitializeResponse,
    consentBudgetMs: number = CONSENT_TIMEOUT_MS,
  ): Promise<{
    servers: McpServer[];
    hostedMarker: OkMcpHostedMarker;
    browserUnavailable: BrowserUnavailableReason | null;
    browserInjected: boolean;
  }> {
    const servers: McpServer[] = [];
    let browserUnavailable: BrowserUnavailableReason | null = null;
    let browserInjected = false;
    let hostedMarker: OkMcpHostedMarker;
    if (isPiBridgeAgent(record.agentRef)) {
      const outcome = await this.settlePiBridge(record, ticket, consentBudgetMs);
      hostedMarker = outcome === 'unavailable' ? 'none' : 'unknown';
    } else if ((await this.harnessAlreadyHasOkMcp(record)) !== null) {
      hostedMarker = 'unknown';
    } else {
      const serverUrl = this.opts.getServerUrl?.();
      if (serverUrl !== undefined && init.agentCapabilities?.mcpCapabilities?.http === true) {
        servers.push({
          type: 'http',
          name: currentMcpServerName(),
          url: `${serverUrl}/mcp`,
          headers: [{ name: MCP_HOSTED_AGENT_HEADER, value: '1' }],
        });
        hostedMarker = 'http-header';
      } else {
        const stdio = this.opts.getMcpStdioCommand?.();
        const entryPath = agentSpawnPath();
        if (stdio !== null && stdio !== undefined) {
          servers.push({
            name: currentMcpServerName(),
            command: stdio.command,
            args: [...stdio.args],
            env: [
              { name: OK_HOSTED_AGENT_ENV, value: '1' },
              ...(entryPath !== undefined && entryPath !== ''
                ? [{ name: 'PATH', value: entryPath }]
                : []),
              ...Object.entries(stdio.env ?? {}).map(([name, value]) => ({ name, value })),
            ],
          });
          hostedMarker = 'stdio-entry-env';
        } else {
          hostedMarker = 'none';
        }
      }
    }
    if (this.opts.agentBrowserTools?.() === true && isCurrentLaunch(record, ticket)) {
      if (agentGetsBrowser(record.agentRef)) {
        const browser = await this.agentBrowserServer(record, ticket, consentBudgetMs);
        if (typeof browser === 'string') {
          browserUnavailable = browser;
        } else {
          servers.push(browser);
          browserInjected = true;
        }
      } else {
        this.opts.log.info(
          { threadId: record.info.threadId, agentId: record.agentRef.id },
          '[acp-threads] browser tools are on, but only Claude Code and Codex chats get the browser',
        );
      }
    }
    if (hostedMarker === 'none') {
      this.opts.log.warn(
        { threadId: record.info.threadId, agentId: record.agentRef.id },
        '[acp-threads] no OK MCP transport available for this agent — it starts without OK tools',
      );
    } else {
      this.opts.log.info(
        { threadId: record.info.threadId, agentId: record.agentRef.id, hostedMarker },
        '[acp-threads] OK MCP injection outcome',
      );
    }
    return { servers, hostedMarker, browserUnavailable, browserInjected };
  }

  private noteBrowserUnavailable(
    record: ThreadRecord,
    reason: BrowserUnavailableReason | null,
  ): void {
    if (record.browserInjected) {
      record.browserNotice = null;
      return;
    }
    if (reason === null || reason === record.browserNotice) return;
    record.browserNotice = reason;
    this.appendEvent(record, { kind: 'browser_unavailable', reason, ts: Date.now() });
  }

  private async agentBrowserServer(
    record: ThreadRecord,
    ticket: LaunchTicket,
    waitBudgetMs: number,
  ): Promise<McpServerStdio | BrowserUnavailableReason> {
    const context = { threadId: record.info.threadId, agentId: record.agentRef.id };
    const browserRoot = this.opts.globalDir;
    if (browserRoot === null) {
      this.opts.log.warn(
        context,
        '[acp-threads] browser tools are on but there is no per-user OpenKnowledge folder to start the browser from — the chat starts without a browser',
      );
      return 'failed';
    }
    const loginShellPath = await this.resolveLoginShellPath().catch(() => null);
    if (!isCurrentLaunch(record, ticket)) return 'failed';
    const rejectedNpx: string[] = [];
    const npx = (this.opts.resolveBrowserNpx ?? resolveBrowserNpx)(
      [record.agentLaunchPath, loginShellPath, agentSpawnPath()],
      undefined,
      (candidate) => {
        const insideProject =
          isWithin(this.opts.contentDir, candidate) || isWithin(record.cwd, candidate);
        if (!insideProject && browserNpxRunnable(candidate)) return true;
        rejectedNpx.push(candidate);
        return false;
      },
    );
    if (npx === null) {
      this.opts.log.warn(
        { ...context, rejectedNpx },
        '[acp-threads] browser tools are on but no usable npx was found — the chat starts without a browser',
      );
      return 'no-node';
    }
    const npmCache = record.agentNpmCache ?? null;
    let server: McpServerStdio | null;
    try {
      server = agentBrowserMcpServer({
        npx,
        folders: await prepareAgentBrowserFolders(browserRoot, record.info.threadId),
        npmCache,
      });
    } catch (err) {
      this.opts.log.warn(
        { ...context, err },
        '[acp-threads] preparing the browser failed — the chat starts without a browser',
      );
      return 'failed';
    }
    if (server === null) {
      this.opts.log.warn(
        { ...context, npx: npx.npx },
        '[acp-threads] the npx found cannot start the browser — the chat starts without a browser',
      );
      return 'no-node';
    }
    if (!isCurrentLaunch(record, ticket)) return 'failed';
    const waitMs = Math.min(this.browserInstallWaitMs, waitBudgetMs);
    let waitTimer: ReturnType<typeof setTimeout> | undefined;
    const installed = await Promise.race([
      this.installBrowserPackage(record, npx, npmCache),
      new Promise<'still-installing'>((resolve) => {
        waitTimer = setTimeout(() => resolve('still-installing'), waitMs);
        waitTimer.unref?.();
      }),
    ]).finally(() => clearTimeout(waitTimer));
    if (installed === 'still-installing') {
      this.opts.log.warn(
        { ...context, waitedMs: waitMs },
        '[acp-threads] installing the browser is taking too long — the chat starts without a browser',
      );
      return 'failed';
    }
    if (!installed) return 'failed';
    this.opts.log.info(
      { ...context, command: server.command, npx: npx.npx },
      '[acp-threads] browser MCP injected',
    );
    return server;
  }

  private async installBrowserPackage(
    record: ThreadRecord,
    npx: ResolvedBrowserNpx,
    npmCache: string | null,
    packageData: BrowserPackageData = 'cached',
    npxCacheRecovery: NpxLaunchRecovery = 'available',
  ): Promise<boolean> {
    const context = { threadId: record.info.threadId, agentId: record.agentRef.id };
    const ensure = this.opts.ensureBrowserPackage ?? ensureNpmPackageInstalled;
    const launch = agentBrowserInstallLaunch(npx, npmCache, packageData);
    try {
      await ensure(launch, AGENT_BROWSER_MCP_PACKAGE, this.opts.log, { reacquire: true });
      return true;
    } catch (err) {
      if (
        err instanceof AgentLaunchError &&
        err.npxCacheEntry !== undefined &&
        npxCacheRecovery === 'available'
      ) {
        const logContext = { ...context, npxCacheEntry: redactDiagnostic(err.npxCacheEntry) };
        const removal = await this.removeStaleNpxCacheEntry(err.npxCacheEntry, logContext);
        if (removal !== 'kept') {
          this.opts.log.warn(
            logContext,
            removal === 'removed'
              ? '[acp-threads] cleared a stale browser npx cache entry; reinstalling the browser'
              : '[acp-threads] browser npx cache entry was cleared by another launch moments ago; reinstalling the browser without clearing it again',
          );
          return this.installBrowserPackage(record, npx, npmCache, packageData, 'spent');
        }
      }
      if (packageData === 'cached') {
        this.opts.log.info(
          { ...context, err },
          "[acp-threads] installing the browser from npm's cached package data failed; installing it again with fresh package data",
        );
        return this.installBrowserPackage(record, npx, npmCache, 'fresh', npxCacheRecovery);
      }
      this.opts.log.warn(
        { ...context, err },
        '[acp-threads] installing the browser failed — the chat starts without a browser',
      );
      return false;
    }
  }

  private async harnessAlreadyHasOkMcp(
    record: ThreadRecord,
  ): Promise<HarnessManagedMcpEntryHit | null> {
    const probe = this.opts.probeHarnessManagedMcpEntry;
    if (probe === undefined || record.agentRef.source !== 'registry') return null;
    const editorId = ACP_AGENT_EDITOR_IDS[record.agentRef.id];
    if (editorId === undefined) return null;
    let hit: HarnessManagedMcpEntryHit | null;
    try {
      hit = await probe(editorId, record.cwd);
    } catch (err) {
      this.opts.log.warn(
        { err, threadId: record.info.threadId, editorId },
        '[acp-threads] harness MCP-config probe failed — injecting OK MCP',
      );
      return null;
    }
    if (hit !== null) {
      this.opts.log.info(
        {
          threadId: record.info.threadId,
          agentId: record.agentRef.id,
          editorId: hit.editorId,
          scope: hit.scope,
          configPath: hit.configPath,
        },
        "[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry",
      );
    }
    return hit;
  }

  private async settlePiBridge(
    record: ThreadRecord,
    ticket: LaunchTicket,
    consentBudgetMs: number,
  ): Promise<PiBridgeOutcome> {
    const probe = this.opts.probePiAcpBridge;
    const threadId = record.info.threadId;
    if (probe === undefined) {
      this.opts.log.debug(
        { threadId, agentId: record.agentRef.id },
        '[acp-threads] no Pi bridge probe wired — OK tools depend on whether the project was already wired',
      );
      return 'unknown';
    }
    let state: PiAcpBridgeProbe;
    try {
      state = await probe(record.cwd);
    } catch (err) {
      this.opts.log.warn({ err, threadId }, '[acp-threads] Pi bridge probe failed');
      return 'unknown';
    }
    if (!isCurrentLaunch(record, ticket)) return 'unknown';
    if (state.project === 'unavailable') {
      this.opts.log.warn(
        { threadId, cwd: state.cwd, err: new Error(state.error) },
        '[acp-threads] Pi project folder is unavailable; this thread has no OK tools',
      );
      this.emitPiBridgeStatus(record, {
        kind: 'pi_bridge_status',
        state: 'project-path-unavailable',
        bridgePath: state.bridgePath,
        detail: state.error,
        ts: Date.now(),
      });
      return 'unavailable';
    }
    if (state.bridgeLoadable) {
      this.opts.log.info(
        { threadId, bridge: state.bridge, bridgePath: state.bridgePath },
        '[acp-threads] Pi already loads the OK bridge extension for this project',
      );
      return 'loadable';
    }
    if (state.bridge === 'foreign' || state.bridge === 'unreadable') {
      this.opts.log.warn(
        { threadId, bridge: state.bridge, bridgePath: state.bridgePath },
        "[acp-threads] OK can't claim the Pi bridge path — leaving it alone; this thread has no OK tools",
      );
      this.emitPiBridgeStatus(record, {
        kind: 'pi_bridge_status',
        state: state.bridge === 'foreign' ? 'foreign-file' : 'unreadable-file',
        bridgePath: state.bridgePath,
        ts: Date.now(),
      });
      return 'unavailable';
    }
    if (record.piBridgeDeclined) {
      this.opts.log.debug(
        { threadId },
        '[acp-threads] Pi bridge prompt already declined for this thread — not re-asking',
      );
      return 'unavailable';
    }
    const ensure = this.opts.ensurePiAcpBridge;
    if (ensure === undefined) {
      this.opts.log.warn(
        { threadId },
        '[acp-threads] Pi bridge is not provisioned and no provisioning seam is wired — not prompting',
      );
      return 'unavailable';
    }

    const requestId = crypto.randomUUID();
    const decision = await this.requestPiBridgeConsent(record, requestId, state, consentBudgetMs);
    if (decision === 'declined') record.piBridgeDeclined = true;
    if (!isCurrentLaunch(record, ticket)) return 'unknown';
    if (decision !== 'granted') {
      this.opts.log.info(
        { threadId, decision },
        '[acp-threads] Pi bridge not provisioned — the thread continues without OK tools',
      );
      return 'unavailable';
    }

    let result: PiAcpBridgeEnsureResult;
    try {
      result = await ensure(record.cwd, state.canonicalCwd);
    } catch (err) {
      const detail = err instanceof Error ? err.message : String(err);
      this.opts.log.warn({ err, threadId }, '[acp-threads] Pi bridge provisioning threw');
      this.appendPiBridgeFailure(record, ticket, requestId, 'bridge-failed', state.bridgePath, {
        detail,
      });
      return 'unavailable';
    }
    if (result.ok) {
      this.opts.log.info(
        { threadId, bridge: result.bridge, trust: result.trust, bridgePath: result.bridgePath },
        '[acp-threads] provisioned the Pi bridge extension for this project',
      );
      if (!isCurrentLaunch(record, ticket)) return 'unknown';
      this.appendEvent(record, {
        kind: 'pi_bridge_status',
        requestId,
        state: 'ready',
        bridgePath: result.bridgePath,
        bridge: result.bridge,
        trust: result.trust,
        ts: Date.now(),
      });
      return 'loadable';
    }
    const bridgeLanded =
      result.bridge === 'written' || result.bridge === 'refreshed' || result.bridge === 'unchanged';
    const state2: PiBridgeThreadState =
      result.bridge === 'refused-project-path'
        ? 'project-path-unavailable'
        : result.bridge === 'refused-foreign'
          ? 'foreign-file'
          : result.bridge === 'refused-unreadable'
            ? 'unreadable-file'
            : bridgeLanded
              ? 'trust-failed'
              : 'bridge-failed';
    this.opts.log.warn(
      {
        threadId,
        bridge: result.bridge,
        trust: result.trust,
        bridgePath: result.bridgePath,
        err: result.error,
      },
      '[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools',
    );
    this.appendPiBridgeFailure(record, ticket, requestId, state2, result.bridgePath, {
      bridge: result.bridge,
      trust: result.trust,
      ...(result.error !== undefined ? { detail: result.error } : {}),
    });
    return 'unavailable';
  }

  private appendPiBridgeFailure(
    record: ThreadRecord,
    ticket: LaunchTicket,
    requestId: string,
    state: PiBridgeThreadState,
    bridgePath: string,
    extra: { bridge?: PiBridgeWriteAction; trust?: PiTrustWriteAction; detail?: string },
  ): void {
    if (!isCurrentLaunch(record, ticket)) return;
    this.appendEvent(record, {
      kind: 'pi_bridge_status',
      requestId,
      state,
      bridgePath,
      ...extra,
      ts: Date.now(),
    });
  }

  private emitPiBridgeStatus(
    record: ThreadRecord,
    event: Extract<ThreadEvent, { kind: 'pi_bridge_status' }>,
  ): void {
    if (record.lastPiBridgeStatus === event.state) return;
    record.lastPiBridgeStatus = event.state;
    this.appendEvent(record, event);
  }

  private requestPiBridgeConsent(
    record: ThreadRecord,
    requestId: string,
    state: Extract<PiAcpBridgeProbe, { project: 'ready' }>,
    budgetMs: number,
  ): Promise<'granted' | 'declined' | 'timeout' | 'closed'> {
    this.appendEvent(record, {
      kind: 'pi_bridge_consent_request',
      requestId,
      agentName: record.info.agent.name,
      bridgePath: state.bridgePath,
      cwd: state.canonicalCwd,
      otherExtensions: state.otherExtensions,
      ts: Date.now(),
    });
    return new Promise((resolvePromise) => {
      const timer = setTimeout(() => {
        record.pendingPiBridgeConsent.delete(requestId);
        this.appendEvent(record, {
          kind: 'pi_bridge_consent_resolved',
          requestId,
          decision: 'timeout',
          ts: Date.now(),
        });
        resolvePromise('timeout');
      }, budgetMs);
      timer.unref?.();
      record.pendingPiBridgeConsent.set(requestId, { resolve: resolvePromise, timer });
    });
  }

  respondPiBridgeConsent(
    threadId: string,
    requestId: string,
    outcome: { kind: 'granted' } | { kind: 'declined' },
  ): void {
    const t = this.mustGet(threadId);
    const pending = t.pendingPiBridgeConsent.get(requestId);
    if (pending === undefined) return;
    t.pendingPiBridgeConsent.delete(requestId);
    clearTimeout(pending.timer);
    const decision = outcome.kind === 'granted' ? 'granted' : 'declined';
    this.appendEvent(t, {
      kind: 'pi_bridge_consent_resolved',
      requestId,
      decision,
      ts: Date.now(),
    });
    pending.resolve(decision);
  }

  private async startThread(
    record: ThreadRecord,
    ticket: LaunchTicket,
    params: {
      agent: { source: 'registry' | 'custom'; id: string };
      settings?: {
        config?: Record<string, string | boolean>;
        modeId?: string;
        contextWindow?: number;
      };
    },
    custom: CustomAgentEntry | null,
    consentBudgetMs: number = CONSENT_TIMEOUT_MS,
    acquisition: AcquisitionPolicy = 'reuse',
  ): Promise<void> {
    let handshake: Awaited<ReturnType<AcpThreadManager['connectAgent']>>;
    try {
      handshake = await this.connectAgent(record, ticket, custom, acquisition, consentBudgetMs);
    } catch (err) {
      const failure = await connectionFailureDetail(
        err,
        record,
        isCurrentLaunch(record, ticket) || isThreadClosed(record),
      );
      await this.failLaunch(record, ticket, failure.agentMessage, failure);
      return;
    }
    if (handshake === null) return;
    const { conn, init, launch } = handshake;

    if (
      (await this.openSession(
        record,
        ticket,
        conn,
        init,
        params.settings,
        'park',
        consentBudgetMs,
      )) !== true
    ) {
      return;
    }
    if (!isCurrentLaunch(record, ticket)) return;
    this.opts.log.info(
      {
        threadId: record.info.threadId,
        agentId: record.info.agent.id,
        launchKind: launch.kind,
        msToReady: Date.now() - record.info.createdAt,
      },
      '[acp-threads] agent ready',
    );

    const prompt = ticket.initialPrompt;
    ticket.initialPrompt = null;
    if (prompt !== null) {
      this.sendPrompt(record.info.threadId, prompt.content, prompt.attachments);
    }
  }

  private async openSession(
    record: ThreadRecord,
    ticket: LaunchTicket,
    conn: ClientConnection,
    init: InitializeResponse,
    settings?: { config?: Record<string, string | boolean>; modeId?: string },
    onAuthRequired: 'park' | 'report' = 'park',
    consentBudgetMs: number = CONSENT_TIMEOUT_MS,
  ): Promise<boolean | 'auth-required'> {
    record.info.availableCommands = null;
    const {
      servers: mcpServers,
      browserUnavailable,
      browserInjected,
    } = await this.buildMcpServers(record, ticket, init, consentBudgetMs);
    if (!isCurrentLaunch(record, ticket)) return false;
    record.browserInjected = browserInjected;
    this.noteBrowserUnavailable(record, browserUnavailable);
    try {
      const session = await conn.agent.request(acpMethods.agent.session.new, {
        cwd: record.cwd,
        mcpServers,
      });
      if (!isCurrentLaunch(record, ticket)) return false;
      record.sessionId = session.sessionId;
      record.info.resumable = resumableFromCapabilities(init);
      record.confirmedContextWindow = appliedContextWindow(record);
      record.info.contextWindow = record.confirmedContextWindow;
      record.envNotePending = true;
      this.persistence.queueMetaWrite(record.info.threadId, this.buildMeta(record));
      if (session.modes !== undefined && session.modes !== null) {
        record.info.modes = session.modes;
        this.emitInfo(record);
      }
      if (session.configOptions !== undefined && session.configOptions !== null) {
        record.info.configOptions = session.configOptions;
        this.emitInfo(record);
      }
    } catch (err) {
      const agentMessage = agentErrorMessage(err);
      if (isAuthRequiredError(err)) {
        const detail = `sign in required: ${agentMessage}`;
        const failure: ThreadFailureDetail = {
          reason: 'auth-required',
          agentMessage,
          machineDetail: authMachineDetail(err, record),
          authMethods: threadAuthMethods(init.authMethods, record.terminalAuthBase),
        };
        if (!isCurrentLaunch(record, ticket)) {
          this.logSuppressedStatus(record, 'auth_required', detail, failure);
          return false;
        }
        if (onAuthRequired === 'report') return 'auth-required';
        this.emitStatus(record, 'auth_required', detail, failure);
        return false;
      }
      const ownsStderrTail = isCurrentLaunch(record, ticket) || isThreadClosed(record);
      await this.failLaunch(record, ticket, `session setup failed: ${agentMessage}`, {
        reason: 'session-setup',
        agentMessage,
        machineDetail: joinMachineDetail({
          primary: agentErrorData(err),
          tail: ownsStderrTail ? await stderrTailDetail(record) : undefined,
        }),
      });
      return false;
    }
    if (!isCurrentLaunch(record, ticket)) return false;

    if (settings?.config !== undefined) {
      await this.applyInitialConfig(record, ticket, conn, settings.config);
      if (!isCurrentLaunch(record, ticket)) return false;
    }
    if (settings?.modeId !== undefined) {
      await this.applyInitialMode(record, ticket, conn, settings.modeId);
      if (!isCurrentLaunch(record, ticket)) return false;
    }

    this.emitStatus(record, 'ready');
    return true;
  }

  async resumeThread(
    threadId: string,
    prompt?: string,
    attachments?: readonly AttachmentPart[],
  ): Promise<ThreadInfo> {
    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    const t = this.mustGet(threadId);
    if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');
    if (t.info.archived !== true) {
      throw new ThreadOpError('not-ready', 'thread is not archived');
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'a resume is already in progress');
    }
    if (this.liveThreadCount() >= this.maxThreads) {
      throw new ThreadOpError('capacity', `maximum of ${this.maxThreads} concurrent agent threads`);
    }
    t.resumeInFlight = true;
    const startedAt = Date.now();
    try {
      await this.ensureLogResolved(t);
      const sessionId = t.sessionId;
      const { info: agentInfo, custom } = await this.resolveAgentInfo(t.agentRef);
      if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
      if (this.liveThreadCount() >= this.maxThreads) {
        throw new ThreadOpError(
          'capacity',
          `maximum of ${this.maxThreads} concurrent agent threads`,
        );
      }
      const ticket = beginLaunch(t);
      t.info.agent = agentInfo;
      t.info.archived = false;
      t.info.availableCommands = null;
      t.stderrTail = [];
      if (t.midTurnOnDisk) {
        t.midTurnOnDisk = false;
        this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });
      }
      const hasContent =
        (prompt !== undefined && prompt !== '') ||
        (attachments !== undefined && attachments.length > 0);
      if (hasContent) {
        this.echoUserMessage(t, prompt ?? '', attachments);
        this.flushBroadcast(t);
      }
      this.emitStatus(t, 'spawning');
      try {
        if (sessionId === null) {
          this.opts.log.warn(
            { threadId, agentId: t.info.agent.id, cause: 'no-session' },
            '[acp-threads] thread is not resumable',
          );
          throw new ThreadOpError(
            'resume-unsupported',
            'this thread never completed an agent session',
          );
        }
        const handshake = await this.connectAgent(
          t,
          ticket,
          custom,
          'reuse',
          BLOCKING_CONSENT_TIMEOUT_MS,
        );
        if (handshake === null) {
          throw new ThreadOpError('not-ready', 'thread closed during resume');
        }
        const { conn, init } = handshake;
        t.info.resumable = resumableFromCapabilities(init);
        t.confirmedContextWindow = appliedContextWindow(t);
        t.info.contextWindow = t.confirmedContextWindow;
        const {
          servers: mcpServers,
          browserUnavailable,
          browserInjected,
        } = await this.buildMcpServers(t, ticket, init, BLOCKING_CONSENT_TIMEOUT_MS);
        if (!isCurrentLaunch(t, ticket)) {
          throw new ThreadOpError('not-ready', 'thread closed during resume');
        }
        t.browserInjected = browserInjected;
        this.noteBrowserUnavailable(t, browserUnavailable);
        const caps = init.agentCapabilities;
        const viaResume = caps?.sessionCapabilities?.resume != null;
        let response: { modes?: unknown; configOptions?: unknown };
        if (viaResume) {
          response = await conn.agent.request(acpMethods.agent.session.resume, {
            sessionId,
            cwd: t.cwd,
            mcpServers,
          });
        } else if (caps?.loadSession === true) {
          t.suppressUpdates = true;
          t.lastSuppressedAt = Date.now();
          try {
            response = await conn.agent.request(acpMethods.agent.session.load, {
              sessionId,
              cwd: t.cwd,
              mcpServers,
            });
            await this.awaitReplayQuiescence(t);
          } finally {
            t.suppressUpdates = false;
          }
        } else {
          this.opts.log.warn(
            { threadId, agentId: t.info.agent.id, cause: 'no-resume-capability' },
            '[acp-threads] thread is not resumable',
          );
          throw new ThreadOpError(
            'resume-unsupported',
            `${t.info.agent.name} doesn't support resuming previous sessions`,
          );
        }
        if (!isCurrentLaunch(t, ticket)) {
          throw new ThreadOpError('not-ready', 'thread closed during resume');
        }
        t.sessionId = sessionId;
        const resumedConfig: Record<string, string | boolean> = Object.fromEntries(
          (t.info.configOptions ?? []).map((option) => [option.id, option.currentValue]),
        );
        const resumedModeId = t.info.modes?.currentModeId;
        const modes = response.modes as ThreadInfo['modes'] | undefined;
        if (modes !== undefined && modes !== null) t.info.modes = modes;
        const configOptions = response.configOptions as ThreadInfo['configOptions'] | undefined;
        if (configOptions !== undefined && configOptions !== null) {
          t.info.configOptions = configOptions;
        }
        await this.applyInitialConfig(t, ticket, conn, resumedConfig, configOptions == null);
        if (!isCurrentLaunch(t, ticket)) {
          throw new ThreadOpError('not-ready', 'thread closed during resume');
        }
        if (resumedModeId !== undefined) {
          await this.applyInitialMode(t, ticket, conn, resumedModeId, modes == null);
          if (!isCurrentLaunch(t, ticket)) {
            throw new ThreadOpError('not-ready', 'thread closed during resume');
          }
        }
        this.emitStatus(t, 'ready');
        this.opts.log.info(
          {
            threadId,
            agentId: t.info.agent.id,
            method: viaResume ? 'session/resume' : 'session/load',
            msToResumed: Date.now() - startedAt,
          },
          '[acp-threads] thread resumed',
        );
        if (hasContent) {
          this.dispatchPrompt(t, prompt ?? '', attachments, { echo: false });
        }
        return { ...t.info };
      } catch (err) {
        await this.abortResume(t, await connectionFailureDetail(err, t, true));
        if (err instanceof ThreadOpError) throw err;
        if (err instanceof AgentLaunchError) {
          throw new ThreadOpError(
            err.code === 'install-failed' ? 'install-failed' : 'spawn-failed',
            err.message,
          );
        }
        this.opts.log.warn({ err, threadId }, '[acp-threads] resume rejected by the agent');
        throw new ThreadOpError(
          'resume-unsupported',
          `couldn't resume the previous session: ${agentErrorMessage(err)}`,
        );
      }
    } finally {
      t.resumeInFlight = false;
    }
  }

  hasStartedWork(threadId: string): boolean {
    const t = this.threads.get(threadId);
    if (t === undefined) return false;
    return t.events.some((event) => event.kind === 'user_message');
  }

  async setContextWindow(threadId: string, tokens: number): Promise<ThreadInfo> {
    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    const t = this.mustGet(threadId);
    this.assertContextWindowChangeable(t, tokens);
    const { custom } = await this.resolveAgentInfo(t.agentRef);
    this.assertContextWindowChangeable(t, tokens);

    const previousWindow = t.launchSettings?.contextWindow;
    const previousConfirmed = t.confirmedContextWindow ?? null;
    t.launchSettings = { ...t.launchSettings, contextWindow: Math.floor(tokens) };
    t.resumeInFlight = true;
    const carried = t.launchTicket?.initialPrompt ?? null;
    const ticket = beginLaunch(t);
    let applied = false;
    t.sessionBeforeRestart = {
      sessionId: t.sessionId,
      resumable: t.info.resumable,
      contextWindow: t.info.contextWindow,
    };
    try {
      await this.teardownFailedAgent(t);
      t.stderrTail = [];
      t.cancelRequested = false;
      t.turnActive = false;
      this.emitStatus(t, 'spawning');
      await this.startThread(
        t,
        ticket,
        { agent: t.agentRef, settings: t.launchSettings },
        custom,
        BLOCKING_CONSENT_TIMEOUT_MS,
      );
      if (!isCurrentLaunch(t, ticket)) {
        throw new ThreadOpError('not-ready', 'thread closed during the context window change');
      }
      const settled = this.getInfo(threadId)?.status;
      if (settled === 'ready' || settled === 'running') {
        applied = true;
        if (carried !== null) {
          this.dispatchPrompt(t, carried.content, carried.attachments, { echo: true });
        }
        return { ...t.info };
      }
      throw new ThreadOpError(
        'spawn-failed',
        lastFailureMessage(t) ?? 'the agent failed to start with that context window',
      );
    } catch (err) {
      if (err instanceof ThreadOpError) throw err;
      const detail = err instanceof Error ? err.message : String(err);
      this.emitStatus(t, 'error', detail, { reason: 'connect', agentMessage: detail });
      throw new ThreadOpError('spawn-failed', detail);
    } finally {
      if (!applied && carried !== null) {
        this.opts.log.info(
          { threadId, agentId: t.agentRef.id },
          '[acp-threads] pending first message dropped: the context window change did not start the agent',
        );
      }
      if (!applied && this.threads.has(threadId)) {
        t.launchSettings = { ...t.launchSettings, contextWindow: previousWindow };
        t.confirmedContextWindow = previousConfirmed;
        t.info.contextWindow =
          this.getInfo(threadId)?.status === 'ready' ? previousConfirmed : null;
        this.endRestart(t);
        this.emitInfo(t);
      }
      t.sessionBeforeRestart = null;
      t.resumeInFlight = false;
    }
  }

  private assertContextWindowChangeable(t: ThreadRecord, tokens: number): void {
    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');
    if (!Number.isFinite(tokens) || tokens <= 0) {
      throw new ThreadOpError('not-ready', 'a context window must be a positive number of tokens');
    }
    const change = contextWindowChangeFor({
      agentId: t.agentRef.id,
      archived: t.info.archived === true,
      turnActive: t.turnActive,
      hasStartedWork: this.hasStartedWork(t.info.threadId),
    });
    if (change.kind === 'unsupported') {
      throw new ThreadOpError('not-ready', 'this agent takes its context window from the model');
    }
    if (change.kind === 'needs-new-chat') {
      throw new ThreadOpError('not-ready', 'start a new chat to change the context window');
    }
    if (t.resumeInFlight) throw new ThreadOpError('not-ready', 'a restart is already in progress');
  }

  async retryThread(threadId: string): Promise<ThreadInfo> {
    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    const t = this.mustGet(threadId);
    this.assertRetryable(t);
    const { info: agentInfo, custom } = await this.resolveAgentInfo(t.agentRef);
    this.assertRetryable(t);
    t.resumeInFlight = true;
    const ticket = beginLaunch(t);
    t.sessionBeforeRestart = {
      sessionId: t.sessionId,
      resumable: t.info.resumable,
      contextWindow: t.info.contextWindow,
    };
    try {
      resetSharedLoginShellPathProvider();
      this.healthyInterpreters.clear();
      await this.teardownFailedAgent(t);
      t.info.agent = agentInfo;
      t.stderrTail = [];
      t.cancelRequested = false;
      t.turnActive = false;
      this.emitStatus(t, 'spawning');
      try {
        await this.startThread(
          t,
          ticket,
          { agent: t.agentRef, settings: t.launchSettings },
          custom,
          BLOCKING_CONSENT_TIMEOUT_MS,
          'reacquire',
        );
      } catch (err) {
        const detail = err instanceof Error ? err.message : String(err);
        this.emitStatus(t, 'error', detail, { reason: 'connect', agentMessage: detail });
        throw new ThreadOpError('spawn-failed', detail);
      }
      if (!isCurrentLaunch(t, ticket)) {
        throw new ThreadOpError('not-ready', 'thread closed during retry');
      }
      const settled = this.getInfo(threadId)?.status;
      if (settled === 'ready' || settled === 'running') {
        this.opts.log.info(
          { threadId, agentId: t.info.agent.id },
          '[acp-threads] thread retry succeeded',
        );
        return { ...t.info };
      }
      throw new ThreadOpError('spawn-failed', lastFailureMessage(t) ?? 'the agent failed to start');
    } finally {
      if (this.threads.has(threadId) && this.endRestart(t)) this.emitInfo(t);
      t.resumeInFlight = false;
    }
  }

  private assertRetryable(t: ThreadRecord): void {
    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');
    if (t.info.archived === true) {
      throw new ThreadOpError('not-ready', 'the thread is archived — resume it instead');
    }
    if (t.info.status !== 'error' && t.info.status !== 'auth_required' && !t.authInFlight) {
      throw new ThreadOpError('not-ready', 'this thread did not fail to start');
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'a retry is already in progress');
    }
  }

  terminalAuthLaunch(threadId: string, methodId: string): ThreadAuthTerminalLaunch {
    const t = this.mustGet(threadId);
    const launch = terminalAuthLaunch(t.lastInit?.authMethods, t.terminalAuthBase, methodId);
    if (launch === null) {
      throw new ThreadOpError('not-ready', 'this agent offers no terminal sign-in by that name');
    }
    return launch;
  }

  async authenticateThread(threadId: string, methodId: string): Promise<ThreadInfo> {
    if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
    const t = this.mustGet(threadId);
    if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');
    if (t.info.archived === true) {
      throw new ThreadOpError('not-ready', 'the thread is archived — resume it instead');
    }
    if (t.info.status !== 'auth_required') {
      throw new ThreadOpError('not-ready', 'this thread is not waiting for a sign-in');
    }
    const conn = t.conn;
    const init = t.lastInit;
    const ticket = t.launchTicket;
    if (conn === null || init === null || t.child === null || ticket === null) {
      throw new ThreadOpError(
        'not-ready',
        `${t.info.agent.name} is no longer running — use Retry to start it again`,
      );
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'the thread is starting over — wait for the retry');
    }
    if (t.authInFlight) {
      throw new ThreadOpError('not-ready', 'a sign-in is already in progress');
    }
    t.authInFlight = true;
    t.authStderr = [];
    t.info.signInOutput = undefined;
    try {
      this.emitStatus(t, 'authenticating');
      try {
        await this.requestAuthenticate(conn, methodId);
      } catch (err) {
        await t.drainStderr?.();
        if (t.conn !== conn) throw threadRestartedDuringSignIn();
        const timedOut = err instanceof AuthenticateTimeoutError;
        const message = timedOut
          ? `the sign-in didn't complete in time — try again`
          : agentErrorMessage(err);
        if (t.child === null) throw new ThreadOpError('agent-exited', message);
        this.emitStatus(t, 'auth_required', `sign-in failed: ${message}`, {
          reason: 'auth-required',
          agentMessage: message,
          machineDetail: authMachineDetail(err, t),
          authMethods: threadAuthMethods(init.authMethods, t.terminalAuthBase),
        });
        throw new ThreadOpError('not-ready', message);
      }
      if (isThreadClosed(t)) throw new ThreadOpError('not-ready', 'thread closed during sign-in');
      if (t.conn !== conn) throw threadRestartedDuringSignIn();
      const opened = await this.openSession(
        t,
        ticket,
        conn,
        init,
        t.launchSettings,
        'report',
        BLOCKING_CONSENT_TIMEOUT_MS,
      );
      if (opened === 'auth-required') {
        this.opts.log.info(
          { threadId, agentId: t.info.agent.id, methodId },
          '[acp-threads] signed in but session still refused — relaunching the agent',
        );
        this.closeSignInCapture(t);
        try {
          return await this.retryThread(threadId);
        } catch (err) {
          if (this.getInfo(threadId)?.status === 'authenticating') {
            this.emitStatus(t, 'auth_required', `sign in required: ${agentErrorMessage(err)}`, {
              reason: 'auth-required',
              agentMessage: agentErrorMessage(err),
              machineDetail: authMachineDetail(err, t),
              authMethods: threadAuthMethods(init.authMethods, t.terminalAuthBase),
            });
          }
          throw err;
        }
      }
      if (opened !== true) {
        if (isThreadClosed(t)) throw new ThreadOpError('not-ready', 'thread closed during sign-in');
        if (!isCurrentLaunch(t, ticket)) throw threadRestartedDuringSignIn();
        throw new ThreadOpError(
          'not-ready',
          lastFailureMessage(t) ?? `${t.info.agent.name} still couldn't start a conversation`,
        );
      }
      this.opts.log.info(
        { threadId, agentId: t.info.agent.id, methodId },
        '[acp-threads] thread signed in',
      );
      return { ...t.info };
    } finally {
      t.authInFlight = false;
      this.closeSignInCapture(t);
    }
  }

  private async requestAuthenticate(conn: ClientConnection, methodId: string): Promise<void> {
    let timer: ReturnType<typeof setTimeout> | undefined;
    const expiry = new Promise<never>((_resolve, reject) => {
      timer = setTimeout(() => reject(new AuthenticateTimeoutError()), this.authenticateTimeoutMs);
      timer.unref?.();
    });
    try {
      await Promise.race([conn.agent.request(acpMethods.agent.authenticate, { methodId }), expiry]);
    } finally {
      if (timer !== undefined) clearTimeout(timer);
    }
  }

  private async abortResume(t: ThreadRecord, failure: ThreadFailureDetail): Promise<void> {
    t.launchTicket = null;
    if (isThreadClosed(t)) {
      await this.stopFailedAgent(t);
      this.emitStatus(t, 'exited', 'resume failed', failure);
      return;
    }
    t.closed = true;
    t.suppressUpdates = false;
    this.failPendingPermissions(t);
    this.failPendingConsents(t);
    try {
      t.conn?.close();
    } catch {}
    const child = t.child;
    if (child !== null) {
      await terminateAgentTree(child, { graceMs: DESTROY_KILL_GRACE_MS });
    }
    t.child = null;
    t.conn = null;
    t.lastInit = null;
    t.closed = false;
    t.turnActive = false;
    this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));
    t.info.archived = true;
    this.recordTerminalStatus(t, 'exited', 'resume failed', failure);
    this.flushBroadcast(t);
    this.persistence.queueMetaWrite(t.info.threadId, this.buildMeta(t));
    await this.persistence.whenIdle(t.info.threadId);
    t.baseSeq = t.info.lastSeq + 1;
    t.events = [];
  }

  private async awaitReplayQuiescence(t: ThreadRecord): Promise<void> {
    const deadline = Date.now() + RESUME_REPLAY_MAX_WAIT_MS;
    while (Date.now() - t.lastSuppressedAt < RESUME_REPLAY_QUIESCENCE_MS && Date.now() < deadline) {
      await new Promise((r) => setTimeout(r, 50));
    }
  }

  sendPrompt(threadId: string, content: string, attachments?: readonly AttachmentPart[]): void {
    const t = this.mustGet(threadId);
    if (t.info.archived === true) {
      throw new ThreadOpError('not-ready', 'the thread is archived — resume it first');
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'the thread is still resuming');
    }
    if (t.authInFlight) {
      throw new ThreadOpError('not-ready', 'the thread is still signing in');
    }
    if (t.sessionId === null || t.conn === null) {
      throw new ThreadOpError('not-ready', 'thread has no live agent session');
    }
    if (t.turnActive) {
      const queue = t.info.queue ?? [];
      if (queue.length >= MAX_QUEUED_PROMPTS) {
        throw new ThreadOpError(
          'not-ready',
          `${MAX_QUEUED_PROMPTS} messages are already waiting — let the agent catch up`,
        );
      }
      const entry: QueuedMessage = { id: crypto.randomUUID(), content, ts: Date.now() };
      if (attachments !== undefined && attachments.length > 0) entry.attachments = attachments;
      t.info.queue = [...queue, entry];
      t.info.lastActivityAt = Date.now();
      this.emitInfo(t);
      return;
    }
    this.dispatchPrompt(t, content, attachments, { echo: true });
  }

  steerPrompt(threadId: string, content: string, attachments?: readonly AttachmentPart[]): void {
    const t = this.mustGet(threadId);
    this.assertSteerable(t);
    this.steerWith(t, content, attachments);
  }

  sendQueuedNow(threadId: string, id: string): boolean {
    const t = this.mustGet(threadId);
    const queue = t.info.queue ?? [];
    const message = queue.find((m) => m.id === id);
    if (message === undefined) return false;
    this.assertSteerable(t);
    const parked = this.takeSteer(t);
    const rest = queue.filter((m) => m.id !== id);
    const next = parked === null ? rest : [queuedFromSteer(parked), ...rest];
    t.info.queue = next.length > 0 ? next : undefined;
    this.steerWith(t, message.content, message.attachments);
    return true;
  }

  private assertSteerable(t: ThreadRecord): void {
    if (t.info.archived === true) {
      throw new ThreadOpError('not-ready', 'the thread is archived — resume it first');
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'the thread is still resuming');
    }
    if (t.authInFlight) {
      throw new ThreadOpError('not-ready', 'the thread is still signing in');
    }
    if (t.sessionId === null || t.conn === null) {
      throw new ThreadOpError('not-ready', 'thread has no live agent session');
    }
  }

  private steerWith(
    t: ThreadRecord,
    content: string,
    attachments?: readonly AttachmentPart[],
  ): void {
    if (!t.turnActive) {
      this.dispatchPrompt(t, content, attachments, { echo: true });
      return;
    }
    this.clearSteer(t);
    const steer: SteerMessage = { content, ts: Date.now() };
    if (attachments !== undefined && attachments.length > 0) steer.attachments = attachments;
    t.info.steer = steer;
    t.info.lastActivityAt = Date.now();
    this.emitInfo(t);
    const timer = setTimeout(() => this.demoteStalledSteer(t), this.steerStallMs);
    timer.unref?.();
    t.steerStallTimer = timer;
    this.cancelTurn(t, { clearQueue: false });
  }

  private demoteStalledSteer(t: ThreadRecord): void {
    t.steerStallTimer = null;
    const steer = t.info.steer;
    if (steer === undefined || t.closed || !t.turnActive) return;
    t.info.steer = undefined;
    t.info.queue = [queuedFromSteer(steer), ...(t.info.queue ?? [])];
    this.emitInfo(t);
  }

  private clearSteer(t: ThreadRecord): void {
    if (t.steerStallTimer !== null) {
      clearTimeout(t.steerStallTimer);
      t.steerStallTimer = null;
    }
    t.info.steer = undefined;
  }

  private takeSteer(t: ThreadRecord): SteerMessage | null {
    const steer = t.info.steer;
    if (steer === undefined) return null;
    this.clearSteer(t);
    return steer;
  }

  private armStallTimer(t: ThreadRecord, delayMs = this.turnStallMs): void {
    if (t.stallTimer !== null) clearTimeout(t.stallTimer);
    const timer = setTimeout(() => this.checkStall(t), delayMs);
    timer.unref?.();
    t.stallTimer = timer;
  }

  private checkStall(t: ThreadRecord): void {
    t.stallTimer = null;
    if (t.closed || !t.turnActive || t.info.stalledSince !== undefined) return;
    if (t.pendingPermissions.size > 0) {
      this.armStallTimer(t);
      return;
    }
    const silentMs = Date.now() - t.agentActivityAt;
    if (silentMs < this.turnStallMs) {
      this.armStallTimer(t, this.turnStallMs - silentMs);
      return;
    }
    t.info.stalledSince = t.agentActivityAt;
    this.opts.log.warn(
      { threadId: t.info.threadId, agentId: t.info.agent.id, silentMs },
      '[acp-threads] turn stalled: no agent activity',
    );
    this.emitInfo(t);
  }

  private touchTurnActivity(t: ThreadRecord): void {
    const now = Date.now();
    t.agentActivityAt = now;
    t.info.lastActivityAt = now;
    if (t.info.stalledSince === undefined) return;
    const stalledForMs = Date.now() - t.info.stalledSince;
    t.info.stalledSince = undefined;
    this.opts.log.info(
      { threadId: t.info.threadId, agentId: t.info.agent.id, stalledForMs },
      '[acp-threads] turn resumed after stall',
    );
    this.emitInfo(t);
    if (t.turnActive) this.armStallTimer(t);
  }

  private clearStall(t: ThreadRecord): void {
    if (t.stallTimer !== null) {
      clearTimeout(t.stallTimer);
      t.stallTimer = null;
    }
    t.info.stalledSince = undefined;
  }

  private logTurnEnded(t: ThreadRecord, outcome: StopReason | 'failed'): void {
    const startedAt = t.turnStartedAt;
    t.turnStartedAt = null;
    this.opts.log.info(
      {
        threadId: t.info.threadId,
        agentId: t.info.agent.id,
        outcome,
        durationMs: startedAt === null ? undefined : Date.now() - startedAt,
      },
      '[acp-threads] turn ended',
    );
  }

  editQueued(threadId: string, id: string, content: string): boolean {
    const t = this.mustGet(threadId);
    const queue = t.info.queue ?? [];
    if (!queue.some((m) => m.id === id)) return false;
    t.info.queue = queue.map((m) => (m.id === id ? { ...m, content, held: false } : m));
    this.emitInfo(t);
    this.drainIfIdle(t);
    return true;
  }

  holdQueued(threadId: string, id: string, held: boolean): boolean {
    const t = this.mustGet(threadId);
    const queue = t.info.queue ?? [];
    if (!queue.some((m) => m.id === id)) return false;
    t.info.queue = queue.map((m) => (m.id === id ? { ...m, held } : m));
    this.emitInfo(t);
    if (!held) this.drainIfIdle(t);
    return true;
  }

  removeQueued(threadId: string, id: string): boolean {
    const t = this.mustGet(threadId);
    const queue = t.info.queue ?? [];
    const next = queue.filter((m) => m.id !== id);
    if (next.length === queue.length) return false;
    t.info.queue = next.length > 0 ? next : undefined;
    this.emitInfo(t);
    return true;
  }

  private drainIfIdle(t: ThreadRecord): void {
    if (t.turnActive || t.closed || t.resumeInFlight) return;
    if (t.info.archived === true || t.sessionId === null || t.conn === null) return;
    const next = this.takeNextQueued(t);
    if (next === null) return;
    this.dispatchPrompt(t, next.content, next.attachments, { echo: true });
  }

  private takeNextQueued(t: ThreadRecord): QueuedMessage | null {
    const queue = t.info.queue;
    if (queue === undefined || queue.length === 0) return null;
    const index = queue.findIndex((m) => m.held !== true);
    if (index === -1) return null;
    const next = queue[index];
    const rest = [...queue.slice(0, index), ...queue.slice(index + 1)];
    t.info.queue = rest.length > 0 ? rest : undefined;
    return next ?? null;
  }

  private echoUserMessage(
    t: ThreadRecord,
    content: string,
    attachments?: readonly AttachmentPart[],
  ): void {
    t.hadUserMessage = true;
    if (t.info.title === t.info.agent.name && content.trim() !== '') {
      const source = t.titleHint !== undefined && t.titleHint.trim() !== '' ? t.titleHint : content;
      t.titleHint = undefined;
      t.info.title = deriveThreadTitle(source, t.info.agent.name);
      this.appendEvent(t, { kind: 'title_changed', title: t.info.title, ts: Date.now() });
      this.emitInfo(t);
    }
    const event: ThreadEvent = { kind: 'user_message', content, ts: Date.now() };
    if (attachments !== undefined && attachments.length > 0) event.attachments = attachments;
    this.appendEvent(t, event);
  }

  async renameThread(threadId: string, rawTitle: string): Promise<ThreadInfo> {
    const t = this.mustGet(threadId);
    if (t.closed) {
      throw new ThreadOpError('not-ready', 'the thread is closing');
    }
    const title = clampThreadTitle(rawTitle);
    if (title === '' || title === t.info.title) return { ...t.info };
    await this.ensureLogResolved(t);
    t.info.title = title;
    this.appendEvent(t, { kind: 'title_changed', title, ts: Date.now() });
    this.flushBroadcast(t);
    this.emitInfo(t);
    await this.persistence.whenIdle(t.info.threadId);
    return { ...t.info };
  }

  private dispatchPrompt(
    t: ThreadRecord,
    content: string,
    attachments: readonly AttachmentPart[] | undefined,
    opts: { echo: boolean },
  ): void {
    if (t.sessionId === null || t.conn === null) {
      throw new ThreadOpError('not-ready', 'thread has no live agent session');
    }
    if (opts.echo) {
      this.echoUserMessage(t, content, attachments);
    }
    let wireText = content;
    let skillBlock: ContentBlock | null = null;
    if (t.envNotePending && !content.startsWith('/')) {
      t.envNotePending = false;
      const skill = t.projectSkill;
      const inline = skill !== null && skill.inlineText !== null;
      const note = buildEnvironmentNote(
        skill === null ? null : { skillPath: skill.skillPath, inline },
      );
      wireText = `${note}\n\n${content}`;
      if (skill !== null) {
        if (skill.inlineText !== null) {
          skillBlock = inlineSkillBlock(
            skill.skillPath,
            skill.inlineText,
            t.info.promptCapabilities,
          );
        }
        this.opts.log.info(
          {
            threadId: t.info.threadId,
            agentId: t.info.agent.id,
            skillPath: skill.skillPath,
            delivery: inline ? 'inline' : 'path',
          },
          '[acp-threads] skill pointer sent',
        );
      }
    }
    t.turnActive = true;
    t.cancelRequested = false;
    t.turnStartedAt = Date.now();
    t.agentActivityAt = t.turnStartedAt;
    this.appendEvent(t, { kind: 'turn_started', ts: t.turnStartedAt });
    this.emitStatus(t, 'running');
    this.opts.log.info(
      { threadId: t.info.threadId, agentId: t.info.agent.id },
      '[acp-threads] turn started',
    );
    this.armStallTimer(t);

    const sessionId = t.sessionId;
    const promptBuild = buildPromptBlocks(
      wireText,
      attachments,
      t.info.promptCapabilities,
      (requested) => this.confinePath(requested).then(({ abs, rel }) => ({ abs, rel })),
    );
    const requestPromise = promptBuild.then((built) => {
      if (built.dropped.length > 0) {
        this.opts.log.warn(
          {
            threadId: t.info.threadId,
            dropped: built.dropped.map((d) => ({ kind: d.part.kind, reason: d.reason })),
          },
          '[acp-threads] dropped attachment parts before session/prompt',
        );
        const dropTs = Date.now();
        for (const d of built.dropped) {
          const label =
            d.part.kind === 'image' || d.part.kind === 'blob'
              ? d.part.name
              : d.part.name || d.part.path;
          this.appendEvent(t, {
            kind: 'agent_stderr',
            line: `[attachment dropped] ${label}: ${d.reason}`,
            ts: dropTs,
          });
        }
      }
      if (t.sessionId === null || t.conn === null) {
        throw new ThreadOpError('not-ready', 'thread has no live agent session');
      }
      if (t.cancelRequested) {
        throw new PromptCancelledBeforeDispatchError();
      }
      return t.conn.agent.request(acpMethods.agent.session.prompt, {
        sessionId,
        prompt: skillBlock === null ? [...built.blocks] : [...built.blocks, skillBlock],
      });
    });
    requestPromise
      .then((response) => {
        t.turnActive = false;
        this.clearStall(t);
        this.logTurnEnded(t, response.stopReason);
        if (isThreadClosed(t)) return;
        this.appendEvent(t, {
          kind: 'turn_ended',
          stopReason: response.stopReason,
          ts: Date.now(),
        });
        if (t.sessionId !== null && t.conn !== null) {
          const steer = this.takeSteer(t);
          if (steer !== null) {
            this.dispatchPrompt(t, steer.content, steer.attachments, { echo: true });
            return;
          }
          const next = this.takeNextQueued(t);
          if (next !== null) {
            this.dispatchPrompt(t, next.content, next.attachments, { echo: true });
            return;
          }
        }
        this.emitStatus(t, 'ready');
      })
      .catch(async (err) => {
        t.turnActive = false;
        this.clearStall(t);
        this.logTurnEnded(t, t.cancelRequested ? 'cancelled' : 'failed');
        if (isThreadClosed(t)) return;
        this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });
        if (t.sessionId !== null && t.conn !== null) {
          const steer = this.takeSteer(t);
          if (steer !== null) {
            this.dispatchPrompt(t, steer.content, steer.attachments, { echo: true });
            return;
          }
        }
        if (t.cancelRequested) {
          this.emitStatus(t, 'ready');
          this.drainIfIdle(t);
          return;
        }
        if (isAuthRequiredError(err)) {
          this.emitStatus(t, 'auth_required', `sign in required: ${agentErrorMessage(err)}`, {
            reason: 'auth-required',
            agentMessage: agentErrorMessage(err),
            machineDetail: authMachineDetail(err, t),
            authMethods: threadAuthMethods(t.lastInit?.authMethods, t.terminalAuthBase),
          });
          return;
        }
        const tail = await stderrTailDetail(t);
        this.emitStatus(t, 'error', `prompt failed: ${agentErrorMessage(err)}`, {
          reason: 'prompt',
          agentMessage: agentErrorMessage(err),
          machineDetail: joinMachineDetail({
            primary: agentErrorData(err),
            tail,
          }),
        });
      })
      .catch((err: unknown) => {
        this.opts.log.error(
          { err, threadId: t.info.threadId },
          '[acp-threads] prompt diagnostics failed',
        );
      });
  }

  cancel(threadId: string): void {
    this.cancelTurn(this.mustGet(threadId), { clearQueue: true });
  }

  private cancelTurn(t: ThreadRecord, opts: { clearQueue: boolean }): void {
    if (opts.clearQueue && (t.info.queue !== undefined || t.info.steer !== undefined)) {
      t.info.queue = undefined;
      this.clearSteer(t);
      this.emitInfo(t);
    }
    if (t.conn === null || t.sessionId === null) return;
    if (t.turnActive) t.cancelRequested = true;
    const wasStalled = t.info.stalledSince !== undefined;
    this.clearStall(t);
    if (wasStalled) this.emitInfo(t);
    this.failPendingPermissions(t);
    this.restoreRunningAfterPermission(t);
    t.conn.agent
      .notify(acpMethods.agent.session.cancel, { sessionId: t.sessionId })
      .catch((err: unknown) => {
        this.opts.log.debug(
          { err, threadId: t.info.threadId },
          '[acp-threads] cancel notification never reached the agent',
        );
      });
  }

  setMode(threadId: string, modeId: string): void {
    const t = this.mustGet(threadId);
    if (t.info.archived === true) {
      const modes = t.info.modes;
      if (modes == null || !modes.availableModes.some((m) => m.id === modeId)) {
        throw new ThreadOpError('not-ready', `no such mode: ${modeId}`);
      }
      t.info.modes = { ...modes, currentModeId: modeId };
      this.emitInfo(t);
      return;
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'the thread is still resuming');
    }
    if (t.conn === null || t.sessionId === null) {
      throw new ThreadOpError('not-ready', 'thread has no live agent session');
    }
    void t.conn.agent
      .request(acpMethods.agent.session.setMode, { sessionId: t.sessionId, modeId })
      .then(() => {
        if (t.info.modes) {
          t.info.modes = { ...t.info.modes, currentModeId: modeId };
          this.emitInfo(t);
        }
      })
      .catch((err) => {
        this.opts.log.warn({ err, threadId }, '[acp-threads] set_mode failed');
      });
  }

  setConfigOption(threadId: string, configId: string, value: string | boolean): void {
    const t = this.mustGet(threadId);
    if (t.info.archived === true) {
      const option = (t.info.configOptions ?? []).find((o) => o.id === configId);
      if (option === undefined) {
        throw new ThreadOpError('not-ready', `no such config option: ${configId}`);
      }
      if (!initialConfigValueValid(option, value)) {
        throw new ThreadOpError('not-ready', `invalid value for ${configId}`);
      }
      t.info.configOptions = (t.info.configOptions ?? []).map((o) =>
        o.id === configId ? ({ ...o, currentValue: value } as SessionConfigOption) : o,
      );
      this.emitInfo(t);
      return;
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'the thread is still resuming');
    }
    if (t.conn === null || t.sessionId === null) {
      throw new ThreadOpError('not-ready', 'thread has no live agent session');
    }
    const request: SetSessionConfigOptionRequest =
      typeof value === 'boolean'
        ? { sessionId: t.sessionId, configId, type: 'boolean', value }
        : { sessionId: t.sessionId, configId, value };
    void t.conn.agent
      .request(acpMethods.agent.session.setConfigOption, request)
      .then((response: SetSessionConfigOptionResponse) => {
        t.info.configOptions = response.configOptions;
        this.emitInfo(t);
      })
      .catch((err) => {
        this.opts.log.warn({ err, threadId, configId }, '[acp-threads] set_config_option failed');
      });
  }

  private async applyInitialConfig(
    record: ThreadRecord,
    ticket: LaunchTicket,
    conn: NonNullable<ThreadRecord['conn']>,
    config: Record<string, string | boolean>,
    sessionStateUnknown = false,
  ): Promise<void> {
    const sessionId = record.sessionId;
    if (sessionId === null) return;
    let applied = false;
    const rejected = new Set<string>();
    const findOption = (id: string) => (record.info.configOptions ?? []).find((o) => o.id === id);
    const passLimit = Object.keys(config).length + 1;
    let pending = Object.entries(config);
    for (let pass = 0; pending.length > 0 && pass < passLimit; pass += 1) {
      const isModel = (id: string): boolean => findOption(id)?.category === 'model';
      let changed = false;
      const ordered = [...pending].sort(([a], [b]) => Number(isModel(b)) - Number(isModel(a)));
      for (const [configId, value] of ordered) {
        const option = findOption(configId);
        if (option === undefined) continue;
        if ((!sessionStateUnknown || pass > 0) && option.currentValue === value) continue;
        if (!initialConfigValueValid(option, value)) continue;
        const request: SetSessionConfigOptionRequest =
          typeof value === 'boolean'
            ? { sessionId, configId, type: 'boolean', value }
            : { sessionId, configId, value };
        try {
          const response: SetSessionConfigOptionResponse = await conn.agent.request(
            acpMethods.agent.session.setConfigOption,
            request,
          );
          if (!isCurrentLaunch(record, ticket)) return;
          record.info.configOptions = response.configOptions;
          rejected.delete(configId);
          applied = true;
          changed = true;
        } catch (err) {
          rejected.add(configId);
          this.opts.log.info(
            { err, threadId: record.info.threadId, configId, pass },
            '[acp-threads] initial config apply attempt failed',
          );
        }
        if (!isCurrentLaunch(record, ticket)) return;
      }
      if (!changed) break;
      pending = Object.entries(config).filter(
        ([configId, value]) => findOption(configId)?.currentValue !== value,
      );
    }
    if (rejected.size > 0) {
      this.opts.log.warn(
        {
          threadId: record.info.threadId,
          rejectedConfigIds: [...rejected],
          sessionStateUnknown,
        },
        '[acp-threads] some remembered config options could not be applied to the new session',
      );
    }
    const missingConfigIds: string[] = [];
    const unmatchedConfigIds: string[] = [];
    for (const [configId, value] of Object.entries(config)) {
      if (rejected.has(configId)) continue;
      const option = findOption(configId);
      if (option === undefined) missingConfigIds.push(configId);
      else if (option.currentValue !== value) unmatchedConfigIds.push(configId);
    }
    if (missingConfigIds.length > 0 || unmatchedConfigIds.length > 0) {
      this.opts.log.info(
        {
          threadId: record.info.threadId,
          missingConfigIds,
          unmatchedConfigIds,
          sessionStateUnknown,
        },
        '[acp-threads] some remembered config options did not come back in the new session',
      );
    }
    if (applied) this.emitInfo(record);
  }

  private async applyInitialMode(
    record: ThreadRecord,
    ticket: LaunchTicket,
    conn: NonNullable<ThreadRecord['conn']>,
    modeId: string,
    sessionStateUnknown = false,
  ): Promise<void> {
    const sessionId = record.sessionId;
    if (sessionId === null) return;
    const modes = record.info.modes;
    if (modes != null) {
      if (modes.availableModes.some((m) => m.id === modeId)) {
        if (!sessionStateUnknown && modes.currentModeId === modeId) return;
        try {
          await conn.agent.request(acpMethods.agent.session.setMode, { sessionId, modeId });
          if (!isCurrentLaunch(record, ticket)) return;
          record.info.modes = { ...modes, currentModeId: modeId };
          this.emitInfo(record);
        } catch (err) {
          this.opts.log.warn(
            { err, threadId: record.info.threadId, modeId, method: 'set_mode' },
            '[acp-threads] initial mode apply failed',
          );
        }
        return;
      }
    }
    const option = (record.info.configOptions ?? []).find(
      (o) => o.category === 'mode' && initialConfigValueValid(o, modeId),
    );
    if (option === undefined) return;
    if (!sessionStateUnknown && option.currentValue === modeId) return;
    try {
      const response: SetSessionConfigOptionResponse = await conn.agent.request(
        acpMethods.agent.session.setConfigOption,
        { sessionId, configId: option.id, value: modeId },
      );
      if (!isCurrentLaunch(record, ticket)) return;
      record.info.configOptions = response.configOptions;
      this.emitInfo(record);
    } catch (err) {
      this.opts.log.warn(
        { err, threadId: record.info.threadId, modeId, method: 'set_config_option' },
        '[acp-threads] initial mode apply failed',
      );
    }
  }

  respondPermission(
    threadId: string,
    requestId: string,
    outcome: { kind: 'selected'; optionId: string } | { kind: 'cancelled' },
  ): void {
    const t = this.mustGet(threadId);
    const pending = t.pendingPermissions.get(requestId);
    if (pending === undefined) return;
    t.pendingPermissions.delete(requestId);
    clearTimeout(pending.timer);
    this.touchTurnActivity(t);
    if (outcome.kind === 'selected' && pending.offeredOptionIds.has(outcome.optionId)) {
      pending.resolve({ outcome: { outcome: 'selected', optionId: outcome.optionId } });
      this.appendEvent(t, {
        kind: 'permission_resolved',
        requestId,
        optionId: outcome.optionId,
        auto: false,
        ts: Date.now(),
      });
    } else {
      pending.resolve({ outcome: { outcome: 'cancelled' } });
      this.appendEvent(t, {
        kind: 'permission_resolved',
        requestId,
        optionId: null,
        auto: false,
        ts: Date.now(),
      });
    }
    this.restoreRunningAfterPermission(t);
  }

  setChatGrant(threadId: string, grant: ThreadChatGrant, enabled: boolean): void {
    const t = this.mustGet(threadId);
    if (t.chatGrants.has(grant) === enabled) return;
    if (enabled) t.chatGrants.add(grant);
    else t.chatGrants.delete(grant);
    t.info.chatGrants = t.chatGrants.size > 0 ? [...t.chatGrants] : undefined;
    this.opts.log.info(
      { threadId, agentId: t.info.agent.id, grant, enabled },
      '[acp-threads] chat grant changed',
    );
    this.emitInfo(t);
  }

  private restoreRunningAfterPermission(t: ThreadRecord): void {
    if (
      t.pendingPermissions.size === 0 &&
      t.turnActive &&
      t.info.status === 'awaiting_permission'
    ) {
      this.emitStatus(t, 'running');
    }
  }

  async closeThread(threadId: string, opts?: { killGraceMs?: number }): Promise<void> {
    const t = this.threads.get(threadId);
    if (t === undefined || t.info.archived === true || t.closed) return;
    t.closed = true;
    t.launchTicket = null;
    this.clearSteer(t);
    this.failPendingPermissions(t);
    this.failPendingConsents(t);
    try {
      t.conn?.close();
    } catch {}
    const child = t.child;
    if (child !== null) {
      const dead = await terminateAgentTree(child, {
        graceMs: opts?.killGraceMs ?? KILL_GRACE_MS,
      });
      if (!dead) {
        this.opts.log.error(
          { threadId, pid: child.pid },
          '[acp-threads] agent process survived SIGKILL escalation',
        );
      }
    }
    t.child = null;
    t.conn = null;
    t.lastInit = null;
    await t.terminals?.disposeAll();
    t.terminals = null;
    this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));
    await this.opts.sessionManager
      .closeAllForAgent(toBroadcasterKey(t.agentSessionId))
      .catch((err) => {
        this.opts.log.warn({ err, threadId }, '[acp-threads] session cleanup failed');
      });
    const failedStart = t.info.status === 'error' || t.info.status === 'auth_required';
    if (!t.hadUserMessage && !failedStart) {
      await this.forgetThread(t);
      this.opts.log.info({ threadId }, '[acp-threads] empty thread discarded on close');
      return;
    }
    if (t.turnActive) {
      t.turnActive = false;
      this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });
    }
    t.info.archived = true;
    this.recordTerminalStatus(t, 'exited', 'thread closed');
    this.flushBroadcast(t);
    this.persistence.queueMetaWrite(threadId, this.buildMeta(t));
    await this.persistence.whenIdle(threadId);
    t.baseSeq = t.info.lastSeq + 1;
    t.events = [];
    t.pendingBroadcast = [];
    t.closed = false;
    this.opts.log.info({ threadId }, '[acp-threads] thread archived');
  }

  async deleteThread(threadId: string): Promise<void> {
    const t = this.mustGet(threadId);
    if (t.info.archived !== true) {
      throw new ThreadOpError('not-ready', 'close the thread before deleting it');
    }
    if (t.resumeInFlight) {
      throw new ThreadOpError('not-ready', 'a resume is in progress');
    }
    await this.forgetThread(t);
    this.opts.log.info({ threadId }, '[acp-threads] thread deleted');
  }

  private async forgetThread(t: ThreadRecord): Promise<void> {
    const threadId = t.info.threadId;
    this.threads.delete(threadId);
    t.subscribers.clear();
    if (t.flushTimer !== null) {
      clearTimeout(t.flushTimer);
      t.flushTimer = null;
    }
    this.clearStall(t);
    await this.persistence.whenIdle(threadId);
    await this.persistence.delete(threadId);
    if (this.opts.globalDir !== null) {
      await removeAgentBrowserFolders(this.opts.globalDir, threadId).catch((err: unknown) => {
        this.opts.log.warn({ err, threadId }, '[acp-threads] removing browser folders failed');
      });
    }
  }

  async destroy(): Promise<void> {
    this.destroyed = true;
    clearInterval(this.reapTimer);
    await Promise.allSettled(
      [...this.threads.keys()].map((id) =>
        this.closeThread(id, { killGraceMs: DESTROY_KILL_GRACE_MS }),
      ),
    );
  }

  private async handlePermissionRequest(
    record: ThreadRecord,
    toolCall: ToolCallUpdate,
    options: PermissionOption[],
    requestMeta?: unknown,
  ): Promise<RequestPermissionResponse> {
    this.touchTurnActivity(record);
    const evidence = mergeToolCallEvidence(
      await reportedToolCall(record, toolCall, requestMeta, this.opts.log),
      toolCall,
    );
    const presented: ToolCallUpdate = {
      ...toolCall,
      ...(toolCall.title == null && evidence.title != null ? { title: evidence.title } : {}),
      ...(toolCall.rawInput === undefined && evidence.rawInput !== undefined
        ? { rawInput: evidence.rawInput }
        : {}),
    };
    const browser = identifyBrowserCall(evidence, {
      requestMeta,
      browserInjected: record.browserInjected,
      agentId: record.info.agent.id,
    });
    const decision = this.opts.permissions.decide(
      record.info.agent.id,
      toolCall,
      options,
      browser,
      record.chatGrants,
      this.opts.autoApproveOkTools?.() ?? true,
    );
    if (decision.auto !== null) {
      const requestId = crypto.randomUUID();
      this.appendEvent(record, {
        kind: 'permission_resolved',
        requestId,
        optionId: decision.auto.optionId,
        auto: true,
        ts: Date.now(),
      });
      return { outcome: { outcome: 'selected', optionId: decision.auto.optionId } };
    }

    const requestId = crypto.randomUUID();
    const offered = offeredPermissionOptions(browser, options);
    this.appendEvent(record, {
      kind: 'permission_request',
      requestId,
      toolCall: presented,
      options: offered,
      ...(readOnlyShellCommand(toolCall) !== null ? { readOnlyShell: true } : {}),
      ts: Date.now(),
    });
    if (record.turnActive && record.info.status === 'running') {
      this.emitStatus(record, 'awaiting_permission');
    }
    return new Promise<RequestPermissionResponse>((resolvePromise) => {
      const timer = setTimeout(() => {
        record.pendingPermissions.delete(requestId);
        this.appendEvent(record, {
          kind: 'permission_resolved',
          requestId,
          optionId: null,
          auto: true,
          ts: Date.now(),
        });
        this.restoreRunningAfterPermission(record);
        resolvePromise({ outcome: { outcome: 'cancelled' } });
      }, PERMISSION_TIMEOUT_MS);
      timer.unref?.();
      record.pendingPermissions.set(requestId, {
        timer,
        offeredOptionIds: new Set(offered.map((o) => o.optionId)),
        resolve: (response) => {
          if (response.outcome.outcome === 'selected') {
            const optionId = response.outcome.optionId;
            const chosen = offered.find((o) => o.optionId === optionId);
            if (chosen !== undefined) {
              void this.opts.permissions.recordChoice(
                record.info.agent.id,
                toolCall,
                chosen,
                browser,
              );
            }
          }
          resolvePromise(response);
        },
      });
    });
  }

  private handleSessionUpdate(record: ThreadRecord, notification: SessionNotification): void {
    this.touchTurnActivity(record);
    const update: SessionUpdate = notification.update;
    if (
      record.browserInjected &&
      (update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update')
    ) {
      rememberReportedToolCall(record, update);
    }
    if (update.sessionUpdate === 'current_mode_update' && record.info.modes) {
      record.info.modes = { ...record.info.modes, currentModeId: update.currentModeId };
      this.emitInfo(record);
    }
    if (update.sessionUpdate === 'config_option_update') {
      record.info.configOptions = update.configOptions;
      this.emitInfo(record);
    }
    if (update.sessionUpdate === 'available_commands_update') {
      record.info.availableCommands = update.availableCommands;
      this.emitInfo(record);
    }
    if (record.suppressUpdates) {
      record.lastSuppressedAt = Date.now();
      return;
    }
    this.appendEvent(record, {
      kind: 'session_update',
      update: boundSessionUpdateForLog(update),
      ts: Date.now(),
    });
  }

  private async handleFsRead(
    requestedPath: string,
    line: number | null,
    limit: number | null,
  ): Promise<{ content: string }> {
    const target = await this.confinePath(requestedPath);
    let content: string;
    if (target.docName !== null) {
      content =
        this.opts.getLoadedDocText?.(target.docName) ?? (await readFile(target.abs, 'utf8'));
    } else {
      content = await readFile(target.abs, 'utf8');
    }
    if (line !== null || limit !== null) {
      const lines = content.split('\n');
      const start = Math.max((line ?? 1) - 1, 0);
      const end = limit !== null ? start + limit : lines.length;
      content = lines.slice(start, end).join('\n');
    }
    return { content };
  }

  private async handleFsWrite(
    record: ThreadRecord,
    requestedPath: string,
    content: string,
  ): Promise<WriteTextFileResponse> {
    this.touchTurnActivity(record);
    const target = await this.confinePath(requestedPath);
    if (target.docName !== null) {
      if (this.opts.localApi === undefined) {
        throw new Error(`document writes are not available here: ${requestedPath}`);
      }
      const result = await writeDocumentThroughRoute(this.opts.localApi, {
        docName: target.docName,
        file: target.rel,
        markdown: content,
        agentId: record.agentSessionId,
        agentName: record.info.agent.name,
        clientName: record.info.agent.id,
      });
      this.setPresence(record, target.docName);
      return result;
    }
    if (this.opts.isIgnoredPath(target.rel)) {
      throw new Error(`path is excluded from the project content scope: ${requestedPath}`);
    }
    const { tracedMkdir, tracedWriteFile } = await import('../fs-traced.ts');
    await tracedMkdir(dirname(target.abs), { recursive: true });
    await tracedWriteFile(target.abs, content);
    return {};
  }

  private confinePath(
    requestedPath: string,
  ): Promise<{ abs: string; rel: string; docName: string | null }> {
    return confineToContentDir(this.opts.contentDir, requestedPath, this.opts.isExcludedPath);
  }

  private mustGet(threadId: string): ThreadRecord {
    const t = this.threads.get(threadId);
    if (t === undefined) throw new ThreadOpError('unknown-thread', `no thread '${threadId}'`);
    return t;
  }

  private appendEvent(t: ThreadRecord, event: ThreadEvent): void {
    const pending = t.pendingBroadcast;
    if (pending.length > 0 && coalesceChunkInto(pending[pending.length - 1], event, t.info.agent)) {
      return;
    }
    const seq = t.baseSeq + t.events.length;
    t.events.push(event);
    t.info.lastSeq = seq;
    if (t.events.length > EVENT_LOG_LIMIT) {
      const drop = t.events.length - EVENT_LOG_LIMIT;
      t.events.splice(0, drop);
      t.baseSeq += drop;
    }
    if (t.pendingBroadcast.length === 0) t.pendingBroadcastFromSeq = seq;
    t.pendingBroadcast.push(event);
    if (t.flushTimer === null) {
      t.flushTimer = setTimeout(() => this.flushBroadcast(t), EVENT_FLUSH_MS);
      t.flushTimer.unref?.();
    }
  }

  private flushBroadcast(t: ThreadRecord): void {
    if (t.flushTimer !== null) {
      clearTimeout(t.flushTimer);
      t.flushTimer = null;
    }
    if (t.pendingBroadcast.length === 0) return;
    const frame: ThreadServerFrame = {
      op: 'events',
      threadId: t.info.threadId,
      fromSeq: t.pendingBroadcastFromSeq,
      events: t.pendingBroadcast,
    };
    this.persistence.appendEvents(t.info.threadId, t.pendingBroadcast);
    t.pendingBroadcast = [];
    for (const sink of t.subscribers) {
      try {
        sink(frame);
      } catch {}
    }
  }

  private emitStatus(
    t: ThreadRecord,
    status: ThreadStatus,
    detail?: string,
    failure?: ThreadFailureDetail,
  ): void {
    if (isThreadClosed(t)) {
      this.logSuppressedStatus(t, status, detail, failure);
      return;
    }
    this.recordTerminalStatus(t, status, detail, failure);
  }

  private logSuppressedStatus(
    t: ThreadRecord,
    status: ThreadStatus,
    detail: string | undefined,
    failure: ThreadFailureDetail | undefined,
  ): void {
    const log =
      status === 'error' || status === 'auth_required' ? this.opts.log.warn : this.opts.log.info;
    log.call(
      this.opts.log,
      {
        threadId: t.info.threadId,
        agentId: t.info.agent.id,
        status,
        suppressed: true,
        detail: detail === undefined ? undefined : redactDiagnostic(detail),
        reason: failure?.reason,
        machineDetail:
          failure?.machineDetail === undefined
            ? undefined
            : redactDiagnostic(failure.machineDetail),
      },
      isThreadClosed(t)
        ? '[acp-threads] status suppressed after thread close'
        : '[acp-threads] status suppressed for a superseded launch',
    );
  }

  private recordTerminalStatus(
    t: ThreadRecord,
    status: ThreadStatus,
    detail?: string,
    failure?: ThreadFailureDetail,
  ): void {
    if (status === 'exited' || status === 'error') {
      t.info.queue = undefined;
      this.clearSteer(t);
      this.clearStall(t);
    }
    if (
      t.launchTicket !== null &&
      t.launchTicket.initialPrompt !== null &&
      (status === 'exited' || status === 'error' || status === 'auth_required')
    ) {
      t.launchTicket.initialPrompt = null;
      this.opts.log.info(
        { threadId: t.info.threadId, agentId: t.info.agent.id, status },
        '[acp-threads] pending first message dropped: the launch settled without starting a turn',
      );
    }
    t.info.status = status;
    t.info.lastActivityAt = Date.now();
    if (status === 'error' || status === 'auth_required') {
      this.opts.log.warn(
        {
          threadId: t.info.threadId,
          agentId: t.info.agent.id,
          status,
          detail,
          reason: failure?.reason,
          machineDetail: failure?.machineDetail,
        },
        '[acp-threads] thread failure status',
      );
    }
    if (status === 'error' && failure !== undefined && isAcpLaunchFailureReason(failure.reason)) {
      void recordAcpLaunchFailure(this.opts.localDir, {
        at: new Date(),
        threadId: t.info.threadId,
        agentId: t.info.agent.id,
        agentSource: t.info.agent.source,
        reason: failure.reason,
        detail,
        machineDetail: failure.machineDetail,
      }).catch((err: unknown) => {
        this.opts.log.warn(
          { err, threadId: t.info.threadId },
          '[acp-threads] launch failure log write failed',
        );
      });
    }
    this.appendEvent(t, {
      kind: 'status',
      status,
      detail,
      ...(failure !== undefined ? { failure } : {}),
      ts: Date.now(),
    });
    this.emitInfo(t);
  }

  private async failLaunch(
    record: ThreadRecord,
    ticket: LaunchTicket,
    message: string | undefined,
    failure: ThreadFailureDetail,
  ): Promise<void> {
    if (!isCurrentLaunch(record, ticket)) {
      this.logSuppressedStatus(record, 'error', message, failure);
      return;
    }
    this.emitStatus(record, 'error', message, failure);
    if (isCurrentLaunch(record, ticket)) await this.teardownFailedAgent(record);
  }

  private async teardownFailedAgent(t: ThreadRecord): Promise<void> {
    t.sessionId = null;
    t.info.resumable = false;
    t.info.contextWindow = null;
    await this.stopFailedAgent(t);
  }

  private endRestart(t: ThreadRecord): boolean {
    const previous = t.sessionBeforeRestart;
    t.sessionBeforeRestart = null;
    if (previous === null || t.sessionId !== null) return false;
    if (isThreadClosed(t)) {
      t.sessionId = previous.sessionId;
      t.info.resumable = previous.resumable;
      t.info.contextWindow = previous.contextWindow;
    }
    return true;
  }

  private async stopFailedAgent(t: ThreadRecord): Promise<void> {
    this.failPendingPermissions(t);
    this.failPendingConsents(t);
    t.lastInit = null;
    await this.stopAgentProcess(
      t,
      '[acp-threads] terminal cleanup on failed-agent teardown failed',
    );
  }

  private emitInfo(t: ThreadRecord): void {
    this.persistence.queueMetaWrite(t.info.threadId, this.buildMeta(t));
    this.broadcastInfo(t);
  }

  private broadcastInfo(t: ThreadRecord): void {
    for (const sink of t.subscribers) {
      try {
        sink({ op: 'info', info: { ...t.info } });
      } catch {}
    }
  }

  private closeSignInCapture(t: ThreadRecord): void {
    t.authStderr = null;
    if (t.info.signInOutput !== undefined) {
      t.info.signInOutput = undefined;
      this.broadcastInfo(t);
    }
  }

  private buildMeta(t: ThreadRecord): PersistedThreadMeta {
    const {
      queue: _queue,
      steer: _steer,
      signInOutput: _signInOutput,
      stalledSince: _stalledSince,
      chatGrants: _chatGrants,
      ...info
    } = t.info;
    const restarting = t.sessionId === null ? t.sessionBeforeRestart : null;
    return {
      version: 1,
      info: restarting === null ? info : { ...info, resumable: restarting.resumable },
      sessionId: t.sessionId ?? restarting?.sessionId ?? null,
      cwd: t.cwd,
      agentRef: t.agentRef,
      docName: t.docName,
      contextWindow: t.confirmedContextWindow ?? null,
      browserNotice: t.browserNotice,
    };
  }

  private failPendingPermissions(t: ThreadRecord): void {
    for (const [requestId, pending] of t.pendingPermissions) {
      clearTimeout(pending.timer);
      pending.resolve({ outcome: { outcome: 'cancelled' } });
      this.appendEvent(t, {
        kind: 'permission_resolved',
        requestId,
        optionId: null,
        auto: true,
        ts: Date.now(),
      });
    }
    t.pendingPermissions.clear();
  }

  private failPendingConsents(t: ThreadRecord): void {
    for (const map of [t.pendingRuntimeConsent, t.pendingPiBridgeConsent]) {
      for (const pending of map.values()) {
        clearTimeout(pending.timer);
        pending.resolve('closed');
      }
      map.clear();
    }
  }

  private setPresence(t: ThreadRecord, currentDoc: string): void {
    const broadcaster = this.opts.agentPresenceBroadcaster;
    if (broadcaster === undefined || broadcaster === null) return;
    try {
      const icon = iconFromClientName(t.info.agent.id);
      const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(t.agentSessionId);
      broadcaster.setPresence(toBroadcasterKey(t.agentSessionId), {
        displayName: t.info.agent.name,
        icon,
        color,
        currentDoc,
        mode: 'writing',
        ts: Date.now(),
        docTs: Date.now(),
      });
    } catch (err) {
      this.opts.log.warn({ err }, '[acp-threads] presence update failed');
    }
  }

  private reapIdleThreads(): void {
    const now = Date.now();
    const cutoff = now - this.idleReapMs;
    for (const t of this.threads.values()) {
      if (t.info.archived === true) continue;
      if (t.subscribers.size === 0 && !t.turnActive && t.info.lastActivityAt < cutoff) {
        this.opts.log.info({ threadId: t.info.threadId }, '[acp-threads] reaping idle thread');
        this.closeThread(t.info.threadId).catch((err: unknown) => {
          this.opts.log.error({ err, threadId: t.info.threadId }, '[acp-threads] reap failed');
        });
        continue;
      }
      if (!t.turnActive || t.unwatchedSince === null) continue;
      const unwatchedFor = now - t.unwatchedSince;
      if (unwatchedFor >= this.unwatchedTurnKillMs) {
        this.opts.log.warn(
          { threadId: t.info.threadId, unwatchedFor },
          '[acp-threads] force-closing unwatched turn that ignored cancel',
        );
        this.closeThread(t.info.threadId).catch((err: unknown) => {
          this.opts.log.error(
            { err, threadId: t.info.threadId },
            '[acp-threads] force-close failed',
          );
        });
      } else if (unwatchedFor >= this.unwatchedTurnCancelMs && !t.unwatchedCancelSent) {
        t.unwatchedCancelSent = true;
        this.opts.log.warn(
          { threadId: t.info.threadId, unwatchedFor },
          '[acp-threads] cancelling turn running with zero subscribers',
        );
        this.cancel(t.info.threadId);
      }
    }
  }
}

export async function confineToContentDir(
  contentDir: string,
  requestedPath: string,
  isExcludedPath: (relPosix: string) => boolean,
): Promise<{ abs: string; rel: string; docName: string | null }> {
  const contentRoot = await realpath(contentDir);
  const abs = normalize(
    isAbsolute(requestedPath) ? requestedPath : resolve(contentRoot, requestedPath),
  );
  let existing = abs;
  let suffix = '';
  for (;;) {
    try {
      const real = await realpath(existing);
      const resolved = suffix === '' ? real : join(real, suffix);
      const rel = relative(contentRoot, resolved);
      if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) {
        throw new Error(`path escapes the content directory: ${requestedPath}`);
      }
      const relPosix = rel.split(sep).join('/');
      const mdMatch = /\.(md|mdx)$/.exec(relPosix);
      const candidate =
        mdMatch !== null
          ? relPosix.slice(0, -mdMatch[0].length)
          : isMermaidDoc(relPosix) || isExcalidrawDoc(relPosix) || isEditableTextDoc(relPosix)
            ? relPosix
            : null;
      const docName =
        candidate !== null &&
        !isSystemDoc(candidate) &&
        !isConfigDoc(candidate) &&
        !isExcludedPath(relPosix)
          ? candidate
          : null;
      return { abs: resolved, rel: relPosix, docName };
    } catch (err) {
      if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
      const parent = dirname(existing);
      if (parent === existing) throw err;
      suffix =
        suffix === ''
          ? abs.slice(parent.length + 1)
          : join(existing.slice(parent.length + 1), suffix);
      existing = parent;
    }
  }
}

function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {
  const status = meta.info.status === 'error' ? 'error' : 'exited';
  return {
    confirmedContextWindow: meta.contextWindow ?? null,
    launchSettings: meta.contextWindow == null ? undefined : { contextWindow: meta.contextWindow },
    info: {
      ...meta.info,
      contextWindow: null,
      status,
      archived: true,
      resumable: meta.info.resumable === false ? false : meta.sessionId !== null,
      queue: undefined,
      steer: undefined,
      signInOutput: undefined,
      chatGrants: undefined,
    },
    docName: meta.docName,
    agentRef: meta.agentRef,
    cwd: meta.cwd,
    child: null,
    conn: null,
    lastInit: null,
    terminalAuthBase: null,
    sessionId: meta.sessionId,
    sessionBeforeRestart: null,
    agentSessionId: `acp-${meta.info.threadId}`,
    events: [],
    baseSeq: meta.info.lastSeq + 1,
    logResolved: false,
    logResolution: null,
    midTurnOnDisk: false,
    resumeInFlight: false,
    authInFlight: false,
    launchTicket: null,
    suppressUpdates: false,
    lastSuppressedAt: 0,
    subscribers: new Set(),
    pendingPermissions: new Map(),
    reportedToolCalls: new Map(),
    toolCallReportWaiters: new Map(),
    browserInjected: false,
    browserNotice: meta.browserNotice ?? null,
    pendingRuntimeConsent: new Map(),
    pendingPiBridgeConsent: new Map(),
    piBridgeDeclined: false,
    lastPiBridgeStatus: null,
    stderrTail: [],
    drainStderr: null,
    authStderr: null,
    terminals: null,
    turnActive: false,
    cancelRequested: false,
    steerStallTimer: null,
    stallTimer: null,
    turnStartedAt: null,
    agentActivityAt: Date.now(),
    unwatchedSince: null,
    unwatchedCancelSent: false,
    pendingBroadcast: [],
    pendingBroadcastFromSeq: 0,
    flushTimer: null,
    closed: false,
    hadUserMessage: true,
    envNotePending: false,
    projectSkill: null,
    chatGrants: new Set(),
  };
}

function initialConfigValueValid(option: SessionConfigOption, value: string | boolean): boolean {
  if (typeof value === 'boolean') return option.type === 'boolean';
  if (option.type !== 'select') return false;
  for (const entry of option.options) {
    if ('value' in entry) {
      if (entry.value === value) return true;
    } else if (entry.options.some((o) => o.value === value)) {
      return true;
    }
  }
  return false;
}

function declinedRuntimeHint(runtimeKind: ManagedRuntimeKind): string {
  const d = describeRuntime(runtimeKind);
  const installUrl =
    runtimeKind === 'node'
      ? 'https://nodejs.org'
      : 'https://docs.astral.sh/uv/getting-started/installation/';
  return `This agent needs \`${d.provides}\`, which isn't installed. OK can download a private copy of ${d.displayName} for you, or install ${d.displayName} yourself (${installUrl}) and it'll be used automatically.`;
}

function expiredRuntimeHint(runtimeKind: ManagedRuntimeKind): string {
  const d = describeRuntime(runtimeKind);
  const installUrl =
    runtimeKind === 'node'
      ? 'https://nodejs.org'
      : 'https://docs.astral.sh/uv/getting-started/installation/';
  return `This agent needs \`${d.provides}\`, which isn't installed. The offer to download a private copy of ${d.displayName} expired before it was answered — start the agent again to get it back, or install ${d.displayName} yourself (${installUrl}) and it'll be used automatically.`;
}

function isAuthRequiredError(err: unknown): boolean {
  if (typeof err !== 'object' || err === null) return false;
  const e = err as { code?: unknown; data?: unknown };
  if (e.code === AUTH_REQUIRED_CODE) return true;
  if (typeof e.data === 'object' && e.data !== null) {
    const kind = (e.data as { errorKind?: unknown }).errorKind;
    if (kind === 'authentication_failed') return true;
  }
  return false;
}

function agentErrorMessage(err: unknown): string {
  return err instanceof Error ? err.message : String(err);
}

function agentErrorData(err: unknown): string | undefined {
  if (typeof err !== 'object' || err === null) return undefined;
  const data = (err as { data?: unknown }).data;
  if (data === undefined || data === null) return undefined;
  try {
    return redactDiagnostic(JSON.stringify(data)).slice(0, 300);
  } catch {
    return undefined;
  }
}

function appliedContextWindow(record: ThreadRecord): number | null {
  if (launchContextMechanism(record.agentRef.id) !== 'codex-config-env') return null;
  return record.launchSettings?.contextWindow ?? null;
}

function lastFailureMessage(t: ThreadRecord): string | undefined {
  for (let i = t.events.length - 1; i >= 0; i -= 1) {
    const event = t.events[i];
    if (event === undefined || event.kind !== 'status') continue;
    if (event.status !== 'error' && event.status !== 'auth_required') continue;
    return event.detail ?? event.failure?.agentMessage;
  }
  return undefined;
}

async function connectionFailureDetail(
  err: unknown,
  record: ThreadRecord,
  ownsStderrTail: boolean,
): Promise<ThreadFailureDetail> {
  const detail =
    err instanceof AgentLaunchError || err instanceof ThreadOpError ? err.message : String(err);
  return {
    reason: 'connect',
    agentMessage: detail,
    machineDetail: joinMachineDetail({
      primary: err instanceof AgentLaunchError ? err.machineDetail : undefined,
      tail: ownsStderrTail ? await stderrTailDetail(record) : undefined,
    }),
  };
}

function queuedFromSteer(steer: SteerMessage): QueuedMessage {
  const demoted: QueuedMessage = { id: crypto.randomUUID(), content: steer.content, ts: steer.ts };
  if (steer.attachments !== undefined && steer.attachments.length > 0) {
    demoted.attachments = steer.attachments;
  }
  return demoted;
}

function isThreadClosed(t: ThreadRecord): boolean {
  return t.closed || t.info.archived === true;
}

function beginLaunch(
  t: ThreadRecord,
  initialPrompt: LaunchTicket['initialPrompt'] = null,
): LaunchTicket {
  const ticket: LaunchTicket = { initialPrompt };
  t.launchTicket = ticket;
  return ticket;
}

function isCurrentLaunch(t: ThreadRecord, ticket: LaunchTicket): boolean {
  return t.launchTicket === ticket;
}

async function stderrTailDetail(t: ThreadRecord): Promise<string | undefined> {
  const lines = t.stderrTail;
  await t.drainStderr?.();
  const tail = redactDiagnostic(lines.join('\n')).slice(-ACQUISITION_DETAIL_MAX_CHARS);
  return tail === '' ? undefined : tail;
}

function joinMachineDetail({
  primary,
  tail,
}: {
  primary: string | undefined;
  tail: string | undefined;
}): string | undefined {
  if (!primary) return tail?.slice(-ACQUISITION_DETAIL_MAX_CHARS) || undefined;
  if (!tail) return primary.slice(0, ACQUISITION_DETAIL_MAX_CHARS);
  const tailFloor = Math.min(tail.length, 1024);
  const primaryBudget = ACQUISITION_DETAIL_MAX_CHARS - tailFloor - 1;
  const headline =
    primary.length > primaryBudget ? `${primary.slice(0, primaryBudget - 1)}…` : primary;
  const remaining = ACQUISITION_DETAIL_MAX_CHARS - headline.length - 1;
  return `${headline}\n${tail.slice(-remaining)}`;
}

function authMachineDetail(err: unknown, t: ThreadRecord): string | undefined {
  const duringSignIn = t.authStderr === null ? undefined : t.authStderr.join('\n');
  return joinMachineDetail({ primary: agentErrorData(err), tail: duringSignIn });
}

function resumableFromCapabilities(init: InitializeResponse): boolean {
  const caps = init.agentCapabilities;
  return caps?.sessionCapabilities?.resume != null || caps?.loadSession === true;
}

const REPORTED_TOOL_CALL_LIMIT = 256;

const REPORTED_TOOL_CALL_WAIT_MS = 1_000;

function mergeToolCallEvidence(
  reported: BrowserCallEvidence | undefined,
  current: BrowserCallEvidence,
): BrowserCallEvidence {
  const reportedMeta = asRecord(reported?._meta);
  const currentMeta = asRecord(current._meta);
  return {
    title: current.title ?? reported?.title ?? null,
    kind: current.kind ?? reported?.kind ?? null,
    rawInput: current.rawInput ?? reported?.rawInput,
    ...(reportedMeta !== null || currentMeta !== null
      ? { _meta: { ...reportedMeta, ...currentMeta } }
      : {}),
  };
}

function rememberReportedToolCall(
  record: ThreadRecord,
  update: BrowserCallEvidence & { readonly toolCallId: string },
): void {
  const merged = mergeToolCallEvidence(record.reportedToolCalls.get(update.toolCallId), update);
  record.reportedToolCalls.delete(update.toolCallId);
  record.reportedToolCalls.set(update.toolCallId, merged);
  if (record.reportedToolCalls.size > REPORTED_TOOL_CALL_LIMIT) {
    const oldest = record.reportedToolCalls.keys().next().value;
    if (oldest !== undefined) record.reportedToolCalls.delete(oldest);
  }
  const waiters = record.toolCallReportWaiters.get(update.toolCallId);
  if (waiters === undefined) return;
  record.toolCallReportWaiters.delete(update.toolCallId);
  for (const wake of waiters) wake();
}

async function reportedToolCall(
  record: ThreadRecord,
  toolCall: ToolCallUpdate,
  requestMeta: unknown,
  log: PinoLogger,
): Promise<BrowserCallEvidence | undefined> {
  const id = toolCall.toolCallId;
  const known = record.reportedToolCalls.get(id);
  if (known !== undefined || !record.browserInjected) return known;
  if (!needsReportedToolCall(toolCall, requestMeta, record.info.agent.id)) return known;
  await new Promise<void>((resolve) => {
    const waiters = record.toolCallReportWaiters.get(id) ?? [];
    const wake = () => {
      clearTimeout(timer);
      const remaining = (record.toolCallReportWaiters.get(id) ?? []).filter((w) => w !== wake);
      if (remaining.length > 0) record.toolCallReportWaiters.set(id, remaining);
      else record.toolCallReportWaiters.delete(id);
      resolve();
    };
    const timer = setTimeout(() => {
      log.warn(
        { threadId: record.info.threadId, toolCallId: id },
        '[acp-threads] no tool call report arrived for a permission request in a chat with the browser; asking with no option to always allow it',
      );
      wake();
    }, REPORTED_TOOL_CALL_WAIT_MS);
    timer.unref?.();
    waiters.push(wake);
    record.toolCallReportWaiters.set(id, waiters);
  });
  return record.reportedToolCalls.get(id);
}