Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

80.0 KB
Raw Blame
/**
 * AppServerHost — 共享 codex app-server 子进程, N session 通过 thread_id 多路复用。
 *
 * 路线 A 设计 (对齐 OpenAI 官方):
 *   - 1 个 CodexAgent 实例只 spawn 1 个 codex app-server 子进程
 *   - 每个 maker session 对应 server 端一个 thread, 通过 thread/start 创建拿 thread_id
 *   - 入站 notification 按 params.threadId 路由到对应 session 的 handlers
 *
 * Lifecycle (用户明确要求, 比 refcount 模型更简单):
 *   - 懒启动: 第一个 acquire/subscribeThread 触发 spawn + initialize
 *   - server 一旦起来, 跟 CodexAgent (= app 进程) 同生命周期, **不随 session 数升降**
 *   - session.close → subscription.release(): 删除本地路由并发送 thread/unsubscribe,
 *     释放该 thread 的 live runtime;共享 app-server 继续服务其他 session
 *   - app.before-quit → 上层显式调 host.shutdown() (Windows 子进程不会随父进程死)
 *
 * 真值参考:
 *   - codex-rs/app-server-client/README.md (shared in-process facade 思路)
 *   - codex-rs/app-server/src/thread_state.rs (server 端 HashMap<thread_id, ThreadState>)
 *
 * 性能纪律 (plan 强制):
 *   - 全异步 IO, 主线程不阻塞
 *   - notification 路由 O(1) (Map lookup + 函数调用)
 *   - notification buffer 防 thread/start response 与 thread/started 通知的固有竞争
 */

import { randomUUID } from 'node:crypto';

import type { Logger } from '../../../interfaces/logger.js';
import type { CodexSessionMcpConfigInput, CodexSubagentRoutingProfile } from '../../base-agent.js';
import { AppServerClient, type RequestProgressDeadline } from './client.js';
import { CODEX_EXTERNAL_AUTH_REFRESH, CodexExternalAuthSession, assertCodexEphemeralAuth, type CodexExternalAuth } from './external-auth.js';
import type { Transport } from './transport.js';
import {
  Method,
  type ClientInfo,
  type CommandExecutionRequestApprovalParams,
  type CommandExecutionRequestApprovalResponse,
  type DynamicToolCallParams,
  type DynamicToolCallResponse,
  type ErrorNotification,
  type FileChangeRequestApprovalParams,
  type FileChangeRequestApprovalResponse,
  type McpServerElicitationRequestParams,
  type McpServerElicitationRequestResponse,
  type CodexMcpServerStatusListResponse,
  type PermissionsRequestApprovalParams,
  type PermissionsRequestApprovalResponse,
  type ServerRequestResolvedNotification,
  type ToolRequestUserInputParams,
  type ToolRequestUserInputResponse,
  type InitializeCapabilities,
  type InitializeResponse,
  type ItemCompletedNotification,
  type ItemStartedNotification,
  type ItemUpdatedNotification,
  type JsonRpcId,
  type ThreadStartedNotification,
  type ThreadTokenUsageUpdatedNotification,
  type ThreadUnsubscribeResponse,
  type TurnPlanUpdatedNotification,
  type TurnCompletedNotification,
  type TurnDiffUpdatedNotification,
  type TurnStartedNotification,
  type ReasoningSummaryTextDeltaNotification,
  type ReasoningSummaryPartAddedNotification,
  type ReasoningTextDeltaNotification,
  type ReasoningEffort,
  type AccountRateLimitsUpdatedNotification,
  type AgentMessageDeltaNotification,
  type ThreadStatusChangedNotification,
  type ThreadSettingsUpdatedNotification,
  type ItemGuardianApprovalReviewStartedNotification,
  type ItemGuardianApprovalReviewCompletedNotification,
  type GuardianWarningNotification,
  type WarningNotification,
} from './protocol.js';

/**
 * 我们订阅的 notification 方法集 — 这之外的 (大部分 delta + plan/diff/hook/etc.)
 * 在 initialize 时通过 optOutNotificationMethods 告诉 server 别推, 省 IPC 带宽。
 *
 * agentMessage 正文订阅专用 delta;item/updated 全量字段保留为兼容兜底与校准来源。
 * reasoning summary 流必须订阅 delta — claude code 等价体验需要逐字出 thinking 文本,
 * item/completed 给的是终态全文 (用来校准), 中间过程靠 delta 才能动起来。
 */
const SUBSCRIBED_METHODS = [
  'thread/started',
  'turn/started',
  'turn/completed',
  'turn/diff/updated',
  'thread/tokenUsage/updated', // Codex usage 走单独通知 (不在 turn/completed 上), 必订
  'item/started',
  'item/updated',
  'item/completed',
  'item/agentMessage/delta',
  'turn/plan/updated',             // Codex update_plan snapshots
  'item/reasoning/summaryTextDelta', // 流式 reasoning 文本增量 (OpenAI summary)
  'item/reasoning/summaryPartAdded', // summary 分段标记 (插 \n\n 分隔用)
  'item/reasoning/textDelta',        // raw inner reasoning 增量 (开源模型才发, OpenAI 通常空)
  'account/rateLimits/updated',      // 账号配额变化 (无 threadId, 走全局 fan-out 路径)
  'thread/status/changed',           // 线程级 active_flags (waiting on approval / user input) — turn lifecycle 部分我们自己拼
  'thread/settings/updated',         // 中途 thread/settings/update 后 server 回带的权威设置快照 (serviceTier / model / effort)
  'serverRequest/resolved',          // 原生 requestUserInput / approval 请求被 server 端自动清理
  'item/autoApprovalReview/started',
  'item/autoApprovalReview/completed',
  'guardianWarning',
  'warning',                         // thread 级提示 (如 WebSocket 回退到 HTTPS)
  'error',
] as const;

const NOTIFICATIONS_TO_OPT_OUT = [
  'item/plan/delta',
  'item/commandExecution/outputDelta',
  'item/fileChange/outputDelta',
  // 以下高频通知全仓无消费方 (client 只会落一条 unhandled notification 日志, 实测合计
  // ~2万条/天)。要消费其中任一项时, 先从这里移除再加进 SUBSCRIBED_METHODS。
  'turn/moderationMetadata',
  'mcpServer/startupStatus/updated',
  'remoteControl/status/changed',
  'item/commandExecution/terminalInteraction',
];

const DEFAULT_THREAD_UNSUBSCRIBE_TIMEOUT_MS = 5_000;

/** thread/started 之外的 notification 都直接 params.threadId; thread/started 走 params.thread.id。 */
function extractThreadId(method: string, params: unknown): string | null {
  if (!params || typeof params !== 'object') return null;
  if (method === 'thread/started') {
    const t = (params as { thread?: { id?: unknown } }).thread;
    return typeof t?.id === 'string' ? t.id : null;
  }
  const tid = (params as { threadId?: unknown }).threadId;
  return typeof tid === 'string' ? tid : null;
}

export interface ThreadEventHandlers {
  threadStarted?: (params: ThreadStartedNotification['params']) => void;
  descendantThreadStarted?: (params: ThreadStartedNotification['params']) => void;
  /**
   * 子线程(子代理)自己的 notification,按 lineage 归到 root 订阅者。
   *
   * 刻意**不复用** dispatchToHandlers 的主线程通道:主线程 handler 带 turn 级簿记
   * (stale turn 判定、currentTurnId、status 推送、usageTracker 记账),子线程事件
   * 灌进去会把子代理的 exec/文件改动渲染成主会话自己的工具调用,并污染主 turn 的
   * 用量与状态机。这里只投递原始 method + params,由上层聚合成子代理卡的实时状态;
   * 上层不关心的 method 自行忽略。
   */
  descendantNotification?: (childThreadId: string, method: string, params: unknown) => void;
  turnStarted?: (params: TurnStartedNotification['params']) => void;
  turnCompleted?: (params: TurnCompletedNotification['params']) => void;
  turnDiffUpdated?: (params: TurnDiffUpdatedNotification['params']) => void;
  /** 每次 turn 都会推一次 (turn 完成前), 与 turn/completed 在同 turnId 下成对出现。 */
  tokenUsageUpdated?: (params: ThreadTokenUsageUpdatedNotification['params']) => void;
  itemStarted?: (params: ItemStartedNotification['params']) => void;
  itemUpdated?: (params: ItemUpdatedNotification['params']) => void;
  itemCompleted?: (params: ItemCompletedNotification['params']) => void;
  /** 正文的逐段增量;item/completed 仍会下发最终全文做权威校准。 */
  agentMessageDelta?: (params: AgentMessageDeltaNotification['params']) => void;
  /** Codex native update_plan snapshots. */
  turnPlanUpdated?: (params: TurnPlanUpdatedNotification['params']) => void;
  /** OpenAI reasoning summary 单段内的文本增量 (按 summaryIndex 区分段)。 */
  reasoningSummaryTextDelta?: (params: ReasoningSummaryTextDeltaNotification['params']) => void;
  /** reasoning summary 新开一段, 后续 summaryTextDelta 用新的 summaryIndex。 */
  reasoningSummaryPartAdded?: (params: ReasoningSummaryPartAddedNotification['params']) => void;
  /** raw inner reasoning 增量 (OpenAI 通常不发, 开源模型才发)。 */
  reasoningTextDelta?: (params: ReasoningTextDeltaNotification['params']) => void;
  /**
   * 账号配额变化 (5h / weekly 滚动窗口 + credits + reachedType)。
   * 账号级数据, host 内部缓存最近 snapshot, 给所有 active subscriber 各调一次;
   * 新 subscribe 时也立即重放最近一次 (防止打开新 session 时 chip 显示空)。
   */
  accountRateLimitsUpdated?: (params: AccountRateLimitsUpdatedNotification['params']) => void;
  /**
   * 线程级粗粒度状态机 (Idle / NotLoaded / SystemError / Active{flags})。
   * 我们只在意 Active.activeFlags 的两类等待标志, 用来 emit "Waiting on approval/input..." status。
   * Idle/SystemError 由 turn/completed + error notification 主导, 不在这里重复处理。
   */
  threadStatusChanged?: (params: ThreadStatusChangedNotification['params']) => void;
  /**
   * 中途 thread/settings/update 后 server 回带的权威设置快照 (serviceTier / model /
   * effort 等)。用来把本地 mutable 三态对齐 server 真相 (例如模型不支持 fast 时
   * server 会把 serviceTier 降级)。
   */
  threadSettingsUpdated?: (params: ThreadSettingsUpdatedNotification['params']) => void;
  serverRequestResolved?: (params: ServerRequestResolvedNotification['params']) => void;
  /** Codex built-in Guardian auto-review lifecycle (Auto permission mode). */
  autoApprovalReviewStarted?: (params: ItemGuardianApprovalReviewStartedNotification) => void;
  autoApprovalReviewCompleted?: (params: ItemGuardianApprovalReviewCompletedNotification) => void;
  guardianWarning?: (params: GuardianWarningNotification) => void;
  warning?: (params: WarningNotification['params']) => void;
  error?: (params: ErrorNotification['params']) => void;
  /**
   * Host 被永久替换(强制退役,如账号切换 / auth 失效)时发给每个订阅者的结构化
   * 生命周期信号。订阅者按自身真实状态收口:
   *
   * - 空闲 / 已完成的订阅者静默失效,不产生任何错误事件——不应把一次内部 host 替换
   *   渲染成历史会话的终止错误(#1391 场景:闲置数小时的已完成会话在切账号时被打
   *   永久红框)。
   * - 真实在飞(turn in-flight / turn/start pending / overload retry)的订阅者清理
   *   在途状态并产生一次终态 error + Done,保证 isTurnRunning 复位、上层 busy 判定 /
   *   Stop 锁 / 输入队列不卡死(2026-07-19 auth app_session_terminated 实排)。
   *
   * 提供该回调时,host **不再**广播 transport error(否则空 turnId 的错误无法被
   * pending/retry 会话收口)。未提供时保持旧行为(广播 transport error)。
   */
  hostForcedRetire?: (signal: { reason: string }) => void;

  // ── ServerRequest (Phase 2 approval) ─────────────────────────────────────
  // server → client 的 request, 必须返回 response (否则 server 卡 turn)。
  // Host 按 params.threadId 路由, 找不到 subscriber 默认 decline (安全兜底)。
  /** server 要求审批 shell 命令执行。 */
  commandExecutionApproval?: (
    params: CommandExecutionRequestApprovalParams,
  ) => Promise<CommandExecutionRequestApprovalResponse>;
  /** server 要求审批文件改动。 */
  fileChangeApproval?: (
    params: FileChangeRequestApprovalParams,
  ) => Promise<FileChangeRequestApprovalResponse>;
  mcpServerElicitation?: (
    params: McpServerElicitationRequestParams,
  ) => Promise<McpServerElicitationRequestResponse>;
  /** server 要求审批 MCP 工具等权限请求 (item/permissions/requestApproval)。 */
  permissionsApproval?: (
    params: PermissionsRequestApprovalParams,
  ) => Promise<PermissionsRequestApprovalResponse>;
  /** EXPERIMENTAL: model/native tool asks the client to collect user input. */
  requestUserInput?: (
    params: ToolRequestUserInputParams,
    meta: ServerRequestMeta,
  ) => Promise<ToolRequestUserInputResponse>;
  /** EXPERIMENTAL: app-server dynamic tool call. */
  dynamicToolCall?: (
    params: DynamicToolCallParams,
    meta: ServerRequestMeta,
  ) => Promise<DynamicToolCallResponse>;
}

export interface ServerRequestMeta {
  requestId: JsonRpcId;
}

export interface ThreadSubscription {
  /** 幂等地解除本地路由,并释放 app-server 内对应 thread 的 live runtime。 */
  release(): Promise<void>;
}

export interface AppServerHostOptions {
  /** Applied before the host becomes ready, and reapplied after every transport restart. */
  externalAuth?: CodexExternalAuth;
  /** Required for every cross-home runtime, including gateway-only routes. */
  requireEphemeralAuth?: boolean;
  /**
   * Transport 工厂; host 每次 bootstrap (含 transport-error 后的重连) 都调一次。
   * 本地 codex 用 `createStdioTransport({binaryPath, cwd, env, extraArgs})`,
   * 远端 codex 用 `createSshDaemonTransport({remoteHost, ...})` (P2)。
   */
  createTransport: () => Transport;
  logger: Logger;
  /** initialize 时上报的客户端身份 (走 server 日志 / thread metadata)。 */
  clientInfo: ClientInfo;
  /**
   * notification 到达时若没找到 subscriber 的缓存窗口 (默认 5000ms)。
   * 解决 thread/started 比 subscribeThread() 早到的固有竞争。
   */
  notificationBufferTtlMs?: number;
  /** thread/unsubscribe 的最大等待时间,避免 session close 被失联 app-server 卡死。 */
  threadUnsubscribeTimeoutMs?: number;
  /**
   * 关联中的 JSON-RPC response 明确返回 cloudRequirements Auth/relogin 时调用一次
   * (单次 latch 在 client 内)。stderr 始终只作为诊断日志。
   */
  onAuthInvalidated?: (
    reason: string,
    context?: { credentialGeneration?: string | null },
  ) => void;
  /** Returns the credential generation frozen for the current concrete transport. */
  captureCredentialGeneration?: () => string | null;
  /**
   * Host 创建时冻结的事实:该 app-server 的 model_provider.base_url 是否走
   * 本机 codex proxy。session 级 prompt gate 只读这个值,不再 live 读取全局状态。
   */
  codexProxyActive?: boolean;
  /** Host creation snapshot: this exact process received the Browser companion. */
  codexBrowserUseAvailable?: boolean;
  /** Exact verified Chrome plugin version provisioned into this process. */
  codexBrowserUseVersion?: string;
  /** Maximum wait for the provisioned Browser companion to publish its MCP tools. */
  codexBrowserUseStartupTimeoutMs?: number;
  /**
   * Host 创建时冻结的 ChatGPT OpenAI transport identity,仅 oauth-bearer spawn 存在。
   */
  remoteCompactionProviderId?: string;
  /** Cindy Provider codex/* 的内部 OpenAI transport identity。 */
  cindyRemoteCompactionProviderId?: string;
  localCompactionProviderId?: string;
  /** Generic custom Provider identities and capabilities frozen into this process. */
  codexCustomProviderRoutes?: Array<{
    providerId: string;
    modelProviderId: string;
    capabilities: Readonly<Record<string, boolean | undefined>>;
    responseModels: readonly string[];
  }>;
  /** Per-thread host-owned MCP URL overrides keyed by the Session instance. */
  buildSessionMcpConfig?: (
    sessionInstanceId: string,
    session?: CodexSessionMcpConfigInput,
  ) => Record<string, unknown>;
  /** Cindy-side fallback used only when a subagent's actual model is not reported. */
  subagentModelFallback?: string;
  /** Frozen provider/model/effort identity for the configured locked subagent route. */
  subagentRoute?: {
    providerId: string;
    catalogModel: string;
    reasoningEffort?: ReasoningEffort | null;
  };
  smartSubagentRoutes?: Array<{
    providerId: string;
    catalogModel: string;
    reasoningEffort?: ReasoningEffort | null;
  }>;
  /** Frozen identity of the Subagent routing/catalog snapshot used by this host. */
  codexSubagentRoutingSignature?: string;
  getSubagentIdentity?: (childThreadId: string) => {
    model: string;
    reasoningEffort?: string;
  } | undefined;
  /** Whether the OpenAI identity provider may use Responses WebSocket on this host. */
  codexOpenAiWebSocketsEnabled?: boolean;
  /** Host-level Subagent route profile used to prevent incompatible local host reuse. */
  codexSubagentRoutingProfile?: CodexSubagentRoutingProfile;
  /** One-shot cleanup for resources owned by this Host generation, run only on terminal retire. */
  onRetired?: () => void | Promise<void>;
}

interface BufferedNotification {
  method: string;
  params: unknown;
  ts: number;
}

/** All native attempts have exited before this error is exposed to a task startup. */
export class CodexNativeInitializationStoppedError extends Error {}

export class AppServerHost {
  private readonly externalAuth: CodexExternalAuthSession | undefined;
  private readonly connectionId = randomUUID();
  private readonly logger: Logger;
  private readonly bufferTtlMs: number;
  private readonly threadUnsubscribeTimeoutMs: number;

  private client: AppServerClient | null = null;
  // Negative proof belongs to the exact transport, not readiness or provider.
  // Any application RPC may load a thread (including future protocol methods).
  // Bootstrap initialize/config/auth and the read-only writer probe do not.
  private readonly writerCandidates = new WeakSet<AppServerClient>();
  /** 同次 ensureStarted 并发调用共享一个 init Promise (避免重复 spawn)。 */
  private startPromise: Promise<InitializeResponse> | null = null;
  private nativeInitializationEpoch = 0;

  private readonly subscribers = new Map<string, ThreadEventHandlers>();
  /** root / descendant threadId → 当前拥有该子树订阅的 root threadId。 */
  private readonly lineageRoots = new Map<string, string>();
  /**
   * 父 turn 尚在对账时的 provisional child claim。
   *
   * reserve 只保活 child 缓冲与 server request waiter,不安装 root 路由;
   * 父 turn 被接受后由 registerDescendantLineage commit,判成孤儿则 discard。
   */
  private readonly pendingLineage = new Map<
    string,
    { parentThreadId: string; rootThreadId: string }
  >();
  /** Server request may race the child thread/started notification that establishes lineage. */
  private readonly threadHandlerWaiters = new Map<string, Set<() => void>>();
  /** One post-start MCP inventory probe per server/tool for this concrete process. */
  private readonly mcpToolAvailability = new Map<string, Promise<boolean>>();
  /** 找不到 subscriber 时按 threadId 暂存的 notification, drain on subscribe。 */
  private readonly buffered = new Map<string, BufferedNotification[]>();
  /** 血缘迭代重建的重入闸(routeDescendantThreadStarted 与重建互相调用)。 */
  private replayingDescendantLineage = false;
  /**
   * 账号配额最近一次 snapshot, 给新 subscribeThread 立即重放 — 用户打开新 codex
   * session 时不必等下次 turn 完成才看到 chip 数据。整个 host 生命周期共享一份 (账号级)。
   */
  private readonly lastAccountRateLimits = new Map<string, AccountRateLimitsUpdatedNotification['params']>();
  /**
   * 没有 limitId 的稀疏更新按「合并进最近观察到的 bucket」约定处理 (usageBroadcaster), 不能当独立
   * bucket 去重或按插入序回放; 仅当它是最新一条时作为最后一份回放, 之后来了带 limitId 的即作废。
   */
  private lastIdlessAccountRateLimits: AccountRateLimitsUpdatedNotification['params'] | null = null;
  /**
   * 记录最近一次已 fan-out 的配额 payload (limitId + JSON), 仅用于丢弃连续重复。app-server 会以秒级间隔
   * 重复推送内容不变的快照 (实测 ~64% 与上一条相同), 相同内容不再重复广播与记日志。
   */
  private lastFannedOutRateLimitsKey: string | null = null;

  private shuttingDown = false;
  private shutdownPromise: Promise<void> | null = null;
  private retired = false;
  private retirementPromise: Promise<void> | null = null;

  constructor(private readonly opts: AppServerHostOptions) {
    this.externalAuth = opts.externalAuth ? new CodexExternalAuthSession(opts.externalAuth) : undefined;
    if (typeof opts.createTransport !== 'function') {
      throw new Error('AppServerHost: createTransport factory is required');
    }
    this.logger = opts.logger.child('codex-app-server-host');
    this.bufferTtlMs = opts.notificationBufferTtlMs ?? 5_000;
    this.threadUnsubscribeTimeoutMs =
      opts.threadUnsubscribeTimeoutMs ?? DEFAULT_THREAD_UNSUBSCRIBE_TIMEOUT_MS;
  }

  isCodexProxyActive(): boolean {
    return this.opts.codexProxyActive === true;
  }

  isCodexBrowserUseAvailable(): boolean {
    return this.opts.codexBrowserUseAvailable === true;
  }

  getCodexBrowserUseVersion(): string | null {
    return this.opts.codexBrowserUseVersion ?? null;
  }

  /**
   * Verify that an MCP server connected and published a concrete tool. Static
   * spawn provisioning is not enough: this is the post-initialize gate that
   * prevents a Skill from being shown when its runtime tool never registered.
   */
  waitForMcpTool(
    serverName: string,
    toolName: string,
    opts: { timeoutMs?: number; pollIntervalMs?: number } = {},
  ): Promise<boolean> {
    const key = `${serverName}\0${toolName}`;
    const cached = this.mcpToolAvailability.get(key);
    if (cached) return cached;
    const probe = this.probeMcpTool(
      serverName,
      toolName,
      opts.timeoutMs ?? this.opts.codexBrowserUseStartupTimeoutMs ?? 10_000,
      opts.pollIntervalMs ?? 100,
    );
    this.mcpToolAvailability.set(key, probe);
    // A negative readiness probe is a point-in-time result, not a permanent
    // host capability fact. The MCP child may finish starting later, so the
    // next session must be allowed to retry. Successful probes stay cached.
    void probe.then((available) => {
      if (!available && this.mcpToolAvailability.get(key) === probe) {
        this.mcpToolAvailability.delete(key);
      }
    });
    return probe;
  }

  private async probeMcpTool(
    serverName: string,
    toolName: string,
    timeoutMs: number,
    pollIntervalMs: number,
  ): Promise<boolean> {
    const deadline = Date.now() + timeoutMs;
    try {
      while (!this.shuttingDown && Date.now() < deadline) {
        let cursor: string | null = null;
        do {
          const remaining = deadline - Date.now();
          if (remaining <= 0) return false;
          const response: CodexMcpServerStatusListResponse =
            await this.request<CodexMcpServerStatusListResponse>(
              Method.McpServerStatusList,
              { cursor, limit: 100, detail: 'toolsAndAuthOnly', threadId: null },
              { timeoutMs: remaining },
            );
          const server = response.data.find((entry) => entry.name === serverName);
          if (server && Object.hasOwn(server.tools, toolName)) return true;
          cursor = response.nextCursor;
        } while (cursor !== null);
        const remaining = deadline - Date.now();
        if (remaining <= 0) return false;
        await new Promise<void>((resolve) => {
          setTimeout(resolve, Math.min(pollIntervalMs, remaining));
        });
      }
    } catch (error) {
      this.logger.warn('MCP tool readiness probe failed', {
        serverName,
        toolName,
        error: error instanceof Error ? error.message : String(error),
      });
    }
    return false;
  }

  /** oauth spawn 定义的 OpenAI 身份 provider id;非 oauth spawn / 未下发 → null。 */
  getRemoteCompactionProviderId(): string | null {
    return this.opts.remoteCompactionProviderId ?? null;
  }

  getLocalCompactionProviderId(): string | null {
    return this.opts.localCompactionProviderId ?? null;
  }

  getCindyRemoteCompactionProviderId(): string | null {
    return this.opts.cindyRemoteCompactionProviderId ?? null;
  }

  getCustomProviderModelProviderId(
    providerId: string | null | undefined,
    model: string | null | undefined,
  ): string | null {
    if (!providerId || !model) return null;
    const route = this.opts.codexCustomProviderRoutes?.find(
      (candidate) => candidate.providerId === providerId,
    );
    return route?.responseModels.includes(model) ? route.modelProviderId : null;
  }

  getCustomProviderThreadPolicy(
    providerId: string | null | undefined,
    model: string | null | undefined,
  ): {
    dynamicIdentity: boolean;
    disableSubagents: boolean;
    disableModelOverrides: boolean;
  } {
    const route = providerId && model
      ? this.opts.codexCustomProviderRoutes?.find(
          (candidate) =>
            candidate.providerId === providerId && candidate.responseModels.includes(model),
        )
      : undefined;
    if (!route) {
      return { dynamicIdentity: false, disableSubagents: false, disableModelOverrides: false };
    }
    const child = this.opts.subagentRoute;
    const childCompatible = !child || (
      child.providerId === route.providerId && route.responseModels.includes(child.catalogModel)
    );
    return {
      dynamicIdentity: true,
      disableSubagents: !childCompatible,
      disableModelOverrides: true,
    };
  }

  /**
   * Return the host-owned MCP URL overrides for one concrete Session instance.
   * Anonymous/legacy callers keep the spawn-level unbound URLs, which preserves
   * ordinary MCP compatibility while permission-sensitive tools fail closed.
   */
  getSessionMcpConfig(
    sessionInstanceId?: string,
    session?: CodexSessionMcpConfigInput,
  ): Record<string, unknown> {
    if (!sessionInstanceId || !this.opts.buildSessionMcpConfig) return {};
    return this.opts.buildSessionMcpConfig(sessionInstanceId, session);
  }

  /** Display metadata only; observed thread model always wins. */
  getSubagentModelFallback(): string | undefined {
    return this.opts.subagentModelFallback;
  }

  getSubagentRoute(): {
    providerId: string;
    catalogModel: string;
    reasoningEffort?: ReasoningEffort | null;
  } | undefined {
    return this.opts.subagentRoute;
  }

  getSmartSubagentRoutes(): AppServerHostOptions['smartSubagentRoutes'] {
    return this.opts.smartSubagentRoutes;
  }

  getSubagentRoutingSignature(): string | undefined {
    return this.opts.codexSubagentRoutingSignature;
  }

  getObservedSubagentIdentity(childThreadId: string): {
    model: string;
    reasoningEffort?: string;
  } | undefined {
    return this.opts.getSubagentIdentity?.(childThreadId);
  }

  getOpenAiWebSocketsEnabled(): boolean {
    return this.opts.codexOpenAiWebSocketsEnabled !== false;
  }

  getSubagentRoutingProfile(): CodexSubagentRoutingProfile {
    return this.opts.codexSubagentRoutingProfile ?? 'default';
  }

  getConnectionId(): string {
    return this.connectionId;
  }

  // ── 生命周期 ──────────────────────────────────────────────────────────────

  /**
   * 幂等 + 并发安全。第一次调用 spawn + initialize, 后续直接返回缓存的
   * InitializeResponse (或共享同一个 in-flight Promise)。
   */
  ensureStarted(capabilities?: InitializeCapabilities): Promise<InitializeResponse> {
    if (this.retired) {
      return Promise.reject(new Error('AppServerHost: cannot ensureStarted() after retirement'));
    }
    if (this.shuttingDown) {
      if (!this.shutdownPromise) {
        return this.shutdown('recheck failed shutdown before restart', { throwOnTransportError: true })
          .then(() => this.ensureStarted(capabilities));
      }
      return Promise.reject(new Error('AppServerHost: cannot ensureStarted() during shutdown'));
    }
    if (this.startPromise) return this.startPromise;
    const startPromise = this.bootstrap(capabilities).catch(async (err) => {
      // 旧启动的迟到失败不能关闭新 client;重试必须等旧进程真正退出。
      if (this.startPromise === startPromise) {
        try {
          await this.shutdown('AppServerHost bootstrap failed', { throwOnTransportError: true });
        } catch (closeError) {
          this.logger.warn('failed to close app-server client after bootstrap failure', {
            error: closeError instanceof Error ? closeError.message : String(closeError),
          });
        }
      }
      throw err;
    });
    this.startPromise = startPromise;
    return startPromise;
  }

  /**
   * ensureStarted 的限时变体 (codex R13 P1): startSession 直调路径用。
   * 冷启动 / transport 重建时 bootstrap 也可能永不返回 (远端 daemon 挂死 /
   * SSH 通道无响应) — request() 的关键 RPC 已带 startup+request 整体
   * deadline, 但 startSession 的 initialize 直调绕开了它, 需要同款上界,
   * 否则 UI 无限卡 session 初始化。
   *
   * 与 request() 内 startup deadline 同款语义: 超时只 reject 本次等待,
   * startPromise 后台继续 (并发共享, 下次调用可直接复用其结果), 挂
   * swallow catch 防迟到 settle 变 unhandled rejection。
   */
  async ensureStartedWithTimeout(timeoutMs: number, label: string): Promise<InitializeResponse> {
    const started = this.ensureStarted();
    let timer: NodeJS.Timeout | null = null;
    try {
      return await Promise.race([
        started,
        new Promise<never>((_, reject) => {
          timer = setTimeout(() => {
            this.nativeInitializationEpoch++;
            reject(new Error(`app-server startup (for ${label}) timed out after ${timeoutMs}ms`));
          }, timeoutMs);
          timer.unref?.();
        }),
      ]);
    } catch (err) {
      started.catch(() => { /* late startup failure swallowed after timeout */ });
      throw err;
    } finally {
      if (timer) clearTimeout(timer);
    }
  }

  private async bootstrap(
    capabilities?: InitializeCapabilities,
    nativeAttempt = 0,
    nativeEpoch = this.nativeInitializationEpoch,
  ): Promise<InitializeResponse> {
    const client = new AppServerClient({
      createTransport: this.opts.createTransport,
      logger: this.opts.logger,
      onTransportError: (err) => {
        // Keep the shared startPromise while recovering this one pre-protocol
        // failure. Every other transport error retains the normal host lifecycle.
        if (!client.nativeSqliteInitializationFailed()) this.handleTransportError(err);
      },
      onAuthInvalidated: this.opts.onAuthInvalidated,
      captureCredentialGeneration: this.opts.captureCredentialGeneration,
    });
    this.client = client;

    if (this.externalAuth) {
      client.setRequestHandler(CODEX_EXTERNAL_AUTH_REFRESH, async (params) => {
        if (this.client !== client || this.shuttingDown || this.retired) {
          throw new Error('Codex account authentication host has retired');
        }
        const request = params as { reason?: unknown; previousAccountId?: unknown } | null;
        if (request?.reason !== 'unauthorized') throw new Error('Unsupported Codex authentication refresh');
        const tokens = await this.externalAuth!.tokens(true, request.previousAccountId);
        if (this.client !== client || this.shuttingDown || this.retired) {
          throw new Error('Codex account authentication host has retired');
        }
        return tokens;
      });
    }

    // 注册 notification handlers BEFORE initialize: server 在握手响应前可能就推了
    // banner / 启动 notification, 漏接就丢。
    for (const method of SUBSCRIBED_METHODS) {
      client.onNotification(method, (params) => {
        if (extractThreadId(method, params)) this.writerCandidates.add(client);
        this.routeNotification(method, params);
      });
    }

    // ServerRequest handlers (Phase 2 approval) — 同样在 initialize 前注册,
    // 防 server 在握手过程中就发出 approval (虽然实际不会, 但 defensive)。
    client.setRequestHandler(Method.CommandExecutionRequestApproval, async (rawParams) => {
      const params = rawParams as CommandExecutionRequestApprovalParams;
      const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
      const handlers = resolvedHandlers instanceof Promise
        ? await resolvedHandlers
        : resolvedHandlers;
      if (!handlers?.commandExecutionApproval) {
        this.logger.warn('commandExecution approval without subscriber → decline', {
          threadId: params.threadId,
          itemId: params.itemId,
        });
        return { decision: 'decline' };
      }
      try {
        return await handlers.commandExecutionApproval(params);
      } catch (e) {
        this.logger.error('commandExecutionApproval handler threw → decline', {
          threadId: params.threadId,
          message: (e as Error).message,
        });
        return { decision: 'decline' };
      }
    });

    client.setRequestHandler(Method.FileChangeRequestApproval, async (rawParams) => {
      const params = rawParams as FileChangeRequestApprovalParams;
      const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
      const handlers = resolvedHandlers instanceof Promise
        ? await resolvedHandlers
        : resolvedHandlers;
      if (!handlers?.fileChangeApproval) {
        this.logger.warn('fileChange approval without subscriber → decline', {
          threadId: params.threadId,
          itemId: params.itemId,
        });
        return { decision: 'decline' };
      }
      try {
        return await handlers.fileChangeApproval(params);
      } catch (e) {
        this.logger.error('fileChangeApproval handler threw → decline', {
          threadId: params.threadId,
          message: (e as Error).message,
        });
        return { decision: 'decline' };
      }
    });

    client.setRequestHandler(Method.McpServerElicitationRequest, async (rawParams) => {
      const params = rawParams as McpServerElicitationRequestParams;
      const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
      const handlers = resolvedHandlers instanceof Promise
        ? await resolvedHandlers
        : resolvedHandlers;
      if (!handlers?.mcpServerElicitation) {
        this.logger.warn('MCP server elicitation without subscriber -> decline', {
          threadId: params.threadId,
          serverName: params.serverName,
        });
        return { action: 'decline', content: null, _meta: null } satisfies McpServerElicitationRequestResponse;
      }
      try {
        return await handlers.mcpServerElicitation(params);
      } catch (e) {
        this.logger.error('mcpServerElicitation handler threw -> decline', {
          threadId: params.threadId,
          serverName: params.serverName,
          message: (e as Error).message,
        });
        return { action: 'decline', content: null, _meta: null } satisfies McpServerElicitationRequestResponse;
      }
    });

    client.setRequestHandler(Method.PermissionsRequestApproval, async (rawParams) => {
      const params = rawParams as PermissionsRequestApprovalParams;
      const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
      const handlers = resolvedHandlers instanceof Promise
        ? await resolvedHandlers
        : resolvedHandlers;
      if (!handlers?.permissionsApproval) {
        this.logger.warn('permissions approval without subscriber → decline', {
          threadId: params.threadId,
        });
        return { permissions: {}, scope: 'turn' } satisfies PermissionsRequestApprovalResponse;
      }
      try {
        return await handlers.permissionsApproval(params);
      } catch (e) {
        this.logger.error('permissionsApproval handler threw → decline', {
          threadId: params.threadId,
          message: (e as Error).message,
        });
        return { permissions: {}, scope: 'turn' } satisfies PermissionsRequestApprovalResponse;
      }
    });

    client.setRequestHandler(Method.ToolRequestUserInput, async (rawParams, meta) => {
      const params = rawParams as ToolRequestUserInputParams;
      const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
      const handlers = resolvedHandlers instanceof Promise
        ? await resolvedHandlers
        : resolvedHandlers;
      if (!handlers?.requestUserInput) {
        this.logger.warn('requestUserInput without subscriber -> empty response', {
          threadId: params.threadId,
          itemId: params.itemId,
        });
        return { answers: {} } satisfies ToolRequestUserInputResponse;
      }
      try {
        return await handlers.requestUserInput(params, { requestId: meta.id });
      } catch (e) {
        this.logger.error('requestUserInput handler threw -> empty response', {
          threadId: params.threadId,
          itemId: params.itemId,
          message: (e as Error).message,
        });
        return { answers: {} } satisfies ToolRequestUserInputResponse;
      }
    });

    client.setRequestHandler(Method.DynamicToolCall, async (rawParams, meta) => {
      const params = rawParams as DynamicToolCallParams;
      const resolvedHandlers = this.resolveRequestHandlers(params.threadId);
      const handlers = resolvedHandlers instanceof Promise
        ? await resolvedHandlers
        : resolvedHandlers;
      if (!handlers?.dynamicToolCall) {
        this.logger.warn('dynamicToolCall without subscriber -> failed result', {
          threadId: params.threadId,
          callId: params.callId,
          tool: params.tool,
        });
        return {
          contentItems: [{ type: 'inputText', text: 'Dynamic tool is unavailable.' }],
          success: false,
        } satisfies DynamicToolCallResponse;
      }
      try {
        return await handlers.dynamicToolCall(params, { requestId: meta.id });
      } catch (e) {
        this.logger.error('dynamicToolCall handler threw -> failed result', {
          threadId: params.threadId,
          callId: params.callId,
          tool: params.tool,
          message: (e as Error).message,
        });
        return {
          contentItems: [{ type: 'inputText', text: (e as Error).message || 'Dynamic tool failed.' }],
          success: false,
        } satisfies DynamicToolCallResponse;
      }
    });

    // start() = create transport + wire onLine/onStderr/onClose. 必须在所有
    // onNotification/setRequestHandler 之后, 在 initialize() 之前。等价于原版
    // 的 client.spawnProcess()。
    client.start();

    const mergedCapabilities: InitializeCapabilities = {
      experimentalApi: true,
      optOutNotificationMethods: NOTIFICATIONS_TO_OPT_OUT,
      ...capabilities,
    };
    let resp: InitializeResponse;
    try {
      resp = await client.initialize(this.opts.clientInfo, mergedCapabilities);
    } catch (error) {
      if (!client.nativeSqliteInitializationFailed()) throw error;
      // No task/config/authentication RPC has been submitted. The transport
      // proves natural exit; still use the existing strict close barrier.
      await client.close({ reason: 'native SQLite initialization failed', throwOnTransportError: true });
      if (nativeAttempt >= 2 || nativeEpoch !== this.nativeInitializationEpoch
        || this.retired || this.shuttingDown || this.client !== client) {
        throw new CodexNativeInitializationStoppedError('Codex native SQLite initialization stopped', { cause: error });
      }
      this.logger.warn('retrying exited native SQLite initialization', { attempt: nativeAttempt + 2, maxAttempts: 3 });
      return this.bootstrap(capabilities, nativeAttempt + 1, nativeEpoch);
    }
    if (this.opts.requireEphemeralAuth || this.externalAuth) {
      // Requirements can override CLI configuration. Reject before any task RPC
      // or token installation; initialization has already loaded native config.
      await assertCodexEphemeralAuth((method, params) => client.request(method, params, { timeoutMs: 10_000 }));
    }
    if (this.externalAuth) {
      await this.externalAuth.authenticate((method, params) => client.request(method, params, { timeoutMs: 10_000 }));
      if (this.client !== client || this.shuttingDown || this.retired) {
        throw new Error('Codex account authentication host has retired');
      }
    }
    this.logger.info('shared app-server up', {
      userAgent: resp.userAgent,
      codexHome: resp.codexHome,
      platformOs: resp.platformOs,
    });
    return resp;
  }

  /**
   * 透传 JSON-RPC request 到底层 client (会先 ensureStarted)。
   * thread/start / turn/start / turn/interrupt / thread/resume / thread/fork 都走这里。
   *
   * `opts.timeoutMs` 按需传入: 裸 RPC 默认**无超时** (协议上 response 可能任意晚),
   * 但 turn/start 这类「daemon 失联就永远挂住」的关键路径应显式给上限 —
   * 超时 reject 后上层按 turn 启动失败收口, 而不是让 UI 无限 generating。
   * `extendWhileProgress` 只顺延请求本身的等待, startup 仍按 timeoutMs 计。
   */
  async request<R = unknown>(
    method: string,
    params?: unknown,
    opts?: { timeoutMs?: number; beforeDispatch?: () => void; extendWhileProgress?: RequestProgressDeadline },
  ): Promise<R> {
    // 冷启动 / transport 重建时 ensureStarted 本身也可能永不返回 (远端 daemon
    // bootstrap 挂死 / SSH 通道无响应) — 调用方显式给 timeoutMs 时同样给它
    // 上界, 否则「关键 RPC 加超时」在启动路径上形同虚设 (greptile R6 P1)。
    // timeoutMs 是 startup + request 的整体 deadline (copilot R9): startup 用掉
    // 的预算从 request 里扣, 否则最坏等 2× timeoutMs, 与「关键 RPC 60s 上界」
    // 的意图冲突, UI 仍可能长时间卡 generating。
    const started = this.ensureStarted();
    if (opts?.timeoutMs != null) {
      const deadline = Date.now() + opts.timeoutMs;
      let timer: NodeJS.Timeout | null = null;
      try {
        await Promise.race([
          started,
          new Promise<never>((_, reject) => {
            timer = setTimeout(() => {
              this.nativeInitializationEpoch++;
              reject(new Error(`app-server startup (for ${method}) timed out after ${opts.timeoutMs}ms`));
            }, opts.timeoutMs);
            timer.unref?.();
          }),
        ]);
      } catch (err) {
        // 超时后 started 仍在后台继续 (下次 request 可直接复用) — 挂一个
        // swallow catch 防它迟到 reject 时变成 unhandled rejection。
        started.catch(() => { /* late startup failure swallowed after timeout */ });
        throw err;
      } finally {
        if (timer) clearTimeout(timer);
      }
      const remaining = deadline - Date.now();
      if (remaining <= 0) {
        throw new Error(`app-server startup (for ${method}) consumed the entire ${opts.timeoutMs}ms timeout budget`);
      }
      if (!this.client) throw new Error('AppServerHost: client missing after ensureStarted (unreachable)');
      opts?.beforeDispatch?.();
      if (method !== 'thread/loaded/list') this.writerCandidates.add(this.client);
      return this.client.request<R>(method, params, { ...opts, timeoutMs: remaining });
    }
    await started;
    if (!this.client) throw new Error('AppServerHost: client missing after ensureStarted (unreachable)');
    opts?.beforeDispatch?.();
    if (method !== 'thread/loaded/list') this.writerCandidates.add(this.client);
    return this.client.request<R>(method, params, opts);
  }

  /** Release one thread's live runtime without archiving or deleting its history. */
  async unsubscribeThread(threadId: string): Promise<void> {
    const client = this.client;
    if (!client) return;
    await client.request<ThreadUnsubscribeResponse>(
      Method.ThreadUnsubscribe,
      { threadId },
      { timeoutMs: this.threadUnsubscribeTimeoutMs },
    );
  }

  /**
   * 强制关停 (app.before-quit / 测试 cleanup / transport error 恢复)。幂等。
   * 清空 subscribers + close client (杀子进程)。**结束后允许 ensureStarted 重新 spawn**
   * (场景: 子进程崩溃后下一个 session 进来自动起一个新的)。
   *
   * **必须** 在 app.before-quit 显式调一次 — Windows 子进程不会随父进程死,
   * 不显式收割就成孤儿。
   */
  async shutdown(
    reason = 'AppServerHost.shutdown()',
    opts?: { throwOnTransportError?: boolean },
  ): Promise<void> {
    this.nativeInitializationEpoch++;
    if (!this.shutdownPromise) {
      this.shuttingDown = true;
      const client = this.client;
      const shutdownPromise = Promise.resolve().then(async () => {
        await client?.close({ reason, throwOnTransportError: true });
        if (this.client === client) this.client = null;
        // start() 的同步 transport 回调可能在 ensureStarted 赋值前触发关闭。
        this.startPromise = null;
        // 只在关闭成功后开放重启;失败保留 barrier,避免新旧 writer 并存。
        this.shutdownPromise = null;
        this.shuttingDown = false;
      }).catch((error) => {
        // 本次结果可以重查,但 client 与 shuttingDown 保留到真实关闭成功。
        if (this.shutdownPromise === shutdownPromise) this.shutdownPromise = null;
        throw error;
      });
      this.shutdownPromise = shutdownPromise;
      this.startPromise = null;
      // MCP readiness belongs to the concrete app-server process.
      this.mcpToolAvailability.clear();
      this.subscribers.clear();
      this.lineageRoots.clear();
      this.pendingLineage.clear();
      this.buffered.clear();
      for (const threadId of this.threadHandlerWaiters.keys()) {
        this.notifyThreadHandlerWaiters(threadId);
      }
    }
    try {
      await this.shutdownPromise;
    } catch (error) {
      if (opts?.throwOnTransportError) throw error;
    }
  }

  /**
   * 终态关停。凭据/账号切换后旧 host 不能再被旧 session 闭包重新拉起;
   * transport error 自愈仍走普通 shutdown(),保留同对象重启能力。
   */
  async retire(
    reason = 'AppServerHost.retire()',
    opts?: { throwOnTransportError?: boolean },
  ): Promise<void> {
    this.retired = true;
    if (!this.retirementPromise) {
      const retirementPromise = Promise.resolve().then(async () => {
        await this.shutdown(reason, { throwOnTransportError: true });
        await Promise.resolve()
          .then(() => this.opts.onRetired?.())
          .catch((error) => {
            this.logger.warn('app-server Host retirement cleanup failed', {
              error: error instanceof Error ? error.message : String(error),
            });
          });
      }).catch((error) => {
        if (this.retirementPromise === retirementPromise) this.retirementPromise = null;
        throw error;
      });
      this.retirementPromise = retirementPromise;
    }
    try {
      await this.retirementPromise;
    } catch (error) {
      if (opts?.throwOnTransportError) throw error;
    }
  }

  /**
   * 强制收割前通知订阅者(结构化生命周期信号)。
   *
   * retire()/shutdown() 会静默清空 subscribers —— 常规路径(凭证切换/app 退出)由
   * 上层先 Session.close 收尾,这是对的;但 auth 失效等强制路径会带着 in-flight turn
   * 直接收割 host,不先叫醒订阅者的话,session 的 isTurnRunning 永远不翻 false,上层
   * 的输入队列 / Stop 的 queueAbortPending 锁 / 凭证切换 busy 判定全部永久卡死
   * (2026-07-19 实排:auth app_session_terminated 触发 retire 后会话假 busy 数小时)。
   * 只广播、不清订阅 —— 紧随其后的 retire() 负责清理。
   *
   * 但**不能**对每个订阅者广播 transport error:空闲/已完成的订阅者(没有 in-flight
   * turn,例如闲置数小时的已完成会话)收到终态 error 后会被写入永久红框,而它并没有
   * 任何真实工作被中断——这只是一次内部 host 替换(#1391 场景)。而真实在飞的
   * turn/start pending / overload retry 订阅者若只收到**空 turnId** 的 transport
   * error,现有 error handler 的 `targetsPendingTurn`(要求非空 turnId)与
   * `wasTurnRunning`(不含 overload retry)无法把它收口,busy 状态会永久卡死。
   *
   * 因此改为发送结构化 `hostForcedRetire` 信号,由每个订阅者按自身完整状态收口
   * (空闲→静默失效;在飞→终态 error + Done)。未提供该回调的订阅者退回旧行为
   * (广播 transport error),保证兼容。
   */
  notifySubscribersOfForcedRetire(reason: string): void {
    if (this.subscribers.size === 0) return;
    let notified = 0;
    let fellBack = 0;
    for (const [threadId, handlers] of this.subscribers) {
      if (handlers.hostForcedRetire) {
        notified += 1;
        try {
          handlers.hostForcedRetire({ reason });
          continue;
        } catch (e) {
          // handler 抛错 → 该订阅者收不到结构化信号, 强退场景最需要兜底:
          // 回退到旧 transport-error 广播, 至少保证有一条终态错误触发收口,
          // 否则 busy 永久卡死 (copilot review on #1720)。
          this.logger.warn('forced retire handler threw — falling back to transport error', {
            threadId,
            message: (e as Error).message,
          });
        }
      }
      // 旧订阅者(未接 hostForcedRetire)保持旧行为:广播 transport error。
      fellBack += 1;
      try {
        handlers.error?.({
          threadId,
          turnId: '',
          willRetry: false,
          scope: 'transport',
          error: { message: `app-server force-retired: ${reason}` },
        });
      } catch (e) {
        this.logger.warn('forced retire broadcast handler threw', {
          threadId,
          message: (e as Error).message,
        });
      }
    }
    this.logger.warn('forced retire with live subscribers — notifying session lifecycles', {
      subscribers: this.subscribers.size,
      notified,
      fellBack,
      reason,
    });
  }

  // ── 订阅 / 路由 ───────────────────────────────────────────────────────────

  /**
   * 为 thread_id 注册一组 handler。release() 先移除本地路由,再通知 app-server
   * 解除这个 thread 的 live subscription;rollout/history 不会被 archive 或 delete。
   * 如果 thread/started (或更早的 notification) 在 subscribe 之前就到了, drain
   * buffered 队列里匹配的项, 按到达顺序 dispatch — 保证不丢事件。
   *
 * 不做 refcount → shutdown:共享 server 仍只跟 host.shutdown() 绑定。这里仅释放
 * 已关闭 session 对应的 thread state,避免它继续持有 MCP/app-server 子进程资源。
   */
  subscribeThread(threadId: string, handlers: ThreadEventHandlers): ThreadSubscription {
    if (this.retired) {
      throw new Error(`AppServerHost.subscribeThread(${threadId}) after retirement`);
    }
    if (this.shuttingDown) {
      throw new Error(`AppServerHost.subscribeThread(${threadId}) during shutdown`);
    }
    if (this.subscribers.has(threadId)) {
      this.logger.warn('overwriting thread subscription', { threadId });
    }
    if (this.client) this.writerCandidates.add(this.client);
    this.subscribers.set(threadId, handlers);
    this.lineageRoots.set(threadId, threadId);
    this.notifyThreadHandlerWaiters(threadId);

    // 排空缓存 (thread/started 比 subscribe 早到的固有竞争)
    const buf = this.buffered.get(threadId);
    if (buf) {
      this.buffered.delete(threadId);
      for (const item of buf) {
        this.dispatchToHandlers(handlers, item.method, item.params);
      }
    }
    this.replayBufferedDescendantThreadStarts(threadId);

    // 账号配额 snapshot replay — 让新 session 立即看到当前账号配额, 不必等下次 turn。
    if ((this.lastAccountRateLimits.size > 0 || this.lastIdlessAccountRateLimits) && handlers.accountRateLimitsUpdated) {
      // 按 limitId 各回放最新一份: 去重后不变的快照不会再被推送, 只回放一条会让新会话缺其余 limit。
      try {
        for (const snapshot of this.lastAccountRateLimits.values()) {
          handlers.accountRateLimitsUpdated(snapshot);
        }
        if (this.lastIdlessAccountRateLimits) handlers.accountRateLimitsUpdated(this.lastIdlessAccountRateLimits);
      } catch (e) {
        this.logger.error('accountRateLimitsUpdated replay threw', { message: (e as Error).message });
      }
    }

    let localReleased = false;
    let serverReleased = false;
    let releasePromise: Promise<void> | null = null;
    return {
      release: () => {
        if (serverReleased) return Promise.resolve();
        if (releasePromise) return releasePromise;

        if (!localReleased) {
          const cur = this.subscribers.get(threadId);
          // A later subscription for the same thread owns the live server state now.
          if (cur !== handlers) {
            serverReleased = true;
            return Promise.resolve();
          }
          this.subscribers.delete(threadId);
          this.deleteLineageForRoot(threadId);
          this.buffered.delete(threadId);
          localReleased = true;
        } else if (this.subscribers.has(threadId)) {
          // A retry must not unsubscribe a newer local owner for the same thread.
          serverReleased = true;
          return Promise.resolve();
        }

        releasePromise = this.unsubscribeThread(threadId)
          .then(() => {
            serverReleased = true;
          })
          .finally(() => {
            releasePromise = null;
          });
        return releasePromise;
      },
    };
  }

  // ── 内部 ─────────────────────────────────────────────────────────────────

  private routeNotification(method: string, params: unknown): void {
    // 账号级 notification — 没有 threadId, 走全局 fan-out 路径:
    // 缓存最近 snapshot (给新 subscribe replay) + 广播给所有 active subscriber 各一份。
    if (method === 'account/rateLimits/updated') {
      const p = params as AccountRateLimitsUpdatedNotification['params'];
      // replay 快照始终跟随最新一条 (哪怕内容未变), 新 subscriber 拿到的与旧行为一致。
      const limitKey = p.rateLimits?.limitId;
      const rawJson = JSON.stringify(p.rateLimits ?? null);
      if (limitKey) {
        // 删后再插, 让 Map 顺序反映最近观察顺序; 带 limitId 的更新使稀疏更新的回放作废。
        this.lastAccountRateLimits.delete(limitKey);
        this.lastAccountRateLimits.set(limitKey, p);
        this.lastIdlessAccountRateLimits = null;
      } else {
        this.lastIdlessAccountRateLimits = p;
      }
      // 只丢弃与上一条已广播更新完全相同的连续重复: 它不改变「最近观察的 bucket」, 下游
      // (usageBroadcaster) 依赖这个顺序把稀疏更新合并进正确的 bucket; A,B,A 中最后的 A 不能丢。
      const fanOutKey = `${limitKey ?? ''}\u0000${rawJson}`;
      if (this.lastFannedOutRateLimitsKey === fanOutKey) return;
      this.lastFannedOutRateLimitsKey = fanOutKey;
      this.logger.debug('accountRateLimits fan-out', {
        subscribers: this.subscribers.size,
        rawJson,
      });
      for (const handlers of this.subscribers.values()) {
        try {
          handlers.accountRateLimitsUpdated?.(p);
        } catch (e) {
          this.logger.error('accountRateLimitsUpdated handler threw', { message: (e as Error).message });
        }
      }
      return;
    }

    const threadId = extractThreadId(method, params);
    if (!threadId) {
      if (method === 'turn/plan/updated') {
        // Older app-server protocol snapshots do not carry threadId for plan updates.
        // Fan-out is best-effort and relies on downstream turnId filtering; newer
        // protocol events should include threadId so dispatch remains session-scoped.
        this.logger.debug('plan update without threadId; fan-out to subscribers', {
          subscribers: this.subscribers.size,
        });
        for (const handlers of this.subscribers.values()) {
          this.dispatchToHandlers(handlers, method, params);
        }
        return;
      }
      // Process-level warnings (config / feature notices) have no thread to route to.
      if (method === 'warning') return;
      this.logger.warn('notification missing threadId', { method });
      return;
    }
    if (method === 'thread/started') {
      this.routeDescendantThreadStarted(params as ThreadStartedNotification['params']);
    }
    const handlers = this.subscribers.get(threadId);
    if (handlers) {
      this.dispatchToHandlers(handlers, method, params);
      return;
    }
    // 已知的子线程(子代理):app-server 对连接内所有 loaded thread 主动推送,过滤全在
    // 本地。此前这里只按 subscribers 精确匹配,子线程的 item/tokenUsage/turn 事件因此
    // 全部落进 TTL 缓冲后被丢弃 —— 子代理在 UI 上没有任何实时状态。改为按 lineage 归到
    // root 的独立 descendant 通道(不进主线程 dispatch,见 descendantNotification 注释)。
    // thread/started 不进这条通道:它已由上面的 routeDescendantThreadStarted 经专用的
    // descendantThreadStarted handler 投递过。两条通道送同一事件会诱发重复处理,且
    // 它仍需按原样落缓冲 —— replayBufferedDescendantThreadStarts 靠子线程 id 下的
    // 缓冲项重建迟到订阅的孙线程血缘。
    const rootThreadId = method === 'thread/started' ? undefined : this.lineageRoots.get(threadId);
    if (rootThreadId && rootThreadId !== threadId) {
      const rootHandlers = this.subscribers.get(rootThreadId);
      if (rootHandlers?.descendantNotification) {
        try {
          rootHandlers.descendantNotification(threadId, method, params);
        } catch (e) {
          this.logger.error('descendant notification handler threw', {
            rootThreadId,
            childThreadId: threadId,
            method,
            message: (e as Error).message,
          });
        }
      }
      // 血缘已知就地收口:root 不消费时直接丢弃,不进缓冲(缓冲只为解 subscribe 竞争,
      // 子线程 id 永远不会被 subscribe,堆在那里只会等 TTL 到点白白清一遍)。
      return;
    }
    // subscribe 还没到 — 暂存 + TTL 清理。Codex 协议保证 server 内同 thread 顺序,
    // drain 时按到达顺序 dispatch 不会乱。
    this.bufferNotification(threadId, method, params);
  }

  /**
   * Server requests from descendant threads must use the root subscription's
   * handlers, just like descendant notifications. The app-server only knows
   * the concrete child thread id, while approvals / elicitation / dynamic
   * tool callbacks belong to the Cindy session that owns the root thread.
   */
  private handlersForThread(threadId: string): ThreadEventHandlers | undefined {
    const rootThreadId = this.lineageRoots.get(threadId)
      ?? (this.subscribers.has(threadId) ? threadId : null);
    return rootThreadId ? this.subscribers.get(rootThreadId) : undefined;
  }

  private resolveRequestHandlers(
    threadId: string,
  ): ThreadEventHandlers | Promise<ThreadEventHandlers | undefined> | undefined {
    const current = this.handlersForThread(threadId);
    // Keep known root/descendant dispatch synchronous. requestUserInput and
    // dynamicToolCall register their broker entry in the first synchronous
    // statements; yielding here would let a same-turn serverRequest/resolved
    // notification cancel the request before that registration (Codex P1).
    if (current || this.subscribers.size === 0) return current;
    return this.waitForThreadHandlers(threadId);
  }

  /**
   * 血缘边登记的共享核心:解析 root、幂等去重、写入 lineageRoots。
   * null = 无法归属(参数非法 / root 不在 / handlers 已释放)。能归属时一定返回
   * root 与 handlers;`establishedNewEdge` 区分本次是否真的落了新边——重复登记
   * (spawn 路径已建边后新版 codex 补发 thread/started)不再落表,但调用方仍拿得到
   * handlers 去转发 thread 元数据(model 等),不能把重复当成完全的 no-op 吞掉。
   * 新边落表后唤醒该子线程上等待血缘的 server request(见 waitForThreadHandlers):
   * spawn 登记与 thread/started 两条路径都可能是 waiter 等的那次解析。
   */
  private establishDescendantLineage(
    childThreadId: string,
    parentThreadId: string,
  ): {
    rootThreadId: string;
    handlers: ThreadEventHandlers;
    establishedNewEdge: boolean;
    releasedRequestWaiters: boolean;
  } | null {
    if (!childThreadId || !parentThreadId || parentThreadId === childThreadId) return null;
    const rootThreadId = this.lineageRoots.get(parentThreadId)
      ?? (this.subscribers.has(parentThreadId) ? parentThreadId : null);
    if (!rootThreadId || childThreadId === rootThreadId) return null;

    const handlers = this.subscribers.get(rootThreadId);
    if (!handlers) return null;

    if (this.lineageRoots.get(childThreadId) === rootThreadId) {
      return {
        rootThreadId,
        handlers,
        establishedNewEdge: false,
        releasedRequestWaiters: false,
      };
    }

    this.lineageRoots.set(childThreadId, rootThreadId);
    const releasedRequestWaiters = this.notifyThreadHandlerWaiters(childThreadId);
    return { rootThreadId, handlers, establishedNewEdge: true, releasedRequestWaiters };
  }

  /**
   * 保留一条待确认的 spawn 血缘,但不安装 root 路由。
   *
   * 这是 turn reconciliation 之前的 provisional 状态:child notification 会继续
   * 留在 child 自己的缓冲里,child server request 会等待;只有父 turn 被确认后,
   * registerDescendantLineage 才会把它变成 live route。重复 reserve 幂等。
   */
  reserveDescendantLineage(childThreadId: string, parentThreadId: string): void {
    if (!childThreadId || !parentThreadId || childThreadId === parentThreadId) return;
    if (this.lineageRoots.has(childThreadId)) return;
    const rootThreadId = this.lineageRoots.get(parentThreadId)
      ?? (this.subscribers.has(parentThreadId) ? parentThreadId : null);
    if (!rootThreadId || !this.subscribers.has(rootThreadId)) return;
    const existing = this.pendingLineage.get(childThreadId);
    if (existing) {
      if (existing.parentThreadId !== parentThreadId || existing.rootThreadId !== rootThreadId) {
        this.logger.warn('ignoring conflicting pending descendant lineage', {
          childThreadId,
          parentThreadId,
          existing,
        });
      }
      return;
    }
    this.pendingLineage.set(childThreadId, { parentThreadId, rootThreadId });
  }

  /**
   * 丢弃尚未 commit 的 spawn 血缘:清掉 child 缓冲并唤醒请求 waiter 走 fail-closed。
   * parentThreadId 可选,用于防止迟到/重复的旧 turn 清掉新 claim。
   */
  discardPendingDescendantLineage(childThreadId: string, parentThreadId?: string): void {
    const pending = this.pendingLineage.get(childThreadId);
    if (!pending || (parentThreadId && pending.parentThreadId !== parentThreadId)) return;
    this.pendingLineage.delete(childThreadId);
    this.buffered.delete(childThreadId);
    this.notifyThreadHandlerWaiters(childThreadId);
  }

  /**
   * Cindy 侧主动登记「子线程 → 父线程」血缘(spawn item 是唯一可靠来源)。
   *
   * codex 0.145 会把 spawn 出的子线程自动 attach 到本连接并转发它的
   * item / tokenUsage / turn 通知,但 `thread/started` 只在显式 thread/start /
   * fork RPC 时发,**内部 spawn 的子线程从来不发**(codex-rs
   * `thread_processor.rs` 仅两处 emit)。只等 thread/started 建血缘,子线程的全部
   * 通知都会在 TTL 缓冲里静默过期:子代理卡没有任何实时数据、终态永远不到,
   * 卡片停在 spawn 时的 running 帧永久转圈;子线程的 approval 请求也会因
   * handlersForThread 查不到 root 而被自动 decline(2026-08-04 生产实测)。
   *
   * 调用方(codex session)从 spawn item 的 agentThreadId / receiverThreadIds
   * 拿到子线程 id 后立即登记。幂等:更新版 codex 若补发 thread/started,
   * routeDescendantThreadStarted 只跳过重复建边与缓冲重放,thread 元数据
   * (model 等)仍会照常转发给订阅者。
   */
  registerDescendantLineage(childThreadId: string, parentThreadId: string): void {
    const pending = this.pendingLineage.get(childThreadId);
    if (pending && pending.parentThreadId !== parentThreadId) {
      this.logger.warn('ignoring descendant lineage commit for a conflicting pending claim', {
        childThreadId,
        parentThreadId,
        pending,
      });
      return;
    }
    if (pending && pending.parentThreadId === parentThreadId) {
      this.pendingLineage.delete(childThreadId);
    }
    const established = this.establishDescendantLineage(childThreadId, parentThreadId);
    if (!established) {
      if (pending?.parentThreadId === parentThreadId) {
        this.buffered.delete(childThreadId);
        this.notifyThreadHandlerWaiters(childThreadId);
      }
      return;
    }
    if (!established.establishedNewEdge) return;
    const replayBufferedNotifications = (): void => {
      // `thread/started` may already be buffered under this child id when the
      // root subscription replays a spawn item and establishes lineage late.
      // Preserve and forward that metadata (notably thread.model) before the
      // ordinary descendant drain deletes the whole buffer and skips starts.
      this.replayBufferedThreadStarts(childThreadId);
      // 子线程在登记前已到达的通知缓存在它自己的 id 下,补投进 descendant 通道;
      // 它名下若已缓冲了孙线程的 thread/started,一并重建整条血缘链。
      this.drainBufferedDescendantNotifications(childThreadId, established.rootThreadId, established.handlers);
      this.replayBufferedDescendantThreadStarts(established.rootThreadId);
    };
    // Resolving a lineage waiter schedules the server-request handler's await
    // continuation. Let that continuation register its broker entry before a
    // buffered serverRequest/resolved notification is replayed; otherwise the
    // cancellation is lost and a request the server already closed reaches UI.
    if (established.releasedRequestWaiters) queueMicrotask(replayBufferedNotifications);
    else replayBufferedNotifications();
  }

  /**
   * Give an already-owned descendant a short window for its thread/started
   * notification to establish lineage. This closes an observed ordering race
   * for node_repl elicitation while preserving fail-closed routing: unknown
   * threads still decline after the bounded wait and can never fan out to an
   * arbitrary subscriber.
   */
  private waitForThreadHandlers(threadId: string): Promise<ThreadEventHandlers | undefined> {
    const current = this.handlersForThread(threadId);
    if (current) return Promise.resolve(current);
    return new Promise((resolve) => {
      let settled = false;
      let timer: NodeJS.Timeout | null = null;
      const finish = (): void => {
        if (settled) return;
        const handlers = this.handlersForThread(threadId);
        // A reserved spawn may legitimately outlive the normal notification TTL while
        // the parent turn is being reconciled. Keep waiting until commit/discard settles
        // it; unknown threads still use the bounded fail-closed window below.
        if (!handlers && this.pendingLineage.has(threadId) && !this.shuttingDown) {
          timer = setTimeout(finish, this.bufferTtlMs);
          timer.unref?.();
          return;
        }
        settled = true;
        if (timer) clearTimeout(timer);
        const waiters = this.threadHandlerWaiters.get(threadId);
        waiters?.delete(finish);
        if (waiters?.size === 0) this.threadHandlerWaiters.delete(threadId);
        resolve(handlers);
      };
      // Use the same bounded lineage window as early thread notifications.
      // Both races are caused by thread/started crossing the subscribe/request
      // boundary, so they should expire together instead of using a shorter
      // empirical timeout that can fail only under load.
      timer = setTimeout(finish, this.bufferTtlMs);
      timer.unref?.();
      const waiters = this.threadHandlerWaiters.get(threadId) ?? new Set<() => void>();
      waiters.add(finish);
      this.threadHandlerWaiters.set(threadId, waiters);
    });
  }

  private notifyThreadHandlerWaiters(threadId: string): boolean {
    const waiters = [...(this.threadHandlerWaiters.get(threadId) ?? [])];
    for (const finish of waiters) finish();
    return waiters.length > 0;
  }

  private routeDescendantThreadStarted(params: ThreadStartedNotification['params']): void {
    const childThreadId = params.thread.id;
    const parentThreadId = params.thread.parentThreadId;
    if (!parentThreadId) return;
    // A provisional spawn claim owns this child until parent turn reconciliation. Do not let
    // an early thread/started install a live root route for a turn that may later be orphaned.
    if (this.pendingLineage.has(childThreadId)) return;
    const established = this.establishDescendantLineage(childThreadId, parentThreadId);
    if (!established) return;
    const { rootThreadId, handlers, establishedNewEdge, releasedRequestWaiters } = established;
    // 血缘重复(spawn 路径已建边)也要转发:thread/started 是 thread.model 等实际
    // 元数据的唯一载体,吞掉它会让「实际线程模型优先」永远等不到观测值(codex review)。
    if (handlers.descendantThreadStarted) {
      try {
        handlers.descendantThreadStarted(params);
      } catch (e) {
        this.logger.error('descendant thread handler threw', {
          rootThreadId,
          parentThreadId,
          childThreadId,
          message: (e as Error).message,
        });
      }
    }
    // 重复建边只补元数据转发:缓冲早已在首次建边时排空,重放在这里只会空转。
    if (!establishedNewEdge) return;
    const replayBufferedNotifications = (): void => {
      // 血缘刚建立:该子线程在此之前到达的 item / tokenUsage / turn 通知都缓存在**它自己的
      // id** 下(那时既不是 subscriber 也没有 lineage)。root 侧的 drain 只排空 root id 的队列,
      // 这些永远排不到 → 早期工具数、token 丢失,漏掉 turn/completed 还会让卡片永久停在
      // running(codex review)。这里按到达顺序补投进 descendant 通道。
      this.drainBufferedDescendantNotifications(childThreadId, rootThreadId, handlers);
      // 本次血缘建立可能解锁**孙**线程:孙的 thread/started 缓存在它自己的 id 下,上面的 drain
      // 只排空 childThreadId 的队列,而且它按契约会跳过 thread/started —— 不再扫一遍,孙线程的
      // 血缘永远建不起来,它的 tool / token / 终态通知会一直烂在缓冲区直到过期(卡片漏计,并
      // 可能一直显示运行中或提前完成)(review)。复用 root 订阅时那套迭代重建。
      this.replayBufferedDescendantThreadStarts(rootThreadId);
    };
    if (releasedRequestWaiters) queueMicrotask(replayBufferedNotifications);
    else replayBufferedNotifications();
  }

  /**
   * 把某子线程在血缘建立前缓存的通知按原顺序补投给 root 的 descendant 通道。
   * `thread/started` 跳过 —— 它已由 routeDescendantThreadStarted 经专用 handler 投递过,
   * 而且 descendantNotification 的契约里不含它。
   */
  private drainBufferedDescendantNotifications(
    childThreadId: string,
    rootThreadId: string,
    handlers: ThreadEventHandlers,
  ): void {
    const buffered = this.buffered.get(childThreadId);
    if (!buffered) return;
    // 先删再投:补投过程中若又触发别的血缘重建,不会把同一批重复投一遍。
    this.buffered.delete(childThreadId);
    if (!handlers.descendantNotification) return;
    for (const item of buffered) {
      if (item.method === 'thread/started') continue;
      try {
        handlers.descendantNotification(childThreadId, item.method, item.params);
      } catch (e) {
        this.logger.error('buffered descendant notification handler threw', {
          rootThreadId,
          childThreadId,
          method: item.method,
          message: (e as Error).message,
        });
      }
    }
  }

  /**
   * Forward buffered starts for one thread without consuming its buffer.
   * The following ordinary drain owns deletion and skips these entries, so
   * starts are delivered exactly once and ahead of item/usage/turn replay.
   */
  private replayBufferedThreadStarts(threadId: string): void {
    const buffered = this.buffered.get(threadId);
    if (!buffered) return;
    for (const item of buffered) {
      if (item.method !== 'thread/started') continue;
      this.routeDescendantThreadStarted(item.params as ThreadStartedNotification['params']);
    }
  }

  private replayBufferedDescendantThreadStarts(rootThreadId: string): void {
    // 重入保护:本方法会调用 routeDescendantThreadStarted,而后者现在又会回调本方法。
    // 嵌套再扫一遍是纯重复劳动(外层的 for(;;) 本来就会继续迭代直到没有新发现),
    // 深血缘下还会退化成 O(深度²)。让嵌套调用直接返回,由最外层那次跑完。
    if (this.replayingDescendantLineage) return;
    this.replayingDescendantLineage = true;
    try {
      this.replayBufferedDescendantThreadStartsInner(rootThreadId);
    } finally {
      this.replayingDescendantLineage = false;
    }
  }

  private replayBufferedDescendantThreadStartsInner(rootThreadId: string): void {
    // thread/started is buffered under the child id. A root subscription therefore
    // cannot drain those entries directly; rebuild the lineage iteratively so an
    // already-buffered child can unlock an already-buffered grandchild as well.
    for (;;) {
      // 先快照本轮的候选再处理:routeDescendantThreadStarted 现在会把该 child 的缓冲队列
      // 排空并**从 this.buffered 删除**,边迭代边删同一个 Map 容易漏项。
      const candidates: ThreadStartedNotification['params'][] = [];
      for (const notifications of this.buffered.values()) {
        for (const item of notifications) {
          if (item.method !== 'thread/started') continue;
          candidates.push(item.params as ThreadStartedNotification['params']);
        }
      }
      let discovered = 0;
      for (const params of candidates) {
        const childThreadId = params.thread?.id;
        const parentThreadId = params.thread?.parentThreadId;
        if (
          !childThreadId
          || !parentThreadId
          || this.lineageRoots.has(childThreadId)
          || this.lineageRoots.get(parentThreadId) !== rootThreadId
        ) continue;
        this.routeDescendantThreadStarted(params);
        if (this.lineageRoots.get(childThreadId) === rootThreadId) discovered += 1;
      }
      if (discovered === 0) return;
    }
  }

  private deleteLineageForRoot(rootThreadId: string): void {
    for (const [threadId, ownerRootThreadId] of this.lineageRoots) {
      if (ownerRootThreadId === rootThreadId) {
        this.lineageRoots.delete(threadId);
      }
    }
    for (const [threadId, pending] of this.pendingLineage) {
      if (pending.rootThreadId === rootThreadId) {
        this.pendingLineage.delete(threadId);
        this.buffered.delete(threadId);
        this.notifyThreadHandlerWaiters(threadId);
      }
    }
  }

  private dispatchToHandlers(handlers: ThreadEventHandlers, method: string, params: unknown): void {
    let fn: ((p: never) => void) | undefined;
    switch (method) {
      case 'thread/started': fn = handlers.threadStarted as (p: never) => void; break;
      case 'turn/started': fn = handlers.turnStarted as (p: never) => void; break;
      case 'turn/completed': fn = handlers.turnCompleted as (p: never) => void; break;
      case 'turn/diff/updated': fn = handlers.turnDiffUpdated as (p: never) => void; break;
      case 'thread/tokenUsage/updated': fn = handlers.tokenUsageUpdated as (p: never) => void; break;
      case 'item/started': fn = handlers.itemStarted as (p: never) => void; break;
      case 'item/updated': fn = handlers.itemUpdated as (p: never) => void; break;
      case 'item/completed': fn = handlers.itemCompleted as (p: never) => void; break;
      case 'item/agentMessage/delta': fn = handlers.agentMessageDelta as (p: never) => void; break;
      case 'turn/plan/updated': fn = handlers.turnPlanUpdated as (p: never) => void; break;
      case 'item/reasoning/summaryTextDelta': fn = handlers.reasoningSummaryTextDelta as (p: never) => void; break;
      case 'item/reasoning/summaryPartAdded': fn = handlers.reasoningSummaryPartAdded as (p: never) => void; break;
      case 'item/reasoning/textDelta': fn = handlers.reasoningTextDelta as (p: never) => void; break;
      case 'account/rateLimits/updated': fn = handlers.accountRateLimitsUpdated as (p: never) => void; break;
      case 'thread/status/changed': fn = handlers.threadStatusChanged as (p: never) => void; break;
      case 'thread/settings/updated': fn = handlers.threadSettingsUpdated as (p: never) => void; break;
      case 'serverRequest/resolved': fn = handlers.serverRequestResolved as (p: never) => void; break;
      case 'item/autoApprovalReview/started': fn = handlers.autoApprovalReviewStarted as (p: never) => void; break;
      case 'item/autoApprovalReview/completed': fn = handlers.autoApprovalReviewCompleted as (p: never) => void; break;
      case 'guardianWarning': fn = handlers.guardianWarning as (p: never) => void; break;
      case 'warning': fn = handlers.warning as (p: never) => void; break;
      case 'error': fn = handlers.error as (p: never) => void; break;
    }
    if (!fn) {
      this.logger.debug('subscriber has no handler for method', { method });
      return;
    }
    try {
      fn(params as never);
    } catch (e) {
      this.logger.error('thread handler threw', { method, message: (e as Error).message });
    }
  }

  private bufferNotification(threadId: string, method: string, params: unknown): void {
    const arr = this.buffered.get(threadId) ?? [];
    arr.push({ method, params, ts: Date.now() });
    this.buffered.set(threadId, arr);
    setTimeout(() => {
      const cur = this.buffered.get(threadId);
      if (!cur) return;
      // A provisional spawn claim owns this buffer until parent turn reconciliation;
      // do not expire the child lifecycle/terminal events just because the normal TTL elapsed.
      // commit/discard removes it explicitly.
      if (this.pendingLineage.has(threadId)) return;
      const cutoff = Date.now() - this.bufferTtlMs;
      const remaining = cur.filter((x) => x.ts > cutoff);
      if (remaining.length === 0) {
        this.buffered.delete(threadId);
      } else {
        this.buffered.set(threadId, remaining);
      }
    }, this.bufferTtlMs).unref?.();
  }

  /**
   * 子进程 crash / IO 错误: 将所有 subscriber 作为 host 强制退役处理,让每个
   * session 按自己的真实状态收口(空闲静默结束 event queue,在飞任务发终态
   * error + Done),然后强制 shutdown。此后下一次 ensureStarted 可以重新 spawn。
   */
  private handleTransportError(err: Error): void {
    this.logger.error('transport error, retiring subscribers + shutting down', { message: err.message });
    // Treat a transport crash as a forced host replacement. Idle sessions must
    // end their event queues, while sessions with in-flight work need the
    // structured terminal error + Done sequence from their own handlers.
    this.notifySubscribersOfForcedRetire(`transport error: ${err.message}`);
    void this.shutdown(`transport error: ${err.message}`);
  }

  // ── 诊断辅助 (测试 / 日志) ────────────────────────────────────────────────

  /** 当前活跃 subscriber 数 — diagnostics, 不参与业务。 */
  get activeSubscriptions(): number {
    return this.subscribers.size;
  }

  /** Whether this process already owns the live state for a root thread. */
  hasThreadSubscription(threadId: string): boolean {
    return this.subscribers.has(threadId);
  }

  /**
   * Opaque concrete process identity which may own a writer. Null proves no
   * application request/thread evidence in this process. A failed shutdown keeps
   * the client (and evidence); a confirmed exit/restart gets a fresh identity.
   */
  get writerCandidate(): object | null {
    return this.client && this.writerCandidates.has(this.client) ? this.client : null;
  }

  /** 是否已经 spawn 过子进程 (但可能已 close)。 */
  get hasStarted(): boolean {
    return this.client !== null;
  }
}