Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

431 KB
Raw Blame
import { appendLocalFileReferenceContext } from "@pi-desktop/shared";
import { buildJobTools } from "./background-job-tools.js";
import {
  MAX_MUTATION_RECOVERY_FAILURES, BASH_PATCH_FAILURE_KEY,
  RECOVERABLE_MUTATION_ERROR_CODES, mutationFailureKey, isPatchCommand,
  mutationTerminationAdvice, mutationTerminationMessage,
} from "./mutation-recovery.js";
import { DESKTOP_AGENT_IDENTITY } from "./agent-identity.js";
import { resolveMcpToolSelection } from "./mcp-tool-selection.js";
import { concreteResponseModel } from "./response-model.js";
import { BatchPlanner, withBatchTurn } from "./batch-planner.js";
import { TOOL_EXECUTION_SPECS, resolveBatchExecutionMode, toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";
import { AsyncLocalStorage } from "node:async_hooks";
import { TOOL_ACTIVATION_SECTION, toolDeclarationPolicy, toolActivationSection, restoredToolActivation, syncToolActivation, type ToolDeclarationPolicy } from "./fixed-tool-declarations.js";
import { orderSystemRows, SystemTranscriptJournal } from "./system-transcript-journal.js";
import { planWorkspaceRequiredResult } from "./plan-workspace-error.js";
import { accountModelStream } from "./request-usage.js";
import { modeToolDenial, retainModeToolDeclaration, withModeExecutionGuard } from "./mode-tool-access.js";
import { restoreHostedSearchReplay } from "./hosted-search-replay.js";
import { requestExtensionUi } from "./extensions/ui-request.js";
import { waitForOperation } from "./extensions/operation.js";
import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import { isValidToolCall, recoverMalformedToolCalls } from "./tool-call-recovery.js";
import { textToolCallDiagnostic } from "./text-tool-call.js";
import { computerUseDescription, computerUseParameters } from "./computer-use/tool.js";
import { imageGenerationDescription, imageGenerationParameters } from "./image-generation/tool.js";
import { todoWriteDescription, todoWriteParameters } from "./todo-tool.js";
import { createJevClassifierTool } from "./jev-classifier-tool.js";
import { CODEMODE_TOOL_NAME } from "./codemode/limits.js";
import { createSessionCodemodeTool } from "./codemode/session.js";
import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { withPiFileOpToolNames } from "./pi-file-ops.js";
import { remoteMutationIdentity } from "./remote-workspace.js";
import { randomUUID } from "node:crypto";
import { mkdirSync } from "node:fs";
import {
  settledDelegationMessage,
  taskMessageSnapshot,
} from "./delegation-message.js";
import { composeDelegateBrief, delegationUserPrompt, literalDelegationUserPrompt, readDelegationUserPrompt, validateUserRequest, type DelegationUserPrompt } from "./delegation-brief.js";
import { DelegationInbox, MAX_DELEGATE_INSTRUCTION_CHARS, type QueuedInstruction } from "./delegation-instructions.js";
import { approveRoleModelChange } from "./delegation-model-approval.js";
import { canResumeDelegation, delegationModelSelection, delegationPolicyHash, matchesDelegationModel, scopedWriteMetadata, selectDelegationTools, thinkingForDelegationModel, type DelegationModelSelection, type DelegationPolicy } from "./delegation-policy.js";
import { parseWriteScope, sameWriteScope } from "./delegation-scope.js";
import {
  Agent,
  runToolCall,
  type AgentContext,
  type AgentEvent,
  type AgentLoopTurnUpdate,
  type AgentMessage,
  type AgentTool,
  type AgentToolResult,
  type AfterToolCallContext,
  type AfterToolCallResult,
  type BeforeToolCallContext,
  type BeforeToolCallResult,
  type PrepareNextTurnContext,
} from "@earendil-works/pi-agent-core";
import {
  cleanupSessionResources,
  isContextOverflow,
  getCurrentTools,
  getToolStateChanges,
  toToolDeclaration,
  type Api,
  type AssistantMessage,
  type ImageContent,
  type Model,
  type Models,
  type SimpleStreamOptions,
  type ToolResultMessage,
  type Usage,
  type UserMessage,
} from "@earendil-works/pi-ai";
import { Type } from "typebox";
import {
  DEFAULT_COMMAND_TIMEOUT_MS,
  OAUTH_AUTH_KIND,
  type TrustedExtensionCommand,
  type TrustedExtensionDiagnostic,
  type TrustedExtensionSpec,
  type TrustedExtensionUiResponse,
} from "@pi-desktop/shared";
import type {
  TrustedExtensionRunner,
  RegisteredTrustedExtensionAgent,
  TrustedExtensionBridge,
} from "./extensions/runner.js";
import type {
  AgentActivity,
  AgentActivityAgent,
  AgentActivityAgentPhase,
  AgentActivityError,
  AgentEventEnvelope,
  AgentStatus,
  AgentPromptAttachment,
  AskToolQuestion,
  AskToolRequest,
  AskToolResolution,
  ContextCompactionFallback,
  CommandShellOption,
  ContextCompactionReason,
  ContextCompactionRecord,
  ContextCompactionSettings,
  MessageUsage,
  Mode,
  ModeDefinition,
  ModeTurnContext,
  MessageAttachment,
  SessionMessageOrigin,
  PlanExecution,
  PlanProposal,
  PlanningState,
  Risk,
  SubagentDefinition,
  SubagentRunStatus,
  SessionThinkingLevel,
  SubagentThinkingLevel,
  ThinkingLevel,
  ToolTokenUsage,
  UiMessage,
} from "@pi-desktop/shared";
import {
  addUsage,
  checkpointGeneration,
  contextCompactionMark,
  cumulativeDelta,
  DEFAULT_SUBAGENT_PERMISSION,
  askToolOptionLabel,
  formatAskToolOutput,
  formatSessionMessage,
  hostedSearchFromMessage,
  isCommandShellOption,
  isAskToolQuestionWithinLimit,
  isToolsOutputParams,
  MAX_ASK_TOOL_QUESTION_CHARS,
  MAX_SUBAGENT_CONCURRENCY,
  normalizeAskToolOption,
  normalizeSubagentName,
  proposalKindForMode,
  resolveSubagentToolNames,
  splitInlineContent,
  subagentModelKey,
  subagentToolsLabel,
  type ProposalKind,
  type SubagentPermission,
  GEN_UI_SKILL_ID,
  withoutReasoningReplayPlaceholder,
} from "@pi-desktop/shared";
import { createStreamCoalescer, type StreamCoalescer } from "./stream-coalescer.js";
import { checkGenUiFragment, genUiFragmentCheckNote, isGenUiFragmentPath } from "./gen-ui-fragment-check.js";
import type { RuntimeHost } from "./host-client.js";
import { classifyAgentError } from "./agent-errors.js";
import {
  captureAssistantProviderReplay,
  restoreAssistantProviderReplay,
  providerReplayForBubble,
  providerReplayToolCallSignatures,
} from "./assistant-provider-replay.js";
import {
  assistantContent,
  sameCommentaryBoundaries,
  type CommentaryTranscript,
  isRecord,
  nowIso,
  timestampMs,
  toJsonObject,
  toJsonValue,
  truncateTextWithMarker,
  usageFromPi,
  usageToPi,
} from "./agent-messages.js";
import {
  hostContentBlockText,
  restoredToolResultContent,
} from "./tool-result-content.js";
import { withExplicitRequired } from "./tool-schema.js";
import { buildSessionContext } from "./session-context.js";
import {
  collectMessageFileOperations,
  executedToolCallIdsInEntries,
  prepareCompaction,
} from "./pi-runtime-compaction-plan.js";
import { compact } from "./pi-runtime-compaction-summary.js";
import {
  ESTIMATED_TEXT_CHARS_PER_TOKEN,
  estimateContextTokens,
  estimateTokens,
} from "./pi-runtime-estimates.js";
import { convertToLlm } from "./pi-runtime-messages.js";
import { withPluginModelContext, type ReadPluginModelContext } from "./plugin-model-context.js";
import type {
  CompactionEntry,
  CompactionPreparation,
  CompactionSettings,
  Entry,
  MessageEntry,
} from "./pi-runtime-types.js";
import {
  initialSystemTranscript,
  CONTEXT_BUDGET_SECTION,
  syncSystemSections,
  systemTranscriptCheckpoint,
  removeTrailingAssistantMessages,
  rebuildSystemTranscript,
  replaceSystemPrompt,
  systemPromptContent,
} from "./system-transcript.js";
import {
  dedupeToolCallMessages,
  createToolCallIdentity,
  reportDuplicateToolCallDrop,
} from "./tool-call-dedupe.js";
import {
  apiBindingForProviderModel,
  buildProviderModel,
  copilotRequestHeaders,
  createExtensionAgentModels,
  createProviderModels,
  DEFAULT_CONTEXT_WINDOW,
  providerRequestFetch,
  providerRequestKey,
  type RuntimeProviderConfig,
} from "./provider-binding.js";
import {
  contextBudgetFor,
  automaticCompactionThresholdFor,
  contextBudgetLimitsFor,
  retainedUserMessageBudget,
  type ContextBudget,
} from "./context-budget.js";
import { PathMutex } from "./path-lock.js";
import { DelegationChainRegistry } from "./delegation-chain.js";
import {
  extractReadFiles,
  isReadOnlyToolName,
  listedReadFiles,
  originalTaskFromTranscript,
  rebuildChainsFromTranscript,
  selectChainRows,
  seedDelegateMessages,
  type DelegationChain,
} from "./delegation-history.js";
import {
  clampOutputToContext,
  effectiveModelContextWindow,
  estimateOutputCapInputTokens,
  requestTranscript,
  supportsMidConversationSystemMessages,
  truncateTextWithinOutputCap,
} from "./output-cap.js";
import {
  composeSubagentSystemPrompt,
  MAX_SUBAGENT_REPORT_CHARS,
  SubagentRun,
  SUBAGENT_LIST_TOOL_NAME,
  SUBAGENT_SEND_TOOL_NAME,
  SUBAGENT_STOP_TOOL_NAME,
  SUBAGENT_TOOL_NAME,
  SUBAGENT_WAIT_TOOL_NAME,
  type SubagentRunResult,
  type SubagentToolOutcome,
} from "./subagent.js";
import {
  composeModeSystemPrompt,
  DEFAULT_RUNTIME_SYSTEM_PROMPT,
} from "./mode-prompts.js";
import { RuntimeModeState, type ModeTurnNoticeParams } from "./modes/mode-state.js";
import {
  COMPLETE_STAGE_TOOL_NAME,
  createCompleteStageTool,
  type ModeGateCommand,
  type ModeGateRunResult,
} from "./modes/complete-stage-tool.js";
import { createHostModeArtifactReader } from "./modes/mode-artifact-reader.js";
import type { ModeArtifactReader } from "./modes/stage-brief.js";
import { agentThinkingLevel, clampThinkingLevel, omitThinkingModel } from "./thinking-level.js";
import {
  alignRetainedReasoningIdentity,
  harvestRetainedReasoning,
  type ReasoningReplayIdentity,
} from "./reasoning-replay.js";
import { genericModelConfig, visionFromModelConfig } from "./model-capabilities.js";
import type { ProjectInstructions } from "./project-instructions.js";
import { projectInstructionsPrompt } from "./project-instructions-prompt.js";
import type { CustomSystemPrompt } from "./custom-system-prompt.js";
import { projectMemoryPrompt } from "./project-memory-prompt.js";
import {
  pluginSkillsPrompt,
  pluginSkillsPromptSections,
  SKILL_TOOL_NAME,
  type PluginSkillDef,
} from "./plugin-skills-prompt.js";
import { pluginSkillsDigest } from "./plugin-skills.js";
import {
  openCodeEndpointFromProvider,
  withOpenCodeSessionHeaders,
} from "./opencode-session-headers.js";
import { withCodexCacheableInstructions } from "./codex-cacheable-instructions.js";
import { withFastModeOptions } from "./fast-mode.js";
import { withSessionAffinityOptions } from "./session-affinity.js";
import { withCompactionRequestHeaders } from "./compaction-request.js";
import type { CompactionRequestShape } from "./compaction-diagnostics.js";
import {
  addSummaryUsage,
  compactionSummaryInputLimit,
  compactionSummaryOutputBudget,
  compactionSummaryReserveTokens,
  COMPACTION_SUMMARY_RETRY_POLICY,
  estimateSummaryPromptTokens,
  planSummaryChunks,
  reduceSummaryInput,
} from "./compaction-summary-input.js";
import {
  CHECKPOINT_TRUNCATION_MARKER,
  COMPACTION_RETAINED_TAIL_SHAPE,
  replayRetainedTail,
  selectRecentTail,
} from "./compaction-tail.js";
import {
  mergeProviderHeaders,
  providerHeadersEqual,
  withProviderHeaders,
} from "./provider-headers.js";
import {
  captureProviderResponse,
  classifyProviderError,
  createProviderRetryStream,
  delayWithAbort,
  PROVIDER_RATE_LIMIT_MAX_RETRIES,
  PROVIDER_TRANSIENT_MAX_RETRIES,
  carriesRetryDelayHeaders,
  isTransientProviderRetryCode,
  providerRateLimitDelayMs,
  providerSetupRetryDelayMs,
  streamIdleTimeoutMs,
  withStreamIdleTimeout,
} from "./provider-retry.js";

import {
  ContextEstimateCalibration,
  type ContextCalibration,
} from "./context-calibration.js";

import { rebuildNodeNetworkTransport } from "./node-proxy.js";
import {
  rejectConflictingAliasedParams,
  requireAliasedParams,
  TOOL_PARAM_ALIASES,
} from "./tool-param-aliases.js";
import {
  createProviderTransportHealth,
  explainsProviderFetchFailure,
  withProviderFetchFailure,
  type ProviderFetchFailure,
  type ProviderTransportHealth,
} from "./provider-transport-recovery.js";

import { fileLineLabel, MAX_FILE_LINE_REFERENCES, parseFileLineRange } from "@pi-desktop/shared";

export type { RuntimeProviderConfig } from "./provider-binding.js";

export type RuntimePromptAttachment = Omit<AgentPromptAttachment, "kind"> & {
  /**
   * `session` is written by Electron main for a resolved
   * `pi-desktop://session/<id>` reference; the renderer never sends it.
   */
  kind: AgentPromptAttachment["kind"] | "session";
  /** Base64 payload is transient and only crosses the sidecar for this turn. */
  data?: string;
  /** Bounded excerpt of a referenced conversation (`kind: "session"`). */
  text?: string;
  /** Set by the runtime when an explicit line reference could not be read. */
  fileReferenceError?: "blocked" | "failed";
};

export type RuntimePrompt = {
  text: string;
  /** Trusted Main delivery, already recorded as a tool row. */
  backgroundCompletion?: UiMessage;
  /** Explicit user selection, resolved against the host-provided tool catalog. */
  mcpServerIds?: string[];
  mcpToolNames?: string[];
  sessionMessage?: SessionMessageOrigin;
  attachments?: RuntimePromptAttachment[];
  /**
   * Trusted run context of a staged mode turn, validated by the sidecar
   * against the session's mode definition (ADR mode-definitions).
   */
  modeTurn?: ModeTurnContext;
};

/**
 * The user's own words plus one quoted block per referenced conversation. The
 * visible prompt is never rewritten: references are additive, and the model
 * must receive this text — a reference accounted for by compaction but absent
 * from the provider request would be context the user never got.
 */
function promptText(input: RuntimePrompt): string {
  const attachments = input.attachments ?? [];
  const sessions = attachments
    .filter(attachment => attachment.kind === "session")
    .map((attachment) => sessionReferenceBlock(attachment))
    .filter((block): block is string => block !== null);
  const fileLines = attachments.filter(attachment => attachment.lineRange && attachment.text !== undefined)
    .slice(0, MAX_FILE_LINE_REFERENCES)
    .map(attachment => {
      const source = escapeAttribute(fileLineLabel(attachment.path, attachment.lineRange!));
      const text = attachment.text!.replaceAll("<", "&lt;");
      return attachment.fileReferenceError
        ? `<file_reference_error source="${source}" status="${attachment.fileReferenceError}">\n${text}\n</file_reference_error>`
        : `<file_lines source="${source}">\n${text}\n</file_lines>`;
    });
  const references = [...sessions, ...fileLines];
  const text = references.length
    ? `${input.text}\n\n${references.join("\n\n")}`.trim()
    : input.text;
  return appendLocalFileReferenceContext(text, input.attachments ?? []);
}

/** One provider image block for an attachment whose bytes crossed this turn. */
function promptImageBlock(attachment: RuntimePromptAttachment): ImageContent {
  return {
    type: "image" as const,
    data: attachment.data!,
    mimeType: attachment.mimeType || "image/png",
  };
}

/** Attachments carrying image bytes this call may inline for the model. */
function promptImages(input: RuntimePrompt): RuntimePromptAttachment[] {
  return (input.attachments ?? []).filter(
    (attachment) =>
      attachment.kind === "image" &&
      typeof attachment.data === "string" &&
      attachment.data.length > 0,
  );
}

/**
 * The prompt the model receives. An image the user placed between words carries
 * the `@path` the Composer serialized, so it becomes a block at that position
 * instead of following every text block (the pre-placement behavior, which is
 * still what an image without an `inlinePath` gets).
 */
function promptContent(input: string | RuntimePrompt): UserMessage["content"] {
  if (typeof input === "string") return input;
  const text = promptText(input);
  const images = promptImages(input);
  if (!images.length) return text;
  const { parts, trailing } = splitInlineContent(text, images);
  const blocks: Array<{ type: "text"; text: string } | ImageContent> = parts.flatMap(
    (part): Array<{ type: "text"; text: string } | ImageContent> =>
      part.kind === "text"
        ? part.text
          ? [{ type: "text" as const, text: part.text }]
          : []
        : [promptImageBlock(part.attachment)],
  );
  blocks.push(...trailing.map(promptImageBlock));
  return blocks;
}

function runtimeAttachmentFromMessage(
  attachment: MessageAttachment,
  data?: string,
): RuntimePromptAttachment {
  return {
    path: attachment.ref,
    name: attachment.name,
    kind: attachment.kind,
    ...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),
    ...(attachment.size !== undefined ? { size: attachment.size } : {}),
    ...(attachment.localReference ? { localReference: attachment.localReference } : {}),
    ...(attachment.text ? { text: attachment.text } : {}),
    // Recorded placement: the message content names this image at that spot, so
    // the restored prompt keeps the block there too.
    ...(attachment.inlinePath ? { inlinePath: attachment.inlinePath } : {}),
    ...(attachment.lineRange ? { lineRange: attachment.lineRange } : {}),
    ...(data ? { data } : {}),
  };
}

/** Attribute-safe text: a session title may contain quotes or angle brackets. */
function escapeAttribute(value: string): string {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

/**
 * A referenced conversation travels with the user's message as one delimited
 * block: it is quoted context, not the user's own words (a session link in the
 * draft produced it), so the model reads it as reference material.
 */
export function sessionReferenceBlock(attachment: RuntimePromptAttachment): string | null {
  const text = attachment.text?.trim();
  if (!text) return null;
  const title = escapeAttribute(attachment.name || attachment.path);
  return `<session_reference name="${title}" session="${escapeAttribute(attachment.path)}">\n${text}\n</session_reference>`;
}

// pi-ai's adapter retry is disabled here so setup and mid-stream 429s share
// one runtime-owned budget instead of multiplying nested retry loops.
const PROVIDER_REQUEST_MAX_RETRIES = 0;
export const TOOL_SEARCH_NAME = "ToolSearch";
/** Stands in for a persisted tool row that never recorded a result. */
const MISSING_TOOL_RESULT_PLACEHOLDER = "[no tool result recorded]";

function toolNameList(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return [
    ...new Set(
      value.filter(
        (name: unknown): name is string =>
          typeof name === "string" && name.length > 0,
      ),
    ),
  ];
}

/** Read canonical and historical activation markers from a ToolSearch row. */
function toolSearchActivatedNames(
  details: unknown,
  legacyAddedToolNames?: unknown,
): string[] {
  const record = isRecord(details) ? details : undefined;
  const candidates = [
    record?.addedToolNames,
    record?.activated,
    legacyAddedToolNames,
  ];
  for (const candidate of candidates) {
    const names = toolNameList(candidate);
    if (names.length > 0) return names;
  }
  return [];
}

function isMissingToolResultPlaceholder(
  content: ToolResultMessage["content"],
): boolean {
  return (
    content.length === 1 &&
    content[0].type === "text" &&
    content[0].text === MISSING_TOOL_RESULT_PLACEHOLDER
  );
}

/** Narrow view of the `tool_end` agent event; the envelope carries the rest. */
type ToolEndEvent = {
  type: "tool_end";
  toolCallId: string;
  result: unknown;
  isError?: boolean;
};

/** Narrow view of the `tool_start` agent event; the envelope carries the rest. */
type ToolStartEvent = {
  type: "tool_start";
  toolCallId: string;
  toolName: string;
  args?: unknown;
};

export const ASK_TOOL_NAME = "asktool";
/**
 * Delegation lifecycle (ADR 0089): `Task` starts a subagent in the background
 * and returns immediately; `TaskWait` converges on running delegations;
 * `TaskList` reports on them; `TaskStop` stops them. Records are kept for the
 * session's lifetime (bounded by pruning below), so a settled delegation can
 * be re-read by id without re-running it.
 */
const MAX_RETAINED_DELEGATIONS = 100;
const DELEGATION_MODEL_OPT_IN_GUIDANCE =
  'To authorize a model override, open Settings → Models, edit the service or account, expand its model Advanced settings, enable "Available for AI delegation", and save. Use an exact key from the delegation catalog; never guess a provider/model key.';
const DELEGATION_DEFAULT_MODEL_GUIDANCE =
  "Omit the `model` parameter on Task to use the definition's default model, or inherit the parent conversation's selected model when no default is pinned. Repeating the definition's own Default model key is the same as omitting `model`.";
/**
 * `TaskWait` blocks the turn, and the model picks the timeout, so the ceiling
 * is what bounds how long a session can look hung with no way to intervene.
 * Expiry is not a failure and does not stop the delegates (D328) — the wait
 * returns a heartbeat plus any finished reports, and the runtime delivers the
 * rest when they finish even if the parent already stopped calling tools.
 */
const TASKWAIT_DEFAULT_TIMEOUT_SECONDS = 600;
const TASKWAIT_MAX_TIMEOUT_SECONDS = 900;
/**
 * A `TaskWait` result is the parent's context; like a delegate's report, it
 * must not become the context problem delegation exists to avoid.
 */
const MAX_TASKWAIT_RESULT_CHARS = 50_000;

export type DelegationStatus =
  | "running"
  | SubagentRunStatus
  | "stopped";

/**
 * One background delegation owned by the session runtime. `completion`
 * resolves when the delegate settles; `abort` stops the delegate's agent.
 */
export type DelegationRecord = {
  delegationId: string;
  /** Parent `Task` toolCallId that started this delegation. */
  parentToolCallId?: string;
  /** True when the delegate declares file-mutating tools (`Write` / `Edit`). */
  writable?: boolean;
  /**
   * Chain id under which host-core keeps this Write/Edit subagent's own git
   * worktree in an isolated session (ADR 0329); absent otherwise.
   */
  worktreeKey?: string;
  /** Original Task transcript snapshot, available after its immediate result. */
  taskMessage?: UiMessage;
  taskTurnId?: string;
  agentName: string;
  modelId: string;
  thinkingLevel: SubagentThinkingLevel;
  status: DelegationStatus;
  startedAt: number;
  completedAt?: number;
  result?: SubagentRunResult;
  completion: Promise<void>;
  resolveCompletion: () => void;
  abort: () => void;
  /** True when `TaskStop` asked for this stop, so an aborted run reads as
   * `stopped` rather than `aborted`. */
  stopRequested: boolean;
  /** System interruption preserves resume eligibility; explicit Stop wins. */
  parentErrorInterrupted?: boolean;
  turns: number;
  toolCalls: number;
  lastToolName?: string;
  lastPhase?: AgentActivityAgentPhase;
  lastActivityAt: number;
  /** `prompt()` / `executeApprovedPlan()` generation that started this run.
   * Resume-after-idle only waits for the current turn's delegates (D352). */
  startedEpoch: number;
  /** The settled report reached the parent's context once: through a
   * `TaskWait` result or the resume-after-idle prompt. Auto-delivery is a
   * single shot per record. */
  reportDelivered: boolean;
  /** Stable chain identity; never appears in a tool parameter (ADR 0279). */
  delegateSessionId: string;
  /** Prior `delegationId` this run continues, when `Task.resume` was set. */
  resumedFrom?: string;
  /** Model the run kept before the resume could not re-resolve it (ADR 0279
   * §4): recorded so the parent can see that the delegate's binding moved. */
  modelChangedFrom?: string;
  /** `toolCallId`s of this run's calls that have not ended yet: dropped when the
   * run settles, so an aborted call cannot pin its captured arguments. */
  pendingToolCallIds?: Set<string>;
  policy?: DelegationPolicy;
  modelSelection?: DelegationModelSelection;
  instructions?: DelegationInbox;
  appendInstruction?: (instruction: QueuedInstruction) => boolean;
};


function delegationSummary(record: DelegationRecord): Record<string, unknown> {
  return {
    delegationId: record.delegationId,
    agent: record.agentName,
    modelId: record.modelId,
    thinkingLevel: record.thinkingLevel,
    status: record.status,
    startedAt: record.startedAt,
    turns: record.result?.turns ?? record.turns,
    toolCalls: record.result?.toolCalls ?? record.toolCalls,
    ...(record.lastToolName ? { lastToolName: record.lastToolName } : {}),
    ...(record.completedAt ? { completedAt: record.completedAt } : {}),
    ...(record.result?.modelFailures ? { modelFailures: record.result.modelFailures } : {}),
    ...(record.result?.error ? { error: record.result.error } : {}),
    // A delegate that compacted or lost history says so in its lifecycle
    // details, not only in the report text (ADR 0299, decision 4).
    ...(record.result?.contextCompactions
      ? { contextCompactions: record.result.contextCompactions }
      : {}),
    ...(record.result?.contextDegraded
      ? { contextDegraded: record.result.contextDegraded }
      : {}),
    ...(record.result?.scratchReportPath
      ? { scratchReportPath: record.result.scratchReportPath }
      : {}),
    ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),
    ...(record.modelChangedFrom
      ? { modelChangedFrom: record.modelChangedFrom }
      : {}),
    ...(record.policy ? { delegationPolicy: record.policy } : {}),
    ...(record.modelSelection ? { delegationModel: record.modelSelection } : {}),
    ...delegationInstructionDetails(record),
  };
}

function delegationInstructionDetails(record: DelegationRecord) {
  const instructions = record.instructions?.snapshot();
  // Details carry ids for the client; the tool's text tells the model what happened.
  return instructions && Object.values(instructions).some((ids) => ids.length) ? { instructions } : {};
}

function delegationInstructionNote(record: DelegationRecord): string {
  const { instructions } = delegationInstructionDetails(record);
  return instructions ? `Instructions: ${instructions.queued.length} queued, ${instructions.delivered.length} delivered, ${instructions.undelivered.length} undelivered.` : "";
}

function elapsedSeconds(record: DelegationRecord, now = Date.now()): number {
  const end = record.completedAt ?? now;
  return Math.max(1, Math.round((end - record.startedAt) / 1000));
}

function agentActivityEqual(
  left?: AgentActivity,
  right?: AgentActivity,
): boolean {
  return JSON.stringify(left) === JSON.stringify(right);
}

function waitingSubagentSnapshot(
  record: DelegationRecord,
): AgentActivityAgent {
  return {
    name: record.agentName,
    ...(record.lastPhase ? { lastPhase: record.lastPhase } : {}),
    ...(record.lastToolName ? { lastToolName: record.lastToolName } : {}),
  };
}

function waitingSubagentsActivity(
  targets: DelegationRecord[],
  since: number,
): Extract<AgentActivity, { phase: "waiting-subagents" }> {
  const running = targets.filter((record) => record.status === "running");
  return {
    phase: "waiting-subagents",
    since,
    subagentCount: running.length,
    ...(running.length > 0
      ? { agents: running.map(waitingSubagentSnapshot) }
      : {}),
  };
}

function formatDelegationHeartbeat(record: DelegationRecord): string {
  const parts = [
    `${record.agentName} (${record.delegationId})`,
    record.status,
    `${elapsedSeconds(record)}s`,
  ];
  const turns = record.result?.turns ?? record.turns;
  const toolCalls = record.result?.toolCalls ?? record.toolCalls;
  if (turns > 0) parts.push(`${turns} turns`);
  if (toolCalls > 0) parts.push(`${toolCalls} tool calls`);
  if (record.lastToolName) parts.push(`last tool ${record.lastToolName}`);
  return parts.join(", ");
}

const DELEGATION_RESUME_PROMPT =
  "The following subagents have finished. Integrate their reports and continue the user's original task. Call TaskStop only if you have decided a still-running delegate should not continue.";

/** Join delegation results into one bounded text block for the model. */
function formatDelegationResults(
  results: Array<{ delegationId: string; agent: string; status: string; report: string }>,
  note?: string,
): { text: string; includedDelegationIds: Set<string> } {
  const parts: string[] = [];
  const includedDelegationIds = new Set<string>();
  let total = 0;
  let omitted = 0;
  for (const result of results) {
    const block = `## ${result.agent} (${result.delegationId}) — ${result.status}\n${result.report}`;
    if (total + block.length > MAX_TASKWAIT_RESULT_CHARS) {
      omitted += 1;
      continue;
    }
    parts.push(block);
    includedDelegationIds.add(result.delegationId);
    total += block.length + 2;
  }
  if (omitted > 0) {
    parts.push(
      `[${omitted} more result${omitted === 1 ? "" : "s"} omitted to protect this context; call TaskWait with their delegationIds to re-read one.]`,
    );
  }
  return {
    text: [note, ...parts].filter((part) => part?.trim()).join("\n\n"),
    includedDelegationIds,
  };
}
const COMPACTION_FALLBACK_MAX_SUMMARY_CHARS = 12_000;
/**
 * Room held back from a fallback's tail for the recovery notice the checkpoint
 * appends after the carried-forward summary.
 */
const COMPACTION_FALLBACK_NOTICE_TOKENS = 512;
/**
 * Share of the safe budget a failure's retained window may occupy. The window
 * is bounded by the keep-recent target as well, so it never carries more
 * history than a successful checkpoint would (`fallbackRetainedTail`).
 */
const COMPACTION_FALLBACK_KEEP_RECENT_RATIO = 0.25;
/**
 * Smallest fraction of that window the recovery path shrinks to before it
 * gives up: seven halvings, enough for a calibrated estimate many times the
 * local one (`recoverCompactionFailure`, issue #2494).
 */
const COMPACTION_FALLBACK_MIN_TAIL_SCALE = 1 / 128;
export const COMPACTION_FALLBACK_MARKER =
  "[automatic context recovery: older context was omitted after summary generation failed]";
/** Stored in place of a carried-forward summary when a fallback had none. */
const COMPACTION_FALLBACK_NO_SUMMARY =
  "No previous context checkpoint is available.";

/**
 * A retained-tail fallback stores any carried-forward summary ahead of the
 * recovery notice, separated by `COMPACTION_FALLBACK_MARKER` (see
 * `createFallbackCheckpoint`). Only the notice is synthetic: the text before
 * the marker is the real summary the failed compaction was carrying forward.
 * Strip the notice — and the "no previous summary" placeholder — so the next
 * summarization rebuilds from that real summary instead of updating a notice
 * that never was a summary (#224), without discarding the history it carried.
 */
function stripCompactionFallbackNotice(
  summary: string | undefined,
): string | undefined {
  if (!summary) return undefined;
  const markerIndex = summary.indexOf(COMPACTION_FALLBACK_MARKER);
  if (markerIndex === -1) return summary;
  const carried = summary.slice(0, markerIndex).trim();
  if (carried.length === 0 || carried === COMPACTION_FALLBACK_NO_SUMMARY) {
    return undefined;
  }
  return carried;
}

/**
 * File operations for a summary chunk that must not re-append the checkpoint's
 * file lists: the last chunk carries the real ones, so a chained summary names
 * each file once.
 */
function emptyFileOps(): CompactionPreparation["fileOps"] {
  return { read: new Set(), written: new Set(), edited: new Set() };
}
/** Path-scoped rules are best-effort and must not stall a file tool turn. */
export const PATH_INSTRUCTION_RESOLUTION_TIMEOUT_MS = 2_000;
const PATH_SCOPED_INSTRUCTION_TOOLS = new Set([
  "Read",
  "Write",
  "Edit",
  "BrowserPreview",
]);
/** Tools whose `path` argument is rewritten, and which therefore must not run
 * concurrently against the same file (see `PathMutex`). */
const PATH_MUTATING_TOOLS = new Set(["Write", "Edit"]);
/** Declared up front at the contract level (Plan and read-only modes). */
const CONTRACT_CORE_TOOL_NAMES = new Set(["Read", "Glob", "Grep", "Bash", "BrowserPreview", ASK_TOOL_NAME]);
const AGENT_CORE_TOOL_NAMES = new Set([
  "Read",
  "Glob",
  "Grep",
  "Write",
  "Edit",
  "Bash",
  ASK_TOOL_NAME,
  // The slash menu answers a user-invoked `/skill:<skill-id>` with an instruction to
  // call `Skill { id }` on the first turn (ADR 0219), and a capability the
  // model has to go looking for is one it will not use. Registration keeps its
  // own gate: the tool only exists when the catalog is non-empty.
  SKILL_TOOL_NAME,
]);
const MAX_ON_DEMAND_TOOL_PROMPT_ENTRIES = 64;
const MAX_TOOL_SEARCH_RESULT_NAMES = 24;


/** Tools that ask the host to switch this session into a contract mode (D198). */
const ENTER_TOOL_NAMES: Record<ProposalKind, string> = {
  plan: "EnterPlanMode",
  goal: "EnterGoalMode",
};
/** Tools that submit a contract of one kind for approval (D198). */
const SUBMIT_TOOL_NAMES: Record<ProposalKind, string> = {
  plan: "SubmitPlan",
  goal: "SubmitGoal",
};
/**
 * Every mode transition must be the only call in its assistant message, so the
 * host commits one durable mode change per tool-call batch.
 */
const MODE_TRANSITION_TOOL_NAMES = new Set([
  ...Object.values(ENTER_TOOL_NAMES),
  ...Object.values(SUBMIT_TOOL_NAMES),
]);

function enterToolKind(name: string): ProposalKind | undefined {
  return name === ENTER_TOOL_NAMES.plan
    ? "plan"
    : name === ENTER_TOOL_NAMES.goal
      ? "goal"
      : undefined;
}

function submitToolKind(name: string): ProposalKind | undefined {
  return name === SUBMIT_TOOL_NAMES.plan
    ? "plan"
    : name === SUBMIT_TOOL_NAMES.goal
      ? "goal"
      : undefined;
}

function modeLabel(mode: Mode): string {
  return mode === "plan" ? "Plan" : mode === "goal" ? "Goal" : "Agent";
}

type ToolCatalogEntry = {
  name: string;
  description: string;
};

type PathInstructionResolution = {
  instructions?: ProjectInstructions;
  fallback: boolean;
};

function pathInstructionScope(path: string): string {
  const normalized = path.replaceAll("\\", "/");
  const slash = normalized.lastIndexOf("/");
  return slash >= 0 ? normalized.slice(0, slash) || "/" : ".";
}

/**
 * Appended for one automatic re-run after a turn that produced nothing the
 * user can see. Two shapes were observed: a wholly empty response, and a
 * finished conclusion written into reasoning while the visible text stayed
 * empty. The same nudge covers both, because both need the same next move.
 */
const SILENT_TURN_NUDGE = [
  "<no_output_recovery>",
  "Your previous turn ended with no visible text and no tool call, so the user saw nothing happen.",
  "Your reasoning is never shown to the user. If you already reached the answer, state it now in plain text.",
  "Otherwise continue the unfinished work, starting with one sentence about what you are doing.",
  "</no_output_recovery>",
].join("\n");

/**
 * Autonomous plan/goal execution: collaboration prompts ask the model to
 * narrate progress ("Writing it now.") then call a tool. Models often emit
 * that narration as a finished assistant message with `finish_reason: stop`
 * and no toolCall, so the runtime treats it as the final answer and ends the
 * run mid-task (#43). One automatic continue with this nudge, then stop.
 */
const PROGRESS_TURN_NUDGE = [
  "<progress_only_recovery>",
  "Your last message announced next steps but contained no tool call, so the autonomous run would have stopped mid-task.",
  "Continue the approved plan now: either call the tools for the work you just described, or write the final self-contained completion report.",
  "Do not announce intent without a tool call in the same message.",
  "</progress_only_recovery>",
].join("\n");

/**
 * Some OpenAI-style models emit their internal parallel-call wrapper as
 * assistant text (`to=multi_tool_use.parallel code:{"tool_uses":[…]}`) instead
 * of real tool calls. PI-Desktop has no such tool, so the whole batch lands as
 * prose and silently does nothing — the turn looks finished while no work ran.
 * Rare (2 occurrences across 255 recorded sessions) but indistinguishable from
 * a stuck agent when it happens.
 */
export function looksLikePseudoToolCall(text: string): boolean {
  return (
    text.includes("multi_tool_use.parallel") || text.includes('{"tool_uses":')
  );
}

/**
 * Automatic protection is on unless a caller explicitly disables it. The token
 * thresholds carried by the legacy settings shape are ignored: they are derived
 * from the active model's context window in `contextBudget`, because no single
 * configured number fits both a 32K and a 1M window.
 */
function compactionEnabled(value?: Partial<ContextCompactionSettings>): boolean {
  return value?.enabled !== false;
}

/**
 * The two compaction families Codex has. `summary` spends a model request on a
 * structured summary of the boundary range; `fresh_window` rolls the context
 * over without summarizing it, the way Codex's token-budget compaction calls
 * `start_new_context_window()`.
 *
 * This is not a user-facing setting — Codex does not expose it either, and a
 * user cannot judge the trade-off from the UI. It exists so the no-summary
 * family is implemented and reachable, not configurable.
 */
export type CompactionStrategy = "summary" | "fresh_window";

function resolveCompactionStrategy(
  option?: CompactionStrategy,
): CompactionStrategy {
  if (option) return option;
  return process.env.PI_DESKTOP_COMPACTION_STRATEGY === "fresh_window"
    ? "fresh_window"
    : "summary";
}

/**
 * Stands in for the summary a rollover deliberately does not generate. The
 * host rejects an empty checkpoint summary, and a silent placeholder would
 * leave the model guessing why its context changed, so the rollover says so.
 */
const CONTEXT_ROLLOVER_SUMMARY = [
  "[context rollover: a new context window was started without summarizing conversation history]",
  "Earlier messages in this session are not part of this request. The complete transcript is still available to the user, and the environment is unchanged.",
  "Ask before assuming anything about work that is not visible here.",
].join("\n\n");

/**
 * Codex's model-facing compaction tool: no parameters, and the description is
 * its wording verbatim. The model cannot know how much room is left, so the
 * tool is only useful together with the budget reminders below.
 */
/** An abort the error classifier recognizes structurally, not by message. */
function turnAbortedError(message: string): Error {
  const error = new Error(message);
  error.name = "AbortError";
  return error;
}

const CONTEXT_COMPACTION_TOOL_NAME = "new_context";
/**
 * Tools a codemode script never calls: tool discovery, user interaction, mode
 * and stage control, context control, and delegation lifecycle all belong to
 * the model's own turn, not to a script.
 */
const CODEMODE_EXCLUDED_TOOL_NAMES: ReadonlySet<string> = new Set([
  CODEMODE_TOOL_NAME,
  TOOL_SEARCH_NAME,
  ASK_TOOL_NAME,
  ...MODE_TRANSITION_TOOL_NAMES,
  COMPLETE_STAGE_TOOL_NAME,
  CONTEXT_COMPACTION_TOOL_NAME,
  SUBAGENT_TOOL_NAME,
  SUBAGENT_WAIT_TOOL_NAME,
  SUBAGENT_LIST_TOOL_NAME,
  SUBAGENT_STOP_TOOL_NAME,
  SUBAGENT_SEND_TOOL_NAME,
]);
/** Tools the read-only contract level may execute, besides plan-safe plugins. */
const CONTRACT_ALLOWED_TOOL_NAMES = new Set([...CONTRACT_CORE_TOOL_NAMES, CONTEXT_COMPACTION_TOOL_NAME]);
const CONTEXT_COMPACTION_TOOL_DESCRIPTION =
  "Start a new context window. Does not clear, reset, or otherwise affect environment state.";
/** Codex's `NEW_CONTEXT_WINDOW_MESSAGE`, one per family. */
const CONTEXT_COMPACTION_TOOL_REPLY: Record<CompactionStrategy, string> = {
  fresh_window:
    "A new context window will start without summarizing conversation history.",
  summary:
    "A new context window will start with a summary of the conversation history.",
};

/**
 * Two-tier budget reminder, matching Codex's `TokenBudgetReminder` and
 * `AutoCompactFallbackPrompt`. Codex reads both thresholds and both texts from
 * per-model metadata; we have no such feed, so the thresholds are derived from
 * the same hard limit the compaction guard uses and the texts are ours.
 */
const CONTEXT_REMINDER_MIN_TOKENS = 8_000;
const CONTEXT_REMINDER_MAX_TOKENS = 32_000;
const CONTEXT_REMINDER_RATIO = 0.15;
/** Close enough to the boundary that the next turn is likely to cross it. */
const CONTEXT_FALLBACK_REMINDER_TOKENS = 2_000;

function contextBudgetReminder(remaining: number): string {
  return [
    "<context_budget>",
    `About ${remaining.toLocaleString("en-US")} tokens of working context remain before this conversation is compacted.`,
    "Start closing out: write anything durable to files, and prefer targeted reads over broad exploration.",
    `You may call ${CONTEXT_COMPACTION_TOOL_NAME} to start the new window yourself once the current step is at a clean stopping point.`,
    "</context_budget>",
  ].join("\n");
}

function contextFallbackReminder(): string {
  return [
    "<context_budget>",
    "The working context is at its limit: the next request compacts this conversation automatically.",
    "Write down now, in this turn, whatever must survive — file paths, decisions, and the exact next step — because unsummarized detail will not be available afterwards.",
    "</context_budget>",
  ].join("\n");
}


export type PluginToolDef = {
  /** Present only on tools resolved from a user MCP server by Electron main. */
  mcpServerId?: string;
  /** Full exposed name (`plugin_<pluginIdSafe>_<toolName>`, D015). */
  name: string;
  description?: string;
  /** JSON schema for arguments (manifest agentTools[].schema). */
  parameters?: unknown;
  /** Declared plugin risk, when the plugin supplied a bounded value. */
  risk?: Risk;
  /**
   * Action names that may run in Plan or Goal mode (ADR 0211). When set
   * and non-empty the runtime may expose this plugin tool in Plan/Goal
   * modes; host-core enforces the per-action restriction.
   */
  planSafeActions?: readonly string[];
};

export type AgentRuntimeOptions = {
  host: RuntimeHost;
  sessionId: string;
  mode: Mode;
  /**
   * Definition of `mode` resolved by Electron main (ADR mode-definitions).
   * Without one, the builtin mapping decides the tool policy.
   */
  modeDefinition?: ModeDefinition;
  /** Durable host turn ID for the current prompt, used by plan identity. */
  turnId?: string;
  readPluginModelContext?: ReadPluginModelContext;
  provider: RuntimeProviderConfig;
  thinkingLevel: SessionThinkingLevel;
  /** Persisted opt-in for retrying transient provider failures until success. */
  infiniteProviderRetry?: boolean;
  backgroundJobContinuationEnabled?: boolean;
  /**
   * Fast mode for main turns, already resolved by the launcher from the
   * session `/fast` switch and the model binding's opt-in (ADR 0334).
   */
  fastMode?: boolean;
  /** TypeSafe Jev credential, resolved by Electron main only when enabled. */
  jevApiKey?: string;
  /**
   * Whether the `Computer` tool is offered at all (ADR 0342). Resolved by
   * Electron main from settings, so a disabled feature is absent from the
   * prompt rather than advertised and refused on every call.
   */
  computerUseEnabled?: boolean;
  /**
   * Whether the opt-in `codemode` tool is offered (ADR
   * codemode-sandbox-boundary). Resolved by Electron main from settings.
   */
  codemodeEnabled?: boolean;
  systemPrompt?: string;
  /** pi-compatible SYSTEM.md / APPEND_SYSTEM.md resolved for the session (issue #542). */
  customSystemPrompt?: CustomSystemPrompt;
  /** Session-bound workspace root used for path-scoped instruction requests. */
  projectPath?: string;
  /** Remote tool root. Model requests and runtime state remain on this machine. */
  remoteWorkspace?: { hostKey: string; path: string };
  /**
   * An isolated session's git worktree (ADR 0329). Files, the extension cwd,
   * and edit bookkeeping use it; `projectPath` stays the project identity.
   */
  workspaceRoot?: string;
  /** Instructions resolved from the session's workspace. */
  projectInstructions?: ProjectInstructions;
  /** Durable project context loaded from host-owned project memory. */
  projectMemory?: string;
  /** Persisted transcript to seed the agent with (session isolation: each
   * session's agent carries only its own history). */
  history?: UiMessage[];
  /** Latest host-owned checkpoint used only to rebuild model context. */
  compaction?: ContextCompactionRecord;
  compactionSettings?: ContextCompactionSettings;
  /**
   * Which compaction family to use. Tests set it explicitly; production reads
   * `PI_DESKTOP_COMPACTION_STRATEGY` and otherwise summarizes.
   */
  compactionStrategy?: CompactionStrategy;
  /** Plugin agent tools to expose to the model this session. */
  pluginTools?: PluginToolDef[];
  /** Plugin skills advertised in the system prompt and loaded via `Skill`. */
  pluginSkills?: PluginSkillDef[];
  /** Trusted extensions enabled for this session (D387); loaded by
   * `loadTrustedExtensions()` before the first prompt. */
  trustedExtensions?: TrustedExtensionSpec[];
  /** Effective command shell selected by host-core for this session. */
  commandShell: CommandShellOption;
  /** Absolute per-session scratch directory for temporary files (D114).
   * Advertised to the model in the system prompt; host-core enforces it as
   * a second containment root. */
  scratchDir?: string;
  /** Absolute per-session directory for inline visualization fragments
   * (ADR gen-ui-inline-visualization). Advertised in the system prompt;
   * host-core enforces it as a containment root. Ignored for remote sessions. */
  visualizationsDir?: string;
  onEvent: (envelope: AgentEventEnvelope) => void;
  /** Bounded diagnostics routed to the Electron logger, never the transcript. */
  onDiagnostic?: (diagnostic: AgentRuntimeDiagnostic) => void;
  /**
   * Subagent definitions this session may delegate to (ADR 0062), already
   * merged and capped by Electron main. Empty means no `Task` tool at all.
   */
  subagents?: SubagentDefinition[];
  /**
   * Provider resolved for each definition that pins one, keyed by its model
   * key. Main owns credential lookup, so a pinned provider that is missing
   * here is unavailable and the delegate must fail loudly rather than
   * silently run on the session's model.
   */
  subagentProviders?: Record<string, RuntimeProviderConfig>;
  /** Resolved keys explicitly opted into Task.model selection; pins alone grant no override. */
  subagentModelKeys?: string[];
};

export type AgentRuntimeDiagnostic = {
  kind: "compaction_failure" | "compaction_shape";
  sessionId: string;
  turnId?: string;
  requestId: string;
  data: Record<string, unknown>;
};

export type RuntimeMatchConfig = {
  mode: Mode;
  provider: RuntimeProviderConfig;
  thinkingLevel: SessionThinkingLevel;
  jevApiKey?: string;
  computerUseEnabled?: boolean;
  codemodeEnabled?: boolean;
  pluginTools?: PluginToolDef[];
  pluginSkills?: PluginSkillDef[];
  trustedExtensions?: TrustedExtensionSpec[];
  customSystemPrompt?: CustomSystemPrompt;
  projectInstructions?: ProjectInstructions;
  projectMemory?: string;
  projectPath?: string;
  /** Remote tool root. Model requests and runtime state remain on this machine. */
  remoteWorkspace?: { hostKey: string; path: string };
  workspaceRoot?: string;
  commandShell: CommandShellOption;
  subagents?: SubagentDefinition[];
  subagentProviders?: Record<string, RuntimeProviderConfig>;
  /** Resolved keys explicitly opted into Task.model selection; pins alone grant no override. */
  subagentModelKeys?: string[];
};

/** Tool calls ride in the assistant content array as `type: "toolCall"`. A
 * message that requested any is never a silent turn: the loop keeps going and
 * the user sees the tool activity. */
function trustedExtensionIds(specs: TrustedExtensionSpec[]): string {
  return specs.map((spec) => spec.id).sort().join("\n");
}

function messageRequestsTools(message: unknown): boolean {
  const content = isRecord(message) ? message.content : undefined;
  return (
    Array.isArray(content) &&
    content.some((part) => isRecord(part) && part.type === "toolCall")
  );
}

const PROGRESS_FORWARD_INTENT_PATTERNS = [
  /\b(?:about to|going to|will|next|then|still(?: need| have to)?|remaining|left to|working on|writing|reading|updating|implementing|checking|running|creating|fixing|reviewing|proceed(?:ing)?|continu(?:e|ing)|starting|moving on)\b/i,
  /(?:接下来|下一步|还需要|仍需|剩下|正在|将要|继续|开始)/i,
];
const PROGRESS_TERMINAL_LEAD =
  /^(?:done|all done|complete(?:d)?|finished|implemented|resolved|verified|successful(?:ly)?|the (?:approved )?(?:plan|goal) is complete)\b/i;

function hasProgressForwardIntent(text: string): boolean {
  return PROGRESS_FORWARD_INTENT_PATTERNS.some((pattern) => pattern.test(text));
}

/** Clearly forward-looking visible assistant text without a toolCall. */
export function isProgressOnlyAssistantTurn(message: unknown): boolean {
  if (!isRecord(message) || message.role !== "assistant") return false;
  if (messageRequestsTools(message)) return false;
  const content = assistantContent(message.content);
  const text = content.text.trim();
  if (!text && content.transcript?.text.trim()) return true;
  if (content.hasFinalAnswer || !text || !hasProgressForwardIntent(text)) return false;
  if (!PROGRESS_TERMINAL_LEAD.test(text)) return true;

  // A report can mention a completed step and still announce the next one.
  // Only recover a terminal-looking lead when a later clause carries the
  // forward intent that distinguishes it from a normal final report.
  return hasProgressForwardIntent(text.replace(PROGRESS_TERMINAL_LEAD, ""));
}

function boundedText(value: string, maxChars: number): string {
  const text = value.trim();
  if (text.length <= maxChars) return text;
  const marker = "\n\n[context recovery summary shortened]\n\n";
  const available = Math.max(2, maxChars - marker.length);
  const headChars = Math.ceil(available / 2);
  const tailChars = Math.floor(available / 2);
  return `${text.slice(0, headChars)}${marker}${text.slice(-tailChars)}`;
}

type CheckpointPersistResult = "persisted" | "oversized" | "failed";

type CompactionRetentionMode = "active_turn" | "completed_turn";

/**
 * A pi preparation plus the anchor the checkpoint is filed against.
 *
 * pi 0.84 dropped `firstKeptEntryId` from `CompactionPreparation`: the
 * compaction entry it writes *is* the boundary, so nothing needs to name the
 * first kept entry. We still record ours — it becomes
 * `ContextCompactionRecord.firstKeptMessageId`, which is persisted and reported
 * on `compaction_end` — so the Codex-shaped reshape below carries it alongside
 * pi's fields.
 */
type ShapedPreparation = CompactionPreparation & {
  firstKeptEntryId?: string;
};

type CheckpointBuildSuccess = {
  ok: true;
  checkpoint: ContextCompactionRecord;
  entries: Entry[];
  budget: ContextBudget;
  preparation: ShapedPreparation;
};

/**
 * Why a checkpoint had to fall back, recorded on the fallback's `details` so a
 * later report says more than `usage: null` does (issue #827). Deliberately a
 * closed vocabulary: provider error text can carry endpoint details, and ADR
 * 0049 keeps it out of the persisted record.
 */
type CompactionFailureReason =
  | "no_new_history"
  | "summary_budget"
  | "summary_provider"
  | "checkpoint_oversized";

type CheckpointBuildFailure = {
  ok: false;
  entries: Entry[];
  budget: ContextBudget;
  preparation?: ShapedPreparation;
  message: string;
  /** Recorded on the fallback checkpoint when this failure recovers to one. */
  failureReason?: CompactionFailureReason;
  tokensBefore?: number;
  /**
   * False when the failure must be reported as-is instead of falling back to a
   * retained-tail checkpoint: the build was cancelled, or the transcript has no
   * durable boundary to anchor any checkpoint to.
   */
  recoverable: boolean;
};

type CheckpointBuild = CheckpointBuildSuccess | CheckpointBuildFailure;

function compactionRetentionMode(details: unknown): CompactionRetentionMode {
  // Checkpoints written before the task-boundary fix did not record whether
  // their retained users belonged to an in-progress turn. Treat those
  // records as active, but still reduce them to one latest user message so a
  // restart cannot restore a sequence of executable-looking old requests.
  return isRecord(details) && details.retainedTailMode === "completed_turn"
    ? "completed_turn"
    : "active_turn";
}

/**
 * The messages a stored checkpoint replays as real context after its summary.
 *
 * A checkpoint that recorded {@link COMPACTION_RETAINED_TAIL_SHAPE} keeps the
 * whole window it stored: it is a failed compaction's only record of the range
 * behind it, so narrowing the tail back to one user message would reinstate
 * exactly the amnesia the window fixes (#827). Records written before that
 * marker existed — and every successful checkpoint — keep the older
 * normalization: at most the latest user message, and none at all once the turn
 * is complete, so a restart cannot restore a sequence of executable-looking old
 * requests.
 */
function retainedTailForContext(
  value: unknown,
  details?: unknown,
): AgentMessage[] | undefined {
  if (!Array.isArray(value)) return undefined;
  if (
    isRecord(details) &&
    details.retainedTailShape === COMPACTION_RETAINED_TAIL_SHAPE
  ) {
    return replayRetainedTail(value) ?? [];
  }
  const messages = value
    .filter(isRecord)
    .filter((message) => message.role === "user") as unknown as AgentMessage[];
  if (compactionRetentionMode(details) === "completed_turn") return [];
  const latestUser = messages.at(-1);
  return latestUser ? [latestUser] : [];
}

function safeJson(value: unknown): string {
  try {
    return JSON.stringify(value) ?? String(value);
  } catch {
    return String(value);
  }
}

const MIN_COMMAND_TIMEOUT_SECONDS = 1;
/** Host safety bound so every spawn still has a finite deadline (D329). */
const MAX_COMMAND_TIMEOUT_SECONDS = 21_600;
/**
 * Schema ceiling for `Bash.timeout`, not an honoured duration. It has to admit
 * millisecond values models send, then the runtime reads those as seconds and
 * clamps to {@link MAX_COMMAND_TIMEOUT_SECONDS} (D273 / D329).
 */
const MAX_ACCEPTED_COMMAND_TIMEOUT = 100_000_000;
const TOOL_OUTPUT_UPDATE_THROTTLE_MS = 100;
const READ_ONLY_CORE_TOOLS = new Set(["Read", "Glob", "Grep"]);
/**
 * How long a stop request waits for a tool that host-core can actually
 * interrupt (`Bash`, `GenerateImages`) to hand back the output it collected
 * before the kill (#1767). Tools without host-side cancellation do not wait at
 * all: the runtime stops waiting the moment the signal fires.
 */
const TOOL_ABORT_GRACE_MS = 10_000;
const MAX_TOOL_PROGRESS_CHARS = 64 * 1024;
const TOOL_PROGRESS_TRUNCATION_MARKER =
  "\n\n[tool output progress truncated]\n\n";

function shellScratchVariable(shell: CommandShellOption): string {
  switch (shell.dialect) {
    case "powershell":
      return "$env:PI_SCRATCH_DIR";
    case "cmd":
      return "%PI_SCRATCH_DIR%";
    case "posix":
      return "$PI_SCRATCH_DIR";
  }
}

function shellSyntaxGuidance(shell: CommandShellOption): string {
  switch (shell.dialect) {
    case "powershell":
      return "Use native Windows PowerShell syntax and Windows paths such as `C:\\work\\file.txt` or `.\\file.txt`.";
    case "cmd":
      return "Use native cmd.exe syntax and Windows paths such as `C:\\work\\file.txt` or `.\\file.txt`.";
    case "posix":
      return "Use native POSIX shell syntax and forward-slash paths such as `/work/file.txt` or `./file.txt`.";
  }
}

export function formatScratchDirForShell(
  shell: CommandShellOption,
  scratchDir?: string,
): string | undefined {
  if (!scratchDir) return undefined;
  if (shell.dialect === "posix") {
    // POSIX shells (including Git Bash on Windows) require forward slashes.
    return scratchDir.replaceAll("\\", "/");
  }
  return scratchDir;
}

export function commandShellGuidance(
  shell: CommandShellOption,
  scratchDir?: string,
): string {
  const scratchVariable = shellScratchVariable(shell);
  const formattedScratch = formatScratchDirForShell(shell, scratchDir);
  const scratch = formattedScratch
    ? `The session scratch directory is \`${formattedScratch}\`; use ${scratchVariable} for it and keep temporary files there.`
    : `When PI_SCRATCH_DIR is available, use ${scratchVariable} for the session scratch directory and keep temporary files there.`;
  return [
    `Shell commands run through ${shell.label} (${shell.id}). The protocol tool remains named Bash for compatibility, even when the active shell is PowerShell or cmd.`,
    shellSyntaxGuidance(shell),
    scratch,
  ].join(" ");
}

function commandShellToolDescription(
  shell: CommandShellOption,
  scratchDir?: string,
): string {
  const formattedScratch = formatScratchDirForShell(shell, scratchDir);
  return [
    `Run a non-interactive command through ${shell.label} in the workspace root.`,
    "The protocol tool remains named Bash for compatibility; write commands for the active shell dialect.",
    shellSyntaxGuidance(shell),
    `The session scratch directory variable is ${shellScratchVariable(shell)}.`,
    `An optional timeout from 1 to ${MAX_COMMAND_TIMEOUT_SECONDS} seconds may be supplied; without it, the command defaults to a 60-second timeout.`,
    `In a local Agent session, ordinary Bash can return a running job after a short wait. Do independent work if useful, then use TaskWait with the job reference before relying on the exit code or any files the command produces. The command keeps its original time limit. Set runInBackground: true for long-lived processes the user needs after the turn ends (dev servers, watchers, builds). A background call returns a backgroundTaskId immediately, survives turn aborts and timeouts, and its output is visible in the composer's running-tasks bar. In Agent mode on supported local Hosts, use TaskList to find it, TaskWait with its job reference to read results, and TaskStop with that reference to stop it. By default, background completion does not automatically resume the model. If notifyOnExit is available in the schema, it may arrange completion-triggered continuation for finite tests/builds.`,
    ...(formattedScratch ? [`The session scratch directory is ${formattedScratch}.`] : []),
  ].join(" ");
}

/**
 * A canonical argument that an alias can stand in for. It has to be optional in
 * the schema — the alias satisfies it — so {@link requireAliasedParams} enforces
 * "exactly one spelling" after {@link normalizeToolParams} has run.
 */
function pathParam(description: string) {
  return Type.Optional(Type.String({ description }));
}

/** The alias spelling of `canonical`, accepted but never advertised as first choice. */
function aliasParam(canonical: string) {
  return Type.Optional(
    Type.String({ description: `Alias for \`${canonical}\`.` }),
  );
}

/**
 * Folds aliased argument names onto the canonical ones and reads a Bash
 * `timeout` that arrived in milliseconds as seconds (D273). Both rewrites are
 * silent: the call succeeds as the model intended rather than costing a turn on
 * a validation error the model cannot see. Returns `params` unchanged when
 * there is nothing to rewrite so the common path allocates nothing.
 */
function normalizeToolParams(toolName: string, params: unknown): unknown {
  if (!isRecord(params)) return params;
  const aliases = TOOL_PARAM_ALIASES[toolName];
  // A value above the honoured seconds ceiling is the millisecond habit (D273 /
  // D329). In-range values, including 600 and 1800, are seconds the agent chose.
  const timeoutIsMs =
    toolName === "Bash" &&
    typeof params.timeout === "number" &&
    Number.isFinite(params.timeout) &&
    params.timeout > MAX_COMMAND_TIMEOUT_SECONDS;
  const aliased = aliases
    ? Object.keys(aliases).filter((alias) => params[alias] !== undefined)
    : [];
  if (aliased.length === 0 && !timeoutIsMs) return params;
  const next = { ...params };
  for (const alias of aliased) {
    const canonical = aliases![alias];
    // Differing spellings were rejected by rejectConflictingAliasedParams
    // before execution; either way the alias is dropped so the host and the
    // transcript never see it.
    if (next[canonical] === undefined) next[canonical] = next[alias];
    delete next[alias];
  }
  if (timeoutIsMs) {
    // Above the honoured seconds ceiling is milliseconds (D273 / D329).
    next.timeout = Math.min(
      MAX_COMMAND_TIMEOUT_SECONDS,
      Math.max(
        MIN_COMMAND_TIMEOUT_SECONDS,
        Math.round((params.timeout as number) / 1000),
      ),
    );
  }
  return next;
}

function commandTimeoutMs(params: unknown): number {
  const timeout = isRecord(params) ? params.timeout : undefined;
  if (timeout === undefined) return DEFAULT_COMMAND_TIMEOUT_MS;
  if (
    typeof timeout !== "number" ||
    !Number.isFinite(timeout) ||
    timeout < MIN_COMMAND_TIMEOUT_SECONDS
  ) {
    throw Object.assign(
      new Error(
        `Invalid timeout: must be a finite number of seconds between ${MIN_COMMAND_TIMEOUT_SECONDS} and ${MAX_COMMAND_TIMEOUT_SECONDS}`,
      ),
      { errorCode: "INVALID_ARGUMENT" },
    );
  }
  if (timeout > MAX_COMMAND_TIMEOUT_SECONDS) {
    throw Object.assign(
      new Error(
        `Invalid timeout: maximum is ${MAX_COMMAND_TIMEOUT_SECONDS} seconds`,
      ),
      { errorCode: "INVALID_ARGUMENT" },
    );
  }
  const timeoutMs = Math.ceil(timeout * 1000);
  return timeoutMs;
}

/**
 * A supplementary-plane character is one code point and two UTF-16 code units.
 * The progress cap counts code units, so a point that does not fit is left out
 * whole instead of being sliced through the middle of its surrogate pair.
 */
function takePrefixCodeUnits(text: string, budget: number): string {
  let used = 0;
  let end = 0;
  for (const point of text) {
    if (used + point.length > budget) break;
    used += point.length;
    end += point.length;
  }
  return text.slice(0, end);
}

function takeSuffixCodeUnits(text: string, budget: number): string {
  let used = 0;
  let start = text.length;
  while (start > 0 && used < budget) {
    const low = text.charCodeAt(start - 1);
    const high = start >= 2 ? text.charCodeAt(start - 2) : 0;
    const pair =
      low >= 0xdc00 &&
      low <= 0xdfff &&
      high >= 0xd800 &&
      high <= 0xdbff;
    const size = pair ? 2 : 1;
    if (used + size > budget) break;
    used += size;
    start -= size;
  }
  return text.slice(start);
}

function appendToolProgress(current: string, chunk: string): string {
  const combined = `${current}${chunk}`;
  if (combined.length <= MAX_TOOL_PROGRESS_CHARS) return combined;
  const remaining = Math.max(
    0,
    MAX_TOOL_PROGRESS_CHARS - TOOL_PROGRESS_TRUNCATION_MARKER.length,
  );
  const headBudget = Math.ceil(remaining * 0.6);
  const tailBudget = remaining - headBudget;
  const head = takePrefixCodeUnits(combined, headBudget);
  const tail = tailBudget > 0 ? takeSuffixCodeUnits(combined, tailBudget) : "";
  return `${head}${TOOL_PROGRESS_TRUNCATION_MARKER}${tail}`;
}

/**
 * Flatten a user message to plain text so it can be truncated at a token
 * budget. Images and other non-text blocks are named rather than kept: a
 * checkpoint that carried them would spend its whole budget on one of them.
 */
function userMessageTextForCheckpoint(message: UserMessage): string {
  if (typeof message.content === "string") return message.content;
  return message.content
    .map((block) =>
      block.type === "text"
        ? block.text
        : `[${block.type} content omitted from checkpoint]`,
    )
    .join("\n");
}

function truncateUserMessageForCheckpoint(
  message: UserMessage,
  tokenBudget: number,
): UserMessage {
  const text = userMessageTextForCheckpoint(message);
  // Same ASCII ceiling as before (budget * 3.5). CJK is then shrunk to the
  // output-cap estimate, which charges about one token per character.
  const ceiling = Math.max(
    1,
    Math.floor(tokenBudget * ESTIMATED_TEXT_CHARS_PER_TOKEN),
  );
  return {
    ...message,
    content: truncateTextWithinOutputCap(
      text,
      tokenBudget,
      CHECKPOINT_TRUNCATION_MARKER,
      ceiling,
    ),
  };
}

/**
 * Choose the user messages that survive a compaction boundary: newest first up
 * to `maxTokens`, truncating the one that crosses the budget instead of
 * dropping it, then restored to chronological order. This is Codex's
 * `build_compacted_history_with_limit` selection.
 */
function selectRetainedUserMessages(
  candidates: UserMessage[],
  maxTokens: number,
): UserMessage[] {
  const selected: UserMessage[] = [];
  let remaining = Math.max(0, maxTokens);
  for (let index = candidates.length - 1; index >= 0 && remaining > 0; index -= 1) {
    const message = candidates[index];
    // pi-ai's chars/3.5 estimate under-counts Han, kana, and Hangul, so a long
    // CJK message looks like it fits and is kept whole. The output-cap
    // estimate is the one the next request is gated on.
    const tokens = Math.max(
      estimateTokens(message),
      estimateOutputCapInputTokens({
        messages: [{ role: "user", content: message.content }],
      }),
    );
    if (tokens <= remaining) {
      selected.push(message);
      remaining -= tokens;
      continue;
    }
    selected.push(truncateUserMessageForCheckpoint(message, remaining));
    break;
  }
  return selected.reverse();
}

/**
 * JSON text fallback for a host result that produced no text blocks. Image
 * `data` and resource `blob` bytes stay off the text channel; type, mimeType,
 * and uri remain so the model still sees what was attached.
 */
function withoutInlineBinary(value: unknown): unknown {
  if (Array.isArray(value)) return value.map((entry) => withoutInlineBinary(entry));
  if (!isRecord(value)) return value;
  const next: Record<string, unknown> = {};
  for (const [key, entry] of Object.entries(value)) {
    if (key === "data" && value.type === "image") continue;
    if (key === "resource" && value.type === "resource" && isRecord(entry)) {
      const resource: Record<string, unknown> = {};
      for (const [resourceKey, resourceValue] of Object.entries(entry)) {
        if (resourceKey === "blob") continue;
        resource[resourceKey] = withoutInlineBinary(resourceValue);
      }
      next.resource = resource;
      continue;
    }
    next[key] = withoutInlineBinary(entry);
  }
  return next;
}

/** Rebuild a pi-ai tool result from a persisted tool row. Rows that never
 * finished (app quit / abort mid-tool) restore as errored results so the
 * model knows the call produced nothing. Exported for tests. */
export function toolResultFromUi(
  m: UiMessage,
  timestamp: number,
): ToolResultMessage {
  const raw: unknown = m.toolResult;
  const blocks = restoredToolResultContent(raw);
  const interrupted = m.toolStatus === "running";
  const rawRecord: Record<string, unknown> | undefined = isRecord(raw)
    ? raw
    : undefined;
  const rawAddedToolNames = rawRecord?.addedToolNames;
  const addedToolNames =
    m.toolName === TOOL_SEARCH_NAME
      ? toolSearchActivatedNames(rawRecord?.details, rawAddedToolNames)
      : toolNameList(rawAddedToolNames);
  if (blocks.length === 0) {
    blocks.push({
      type: "text",
      text: interrupted
        ? "[tool call was interrupted before a result was recorded]"
        : MISSING_TOOL_RESULT_PLACEHOLDER,
    });
  }
  return {
    role: "toolResult",
    toolCallId: m.toolCallId ?? "",
    toolName: m.toolName ?? "",
    content: blocks,
    ...(toJsonValue(rawRecord?.details) !== undefined || addedToolNames.length > 0
      ? {
          details: {
            ...toJsonObject(rawRecord?.details),
            ...(addedToolNames.length > 0 ? { addedToolNames } : {}),
          },
        }
      : {}),
    isError:
      interrupted ||
      m.toolStatus === "error" ||
      m.toolStatus === "denied" ||
      m.isError === true,
    timestamp,
  };
}

function estimateToolTokenUsage(
  model: Model<Api>,
  toolCallId: string,
  toolName: string,
  args: unknown,
  result: unknown,
  isError: boolean,
  timestamp: number,
): ToolTokenUsage | undefined {
  const toolCall = {
    role: "assistant" as const,
    content: [
      {
        type: "toolCall" as const,
        id: toolCallId,
        name: toolName,
        arguments: toJsonObject(isRecord(args) ? args : { value: args }),
      },
    ],
    api: model.api,
    provider: model.provider,
    model: model.id,
    usage: usageToPi(undefined),
    stopReason: "toolUse" as const,
    timestamp,
  } satisfies AssistantMessage;
  // Optional telemetry must not suppress a terminal tool event.
  if (!isValidToolCall(toolCall.content[0])) return undefined;
  const toolRow = {
    id: toolCallId,
    role: "tool" as const,
    content: safeJson(result),
    createdAt: new Date(timestamp).toISOString(),
    toolCallId,
    toolName,
    toolResult: result,
    toolStatus: isError ? ("error" as const) : ("success" as const),
    isError,
  } satisfies UiMessage;
  const resultMessage = toolResultFromUi(toolRow, timestamp);
  const argumentTokens = estimateTokens(toolCall);
  const resultTokens = estimateTokens(resultMessage);

  return {
    argumentTokens,
    resultTokens,
    totalTokens: argumentTokens + resultTokens,
    estimated: true,
  };
}

function estimateVisibleResponseOutputTokens(
  message: Pick<UiMessage, "content" | "thinking">,
): number | undefined {
  const visible = `${message.thinking ?? ""}\n${message.content}`.trim();
  if (!visible) return undefined;
  return Math.max(1, Math.ceil(Array.from(visible).length / 4));
}

/** host-core's `worktree.delegate.settle` result (ADR 0329). */
export type DelegateWorktreeSettlement =
  | { result: "none" }
  | { result: "noChanges" }
  | { result: "merged"; commits: number }
  | { result: "conflict"; files: string[] }
  | { result: "notMerged"; reason: string }
  | { result: "kept" };

/** The line appended to a delegate's report about its worktree. */
export function delegateWorktreeNote(settlement: DelegateWorktreeSettlement, resume: string): string {
  switch (settlement.result) {
    case "merged":
      return `Isolated worktree: merged ${settlement.commits} commit(s) into the session workspace.`;
    case "noChanges":
      return "Isolated worktree: no file changes; the worktree was removed.";
    case "conflict":
      return `Isolated worktree: NOT merged. These files conflict with the session workspace: ${settlement.files.join(", ")}. Continue with ${resume} to resolve them in the subagent's worktree; the merge is retried when it ends.`;
    case "notMerged":
      return `Isolated worktree: not merged yet (${settlement.reason}). Continue with ${resume} to retry.`;
    case "kept":
      return `Isolated worktree: the run did not complete, so its changes were kept unmerged. Continue with ${resume} to finish them.`;
    default:
      return "";
  }
}

/**
 * System-prompt rules for an isolated session (ADR 0329): the workspace is a
 * separate git worktree that the user merges from the app.
 */
export function isolatedWorkspaceGuidance(): string {
  return [
    "Isolated session: the advertised workspace is a separate git worktree on its own branch; the user's main project checkout is outside it.",
    "Edit, build, and test only inside this workspace and never change files in the main checkout.",
    "The worktree is a fresh checkout, so install dependencies first when a build or test needs them.",
    "Start dev servers only on the 10 ports beginning at the PI_PORT environment variable.",
    "Do not switch branches, rebase, or reset in this worktree; the user merges its branch into the project from the app.",
    "To resolve a merge conflict here, remove the conflict markers from text files, and stage binary or deleted files with git add or git rm.",
    "MCP tools act on the main project, not on this workspace.",
    "Subagents that can Write or Edit work in their own worktrees and are merged back when they finish; their report states the merge result.",
  ].join(" ");
}

export class DesktopAgentRuntime {
  private agent: Agent;
  private models: Models;
  private model: Model<Api>;
  private turnId?: string;
  private disposed = false;
  private aborting?: Promise<void>;
  readonly sessionId: string;
  /** Session mode, its definition and the claimed run turn (ADR mode-definitions). */
  private readonly modeState: RuntimeModeState;
  /** Gate commands CompleteStage runs through the Host Bash path, by tool-call id. */
  private readonly modeGateCalls = new Map<string, ModeGateCommand["modeGate"]>();
  private get mode(): Mode {
    return this.modeState.modeId;
  }
  private provider: RuntimeProviderConfig;
  private thinkingLevel: SessionThinkingLevel;
  private host: RuntimeHost;
  private onEvent: (envelope: AgentEventEnvelope) => void;
  private onDiagnostic: (diagnostic: AgentRuntimeDiagnostic) => void;
  private streamSink: StreamCoalescer;
  private baseSystemPrompt: string;
  private customSystemPrompt?: CustomSystemPrompt;
  private planningState: PlanningState;
  private pendingPlanId?: string;
  private currentAssistant?: UiMessage;
  private liveCommentary?: CommentaryTranscript;
  private pluginTools: PluginToolDef[];
  private pluginSkills: PluginSkillDef[];
  private trustedExtensionSpecs: TrustedExtensionSpec[];
  private extensionRunner?: TrustedExtensionRunner;
  private trustedExtensionLoad?: Promise<void>;
  private extensionSessionName?: string;
  private extensionTurnIndex = 0;
  /** Headers an extension edited in `before_provider_headers` for the current turn. */
  private extensionProviderHeaders?: Record<string, string>;
  private extensionProviderRequestId = 0;
  /** Subagent definitions offered through the `Task` tool (ADR 0062). */
  private subagents: SubagentDefinition[];
  private subagentProviders: Record<string, RuntimeProviderConfig>;
  private subagentModelKeys: Set<string>;
  /** On-demand Task.model grants; never mixed into launch opt-in matching. */
  private subagentOverrideProviders: Record<string, RuntimeProviderConfig>;
  /**
   * Background delegations of this session (ADR 0089). `Task` starts one and
   * returns; `TaskWait`/`TaskList`/`TaskStop` drive it afterwards.
   */
  private delegations = new Map<string, DelegationRecord>();
  /** Resumable chains rebuilt from the transcript and updated as Task settles. */
  private readonly delegationChains = new DelegationChainRegistry();
  private readonly preparingDelegateWorktrees = new Set<string>();
  private delegationPrompt?: () => Promise<DelegationUserPrompt | undefined>;
  /** Transcript rows used to rebuild a resumed delegate's context (ADR 0279):
   * the seed history at launch plus every row this session's delegates emit. */
  private readonly transcriptHistory: UiMessage[];
  /** Row ids already in `transcriptHistory` from live delegate events, so a
   * retried stream appends once. */
  private readonly appendedDelegationRowIds = new Set<string>();
  /** Name and arguments of a delegate's in-flight call: `tool_end` carries the
   * result only, and the row a resume replays needs both. */
  private readonly delegateToolCalls = new Map<
    string,
    { name: string; args: unknown }
  >();
  /** The prompt this runtime composed last, so a mid-turn refresh can tell its
   * own prompt from a transient variant it must not clobber. */
  private composedSystemPrompt?: string;
  /** Set by `abort` / `dispose` so a finishing delegate cannot restart the parent. */
  private runCancelled = false;
  /** Provider call ids are not unique across sibling agents. Keep all
   * authorization metadata local to the executor, never keyed by such ids. */
  private readonly delegateExecution = new AsyncLocalStorage<{
    owner: string; permission: SubagentPermission; worktreeKey?: string; writeScope?: readonly string[];
    /** The turn that started the delegate; its Host permission ceiling governs the delegate's calls. */
    turnId?: string;
  }>();
  /** Serializes same-path mutations across the parent and its delegates. */
  private writeLocks = new PathMutex();
  /** Orders one parallel batch's calls by the resources they claim. */
  private batchPlanner: BatchPlanner;
  /** Complete tool registry; only the active subset is sent to the provider. */
  private toolCatalog = new Map<string, AgentTool>();
  /** Tools intentionally omitted from the initial provider request. */
  private deferredToolNames = new Set<string>();
  /** Deferred tools activated for this runtime and declaration epoch. */
  private activeDeferredToolNames = new Set<string>();
  private declarationPolicy?: ToolDeclarationPolicy;
  private trackToolActivation = false;
  private activationHydrated = false;
  private scratchDir?: string;
  private visualizationsDir?: string;
  private projectPath?: string;
  private remoteWorkspace?: { hostKey: string; path: string };
  /** Set only for an isolated session; see `RuntimeConfig.workspaceRoot`. */
  private workspaceRoot?: string;
  private commandShell: CommandShellOption;
  private baseProjectInstructions?: ProjectInstructions;
  private projectInstructions?: ProjectInstructions;
  /** Weak argument identity binds preparation to the exact validated call, without retained IDs. */
  private preparedPathToolArgs = new WeakMap<object, unknown>();
  private builtinTools = new WeakSet<AgentTool>();
  private instructionExecution = new AsyncLocalStorage<(instructions: ProjectInstructions | undefined) => void>();
  private projectMemory?: string;
  /** Per-prompt claims prevent repeated path-resolution RPCs for one directory. */
  private pathInstructionClaims = new Map<
    string,
    Promise<PathInstructionResolution>
  >();
  /* Timing anchors (D137). `requestStartedAt` marks the moment the agent is
   * free to issue the next provider request — turn start, or the last tool
   * result coming back — so `providerWaitMs` below is the model's own latency
   * rather than the whole turn. With parallel tool calls the last one wins,
   * which is the correct anchor: the request goes out once all have resolved. */
  private requestStartedAt?: number;
  private streamStartedAt?: number;
  private agentActivity?: AgentActivity;
  /** Targets of the in-flight parent wait; live snapshots refresh this set. */
  private delegationWaitTargets?: DelegationRecord[];
  private providerResponseStatus?: number;
  private providerRetryHeaders?: Record<string, string>;
  /**
   * Size and message count of the provider attempt in flight. A failed request
   * has to be correlatable with how much context it carried, and on a network
   * failure the request never returns a response to read it from (issue #234).
   */
  private providerRequestBytes?: number;
  private providerRequestMessages?: number;
  /**
   * The estimate that describes the provider attempt in flight, parked by
   * `streamFn` and consumed when that attempt settles with a usage report.
   * Without the pair there is nothing to measure the estimator against.
   */
  private inFlightContextEstimate?: ContextCalibration;
  private readonly contextCalibration = new ContextEstimateCalibration();
  /**
   * Transport cause of the last provider attempt that rejected before any
   * response arrived, captured where the original Error still exists. pi-ai
   * only forwards a flattened `errorMessage`, so without this the real errno is
   * gone before classification and `fetch failed` reaches the log as
   * `networkCategory: "unknown"` (issue #234).
   */
  private providerFetchFailure?: ProviderFetchFailure;
  /**
   * Consecutive-failure policy for the shared undici pool. Rebuilding the pool
   * is a process-wide action, so the evidence stays per session and the pool is
   * rebuilt only when the same origin keeps failing unanswered (issue #234).
   */
  private readonly providerTransportHealth: ProviderTransportHealth =
    createProviderTransportHealth();
  private pendingProviderRetry?: ReturnType<typeof classifyAgentError>;
  /** Non-429 setup + stream failures since the last successful response. */
  private providerTransientRetryAttempt = 0;
  /** Shared OpenCode-style 429 retry count across setup and stream phases. */
  private providerRateLimitRetryAttempt = 0;
  /** Opt-in mode removes only the retry-count ceiling; abort and backoff stay intact. */
  private infiniteProviderRetry = false;
  private backgroundJobContinuationEnabled = false;
  private fastMode = false;
  private jevApiKey?: string;
  private computerUseEnabled = false;
  private codemodeEnabled = false;
  private activeProviderRetryAttempt = 0;
  private providerRetryInProgress = false;
  private suppressProviderRetryRunEnd = false;
  private providerRetryAbort?: AbortController;
  /* Silent-turn recovery: a turn that ends with no tool call and no visible
   * text is invisible to the user. 15 of 255 recorded sessions ended a turn
   * that way, and every one of them was followed by the user typing "继续".
   * One automatic re-run per prompt, then the failure becomes visible. */
  private pendingSilentTurnRerun = false;
  private silentTurnRerunAttempted = false;
  /**
   * The first settled reply to a current Host-ledger completion notice may
   * need no acknowledgement (D446). Spent by that reply, and revoked as soon
   * as accepted user steering enters the model context.
   */
  private allowSilentCompletion = false;
  private silentTurnRerunInProgress = false;
  private suppressSilentTurnRunEnd = false;
  /** Autonomous plan/goal execution: one progress-only continue (#43). */
  private autonomousExecution = false;
  private pendingProgressTurnRerun = false;
  private progressTurnRerunAttempted = false;
  private progressTurnRerunInProgress = false;
  private suppressProgressTurnRunEnd = false;
  private bashYieldCalls = new Set<string>();
  private activeToolCalls = new Map<
    string,
    { toolName: string; args: unknown; startedAt: number }
  >();
  private pendingAskTools = new Map<
    string,
    {
      request: AskToolRequest;
      resolve: (answers: Array<string[] | null>) => void;
    }
  >();
  /** Host failures need to reach pi-agent-core's tool error channel without
   * discarding the structured diagnostics returned in `details`. */
  private failedHostToolCalls = new Set<string>();
  /** Per-prompt mutation failures provide one recovery attempt, then stop. */
  private mutationFailureCounts = new Map<string, number>();
  /** `<failure key> <error code>` pairs that already spent their free retry. */
  private mutationRecoveryGraces = new Set<string>();
  /** Why the recovery guard ended the turn, pending its visible error row. */
  private pendingMutationTermination?: {
    kind: "edit" | "patch-command";
    target: string;
    lastErrorCode?: string;
  };
  private terminatingToolCalls = new Set<string>();
  private delegateMutationTerminations = new Map<string, { code: string; message: string }>();
  private fullEntries: MessageEntry[];
  private readonly uniqueToolCalls: ReturnType<typeof createToolCallIdentity>;
  private readonly systemJournal = new SystemTranscriptJournal();
  private composedSections: Record<string, string> = {};
  private activeCompaction?: ContextCompactionRecord;
  private compactionEnabled: boolean;
  private readonly compactionStrategy: CompactionStrategy;
  private pendingUserMessageId?: string;
  private acceptingSteering = false;
  private steeringContinuation = false;
  private steeringWaitAbort?: AbortController;
  private pendingSteering = new Map<AgentMessage, { id: string; toolNames: string[]; delegationPrompt?: DelegationUserPrompt }>();
  private pendingOverflow = false;
  private overflowRecoveryAttempted = false;
  private overflowRecoveryInProgress = false;
  private suppressOverflowRunEnd = false;
  private turnHadError = false;
  /** Bumped at the start of each parent `prompt()` / `executeApprovedPlan()`. */
  private turnEpoch = 0;
  private compactionAbort?: AbortController;
  private compactionInProgress = false;
  /** Runtime operations that own a durable turn until their async cleanup ends. */
  private readonly activeTurnSettlements = new Map<string, Promise<void>>();
  /** The in-flight checkpoint was cut short by Stop/dispose, not by a failure. */
  private compactionAborted = false;
  /** Why the latest checkpoint attempt failed, for the turn error it causes. */
  private lastCompactionFailure?: string;
  /** Set by the `new_context` tool, consumed at the next turn boundary. */
  private pendingModelCompaction = false;
  /** One-shot request to finish the current turn at the next boundary. */
  private gracefulStopRequested = false;
  /** Codex's `claim_*` flags: one of each reminder per context window. */
  private contextReminderClaimed = false;
  private contextFallbackReminderClaimed = false;
  private activeToolProgressCleanups = new Set<(flush: boolean) => void>();
  /**
   * Abort handlers for the tool calls currently awaiting `tools.execute`.
   * `abort()` drives these directly: a tool must be released even when the
   * signal it was handed never fires, or the stop RPC stays pending forever.
   */
  private activeToolAborts = new Set<() => void>();
  private readonly steeringToolAborts = new Map<string, () => void>();
  private fileLineReadCalls = new Map<string, { blocked: boolean }>();
  private hostCloseUnsubscribe?: () => void;
  private turnSubagentUsage?: MessageUsage;
  private compactionRequestShape?: CompactionRequestShape;
  private compactionShapeLogged = false;
  private compactionDiagnosticBudget?: {
    hardLimit: number;
    outputBudget: number;
    plannedChunks: number;
  };

  constructor(opts: AgentRuntimeOptions) {
    this.sessionId = opts.sessionId;
    this.turnId = opts.turnId;
    // A restored checkpoint already compacted the window: stage
    // `on.compaction` injects apply from the first run turn.
    this.modeState = new RuntimeModeState(opts.mode, opts.modeDefinition, { compacted: Boolean(opts.compaction) });
    this.planningState = proposalKindForMode(this.mode) ? "planning" : "inactive";
    this.provider = opts.provider;
    this.thinkingLevel = clampThinkingLevel(opts.provider, opts.thinkingLevel);
    this.infiniteProviderRetry = opts.infiniteProviderRetry === true;
    this.backgroundJobContinuationEnabled = opts.backgroundJobContinuationEnabled === true;
    this.fastMode = opts.fastMode === true;
    this.jevApiKey = opts.jevApiKey;
    this.computerUseEnabled = opts.computerUseEnabled === true;
    this.codemodeEnabled = opts.codemodeEnabled === true;
    this.host = opts.host;
    this.batchPlanner = new BatchPlanner(this.host, this.sessionId);
    this.onDiagnostic = opts.onDiagnostic ?? (() => undefined);
    this.hostCloseUnsubscribe = this.host.onClose?.(() => {
      this.cleanupActiveToolProgress();
    });
    this.streamSink = createStreamCoalescer(opts.onEvent);
    this.onEvent = (envelope) => this.streamSink.push(envelope);
    this.pluginTools = opts.pluginTools ?? [];
    this.pluginSkills = [...(opts.pluginSkills ?? [])].sort((left, right) => left.id.localeCompare(right.id));
    this.trustedExtensionSpecs = opts.trustedExtensions ?? [];
    this.subagents = opts.subagents ?? [];
    this.subagentProviders = opts.subagentProviders ?? {};
    this.subagentModelKeys = new Set(opts.subagentModelKeys ?? []);
    this.subagentOverrideProviders = {};
    if (!isCommandShellOption(opts.commandShell) || !opts.commandShell.available) {
      throw Object.assign(new Error("active command shell is invalid or unavailable"), {
        errorCode: "COMMAND_SHELL_INVALID",
      });
    }
    this.commandShell = opts.commandShell;
    this.remoteWorkspace = opts.remoteWorkspace;
    this.scratchDir = opts.remoteWorkspace ? undefined : opts.scratchDir;
    this.visualizationsDir = opts.remoteWorkspace ? undefined : opts.visualizationsDir;
    this.projectPath = opts.remoteWorkspace?.path ?? (opts.projectPath?.trim() || undefined);
    // Remote workspaces are never isolated (ADR 0329).
    this.workspaceRoot = opts.remoteWorkspace ? undefined : opts.workspaceRoot?.trim() || undefined;
    this.customSystemPrompt = opts.customSystemPrompt;
    this.baseProjectInstructions = opts.projectInstructions;
    this.projectInstructions = opts.projectInstructions;
    this.projectMemory = opts.projectMemory?.trim() || undefined;
    this.compactionEnabled = compactionEnabled(opts.compactionSettings);
    this.compactionStrategy = resolveCompactionStrategy(opts.compactionStrategy);

    this.rebuildToolCatalog();
    const model = buildProviderModel(this.provider);
    this.model = model;
    const models = createProviderModels(this.provider, model);
    this.models = models;
    const runtimeApiKey = providerRequestKey(this.provider);

    this.transcriptHistory = [...(opts.history ?? [])];
    this.fullEntries = this.historyToEntries(this.transcriptHistory, opts.compaction?.throughMessageId);
    this.uniqueToolCalls = createToolCallIdentity(this.fullEntries.map((entry) => entry.message));
    this.activeCompaction = opts.compaction;
    this.delegationChains.hydrate(
      rebuildChainsFromTranscript(this.transcriptHistory),
    );
    // Parts: [0] is the product persona; [1:] are operational rules a custom
    // SYSTEM.md must not remove (tool guidance, delegation, scratch, skills).
    const defaultSystemPromptParts = [
      DEFAULT_RUNTIME_SYSTEM_PROMPT,
      // Workflow rules.
      "Complete the requested work and relevant checks without expanding scope. Preserve unrelated user changes. Resolve recoverable blockers yourself.",
      // Visibility rules.
      "Before each tool batch, briefly state its purpose. Keep the user informed during long work. The final response must state the outcome, verification, and remaining blockers. Never claim actions or checks you did not perform.",
      // File-reference formatting.
      "File references: when citing a real local file, use a Markdown link with a short label and the exact absolute path as its target, e.g. [file.ts](/workspace/src/file.ts:42). Add only a starting line (:line or :line:column) when useful; do not use ranges or GitHub #L anchors. Wrap destinations containing spaces in angle brackets. Do not wrap links in backticks or use file://, vscode://, or https:// for local files. Link only to existing files in the accessible workspace; mention unavailable or other-repository files as code text.",
      // Delegation steering (ADR 0089).
      ...(this.subagents.length
        ? [
            `## Delegation
Do the work yourself by default. Delegate only bounded, independent tasks with a clear benefit over direct execution.
No recursive delegation, duplicate work, or agent debates.
If the user names an expert, use that exact role. Copy only the user's exact relevant words into Task.userRequest; put your additions in Task.task. Do not substitute a role or add conflicting instructions. If the role is unavailable or the relevant text is unclear, tell the user or ask for clarification.
Allow at most one optional review pass unless the user requests more. Fix and retest concrete, in-scope defects without restarting broad reviews.
Do not invent objections or turn speculative risks into blockers. Stop when the requested work is complete and relevant checks pass, or report a genuine blocker.`,
            ...(this.subagentModelSummary()
              ? [this.subagentModelSummary()!]
              : []),
          ]
        : []),
      // Editing workflow.
      `Editing workflow: inside the advertised workspace, use Edit for small, uniquely anchored changes and Write for new files or intentional whole-file rewrites. Never modify the same path concurrently. Do not use shell apply_patch, git apply, patch, or hand-edited unified-diff files. On failure, diagnose the cause, refresh content or anchors with Read or a complete tool-provided reveal when needed, and correct the payload before retrying. After three failed edit attempts on the same path in one user turn, stop editing that path, report the exact error, and continue unblocked work. For an authorized worktree outside the advertised workspace, use a guarded, deterministic Bash edit that aborts on unexpected content, then verify the diff.`,
      // Shell dialect and scratch variable are selected by host-core.
      commandShellGuidance(this.commandShell),
      // Session scratch directory (D114).
      ...(this.scratchDir
        ? [
            `Store ad-hoc temporary and intermediate files in the session scratch directory using ${shellScratchVariable(this.commandShell)}. Workspace writes must be task-related project files or required toolchain outputs. Scratch persists across turns and is deleted with the session.`,
          ]
        : []),
      // Inline visualizations (ADR gen-ui-inline-visualization).
      ...(this.visualizationsDir
        ? [
            `Visualization directory (absolute paths only, .html fragments only; see the ${GEN_UI_SKILL_ID} skill): \`${this.visualizationsDir}\``,
          ]
        : []),
      // Isolated session (ADR 0329).
      ...(this.workspaceRoot ? [isolatedWorkspaceGuidance()] : []),
    ];
    // A custom SYSTEM.md replaces only the product persona line, never the
    // operational rules in the default parts: tool guidance, delegation
    // steering and scratch mechanics keep the desktop working (issue #542).
    this.baseSystemPrompt = [
      (
        opts.customSystemPrompt?.replace ??
        opts.systemPrompt ??
        DEFAULT_RUNTIME_SYSTEM_PROMPT
      ).trim(),
      ...defaultSystemPromptParts.slice(1),
    ].join("\n\n");
    this.refreshToolDeclarationPolicy();
    this.restoreDeferredToolsFromContext();
    const tools = this.declaredTools();
    this.agent = new Agent({
      identity: DESKTOP_AGENT_IDENTITY,
      streamFn: (m, context, options) => {
        this.setAgentActivity({ phase: "waiting-model", since: Date.now() });
        this.providerResponseStatus = undefined;
        this.providerRetryHeaders = undefined;
        this.providerRequestBytes = undefined;
        this.providerRequestMessages = context.messages?.length;
        // Park what this request is expected to cost, so the usage report that
        // settles it can be measured against it (`contextBudget` corrects the
        // same shape).
        // The target model travels with the estimate: hosted search only
        // costs what this model's adapter will actually replay.
        this.inFlightContextEstimate = estimateContextTokens(
          context.messages ?? [],
          m,
        );
        // A new model request starts a new transport streak: the evidence that
        // justified a rebuild does not carry into the next request (issue #234).
        this.providerFetchFailure = undefined;
        this.providerTransportHealth.reset();
        const requestOptions: SimpleStreamOptions = withProviderHeaders(
          withOpenCodeSessionHeaders(
            {
              ...options,
              maxRetries: PROVIDER_REQUEST_MAX_RETRIES,
              sessionId: this.sessionId,
              // pi-ai only exposes onResponse after a request succeeds. Capture the
              // failed response separately so a 429 can honor Retry-After headers,
              // and capture the transport cause of a rejection while the original
              // Error still exists (issue #234).
              fetch: providerRequestFetch(
                m.api,
                captureProviderResponse(
                  options?.fetch,
                  (response, requestBytes, failure) => {
                    this.providerResponseStatus = response?.status;
                    this.providerRequestBytes = requestBytes;
                    this.providerFetchFailure = failure;
                    if (failure) this.recoverProviderTransport(failure);
                    // A gateway 502/503 can also state Retry-After, so keep headers
                    // for every status whose delay is usable, not only for 429.
                    this.providerRetryHeaders = carriesRetryDelayHeaders(
                      response?.status,
                    )
                      ? response?.headers
                      : undefined;
                  },
                ),
                this.provider.authKind,
              ),
              onResponse: async (response, responseModel) => {
                this.providerResponseStatus = response.status;
                await options?.onResponse?.(response, responseModel);
              },
            },
            {
              ...openCodeEndpointFromProvider(this.provider, m),
              sessionId: this.sessionId,
            },
          ),
          mergeProviderHeaders(
            copilotRequestHeaders(this.provider, context),
            this.provider.headers,
          ),
          m.api,
        );
        // Only main turns ask for the priority tier: subagents, compaction and
        // one-shot requests build their own options and keep the default.
        const hookedOptions = withFastModeOptions(
          withSessionAffinityOptions(
            this.withExtensionProviderHooks(
              withCodexCacheableInstructions(requestOptions, m),
              m,
            ),
            {
              provider: this.provider,
              api: m.api,
              baseUrl: m.baseUrl,
              sessionId: this.sessionId,
            },
          ),
          m.api,
          this.fastMode,
        );
        // Both output clamps, ours and pi-ai's inside `streamSimple`, must see
        // the instructions the adapter sends, not every superseded snapshot.
        const requestContext = requestTranscript(m, context);
        const attemptOptions: SimpleStreamOptions = {
          ...hookedOptions,
          // Cap the output budget at the pi-desktop layer so the estimate
          // holds for both adapter branches: `streamSimple` re-derives
          // max_tokens, but the low-level `stream` path used by
          // `thinkingLevel: "omit"` would otherwise send it untouched, and
          // both consume an estimate that under-counts CJK text (issue B).
          maxTokens: clampOutputToContext(m, requestContext, hookedOptions.maxTokens),
        };
        const usageTurnId = this.turnId;
        const openAttempt = (retryOptions: SimpleStreamOptions, input = requestContext) => {
          // Each network attempt owns its idle clock and abort signal.
          const stallAbort = new AbortController();
          const timedOptions = {
            ...retryOptions,
            signal: AbortSignal.any([
              ...(retryOptions.signal ? [retryOptions.signal] : []),
              stallAbort.signal,
            ]),
            ...(input !== requestContext && retryOptions.maxTokens !== undefined
              ? { maxTokens: clampOutputToContext(m, input, retryOptions.maxTokens) } : {}),
          };
          const stream = accountModelStream(m, () =>
            this.thinkingLevel === "omit"
              ? this.models.stream(omitThinkingModel(m), input, timedOptions)
              : this.models.streamSimple(m, input, timedOptions), {
              providerId: this.provider.id,
              nativeCost: this.provider.modelConfig?.nativeCost,
              onUsage: (usage) => this.emit({ type: "usage", usage }, usageTurnId),
            });
          return withStreamIdleTimeout(stream, m, streamIdleTimeoutMs(), () => stallAbort.abort());
        };
        const readPluginContext = opts.readPluginModelContext;
        const retryStream = createProviderRetryStream(
          m,
          requestContext,
          attemptOptions,
          readPluginContext && usageTurnId && this.activeTurnSettlements.has(usageTurnId)
            ? async (retryOptions) => {
                const signal = retryOptions.signal;
                const contributions = await readPluginContext({
                  sessionId: this.sessionId, turnId: usageTurnId,
                  modelKey: `${this.provider.id}/${m.id}`,
                }, signal).catch(() => undefined);
                signal?.throwIfAborted();
                const messages = this.turnId === usageTurnId && !this.runCancelled
                  ? withPluginModelContext(requestContext.messages, contributions)
                  : requestContext.messages;
                return openAttempt(retryOptions, messages === requestContext.messages
                  ? requestContext : { ...requestContext, messages });
              }
            : openAttempt,
          {
            claim: (error, phase) => this.claimProviderRetry(error, phase),
            headers: () => this.providerRetryHeaders,
            status: () => this.providerResponseStatus,
            failure: () => this.providerFetchFailure,
            onRetry: ({ error, attempt, delayMs }) => {
              this.setAgentActivity({
                phase: "retrying",
                since: Date.now(),
                attempt,
                ...(this.infiniteProviderRetry ? { infinite: true } : {}),
                retryDelayMs: delayMs,
                error: this.retryActivityError(error),
              });
            },
          },
        );
        return this.uniqueToolCalls(retryStream, context.messages);
      },
      // A vendor account has no long-lived key. Leaving it unset keeps pi-ai
      // from overriding the auth the provider just resolved for this request.
      getApiKey: async () => runtimeApiKey || undefined,
      // The provider's rule that a tool-call id is unique is enforced here, on
      // the last view before the wire: the request is the only place it can be
      // guaranteed for both a rebuilt context and one that grew in this process.
      convertToLlm: async (messages) => {
        await this.systemJournal.persist(messages, this.fullEntries, async (message) => {
          await this.host.call("session.appendMessage", {
            sessionId: this.sessionId, turnId: this.turnId, message,
          });
        });
        return alignRetainedReasoningIdentity(
          convertToLlm(this.dropDuplicateToolCalls(messages)), this.reasoningReplayIdentity(),
        );
      },
      prepareRequest: ({ context }) => this.prepareToolDeclarations(context),
      // Extensions see every provider request, including the first one of a
      // run, which `prepareNextTurn` never reaches (spec 16 §6, issue #1838).
      transformContext: (messages) => this.extensionContext(messages),
      prepareNextTurnWithContext: (context, signal) =>
        this.prepareNextTurn(context, signal),
      afterToolCall: async (context) => this.afterToolCall(context),
      initialState: {
        model,
        tools: [],
        thinkingLevel: agentThinkingLevel(this.thinkingLevel),
        messages: initialSystemTranscript(this.composeSystemPrompt(), tools, this.liveSessionContext().messages, this.composedSections),
      },
      // Plan transitions must be the only tool call in an assistant batch.
      // Sequential execution also makes the host-confirmed mode change visible
      // before the next model request in the same run.
      beforeToolCall: (context) => this.beforeToolCall(context),
      // pi prepares the entire parallel batch in source order before launching
      // execution. Any sequential member still makes the whole batch sequential.
      toolExecution: "parallel",
      steeringMode: "all",
      // pi-agent-core 0.87 replaces shouldStopAfterTurn with finishTurn. A
      // queued renderer prompt ends a completed turn at the next boundary,
      // without treating an error or abort as a graceful stop.
      finishTurn: async ({ message }) => {
        if (message.stopReason === "error" || message.stopReason === "aborted") return;
        // A paused run's turn has used its wrap-up requests (ADR mode-definitions).
        if (this.modeState.closeoutExhausted()) return { action: "end" };
        if (!this.gracefulStopRequested) return;
        this.gracefulStopRequested = false;
        return { action: "end" };
      },
    });

    // Avoid Pi inserting a tool-only baseline ahead of restored legacy rows.
    this.setAgentTools(tools);

    // pi awaits every listener, so a throw here would reject the run in
    // progress and, with nothing awaiting that rejection, could take the whole
    // sidecar down. Contain it: log with the session attached and let the
    // loop continue; a handler that failed on one event still sees the next.
    this.agent.subscribe((event) =>
      this.handleAgentEvent(event).catch((error: unknown) => {
        this.logEventHandlerFailure(event, error);
      }),
    );
  }

  private logEventHandlerFailure(event: AgentEvent, error: unknown): void {
    const detail =
      error instanceof Error
        ? `${error.name}: ${error.message}${error.stack ? `\n${error.stack}` : ""}`
        : String(error);
    process.stderr.write(
      `[agent-runtime] event handler failed (session=${this.sessionId} turn=${this.turnId} event=${event.type}): ${detail}\n`,
    );
  }

  /** Applied before the next prompt rebuilds its tool declarations. */
  setBackgroundJobContinuationEnabled(enabled: boolean): void {
    if (this.disposed) throw new Error("runtime disposed");
    this.backgroundJobContinuationEnabled = enabled;
  }

  /** Update the opt-in retry policy without rebuilding an idle runtime. */
  setInfiniteProviderRetry(enabled: boolean): void {
    if (this.disposed) throw new Error("runtime disposed");
    this.infiniteProviderRetry = enabled;
  }

  /** Apply the session `/fast` switch to the next turn of a reused runtime. */
  setFastMode(enabled: boolean): void {
    if (this.disposed) throw new Error("runtime disposed");
    this.fastMode = enabled;
  }

  /** Refresh catalog instructions without changing the running session owner. */
  setPluginSkills(skills: PluginSkillDef[]): void {
    if (this.disposed) throw new Error("runtime disposed");
    if (this.getStatus().isRunning) throw new Error("cannot update skills during an active turn");
    const sorted = [...skills].sort((left, right) => left.id.localeCompare(right.id));
    if (pluginSkillsDigest(this.pluginSkills) === pluginSkillsDigest(sorted)) return;
    this.pluginSkills = sorted;
    this.rebuildToolCatalog();
    this.setAgentTools(this.activeTools());
    this.setAgentSystemPrompt(this.composeSystemPrompt());
  }

  /**
   * Switch the mode (or its definition) on this Agent without creating
   * another Agent. Only the builtin Plan negotiates a proposal (D198); every
   * other mode's capabilities follow its tool policy level.
   */
  setMode(mode: Mode, definition?: ModeDefinition): void {
    if (this.disposed) throw new Error("runtime disposed");
    const kind = proposalKindForMode(mode);
    const previousMode = this.mode;
    const planningState: PlanningState = kind ? "planning" : "inactive";
    const details = kind ? { kind } : {};
    if (!this.modeState.setMode(mode, definition)) {
      this.setPlanningState(planningState, details);
      return;
    }
    if (this.mode !== previousMode || !this.modeState.isAgentLevel()) this.abortRunningDelegations();
    this.activeDeferredToolNames.clear();
    this.rebuildToolCatalog();
    this.restoreDeferredToolsFromContext();
    this.setAgentSystemPrompt(this.composeSystemPrompt());
    this.setAgentTools(this.activeTools());
    this.setPlanningState(planningState, details);
  }

  getMode(): Mode {
    return this.mode;
  }

  private agentUsesTranscriptSystemMessages(): boolean {
    let current: object | null = this.agent.state as unknown as object;
    while (current) {
      const descriptor = Object.getOwnPropertyDescriptor(current, "systemPrompt");
      if (descriptor) return typeof descriptor.get === "function" && !descriptor.set;
      current = Object.getPrototypeOf(current) as object | null;
    }
    return false;
  }

  private setAgentSystemPrompt(prompt: string): void {
    if (!this.agentUsesTranscriptSystemMessages()) {
      (this.agent.state as unknown as { systemPrompt: string }).systemPrompt = prompt;
      return;
    }
    this.agent.state.messages = prompt === this.composedSystemPrompt
      ? syncSystemSections(this.agent.state.messages, this.composedSections)
      : replaceSystemPrompt(this.agent.state.messages, prompt);
  }

  private setAgentMessages(messages: AgentMessage[]): void {
    if (!this.agentUsesTranscriptSystemMessages()) {
      this.agent.state.messages = messages;
      return;
    }
    this.agent.state.messages = rebuildSystemTranscript(
      this.agent.state.messages.filter((message) => message.role !== "system" || !this.systemJournal.isPersisted(message)), messages,
    );
  }

  /** Steering is consumed after next-turn preparation; sync before dispatch. */
  private prepareToolDeclarations(context: AgentContext): AgentLoopTurnUpdate {
    this.modeState.noteModelRequest();
    const tools = this.declaredTools();
    let messages = context.messages;
    const changes = getToolStateChanges(getCurrentTools(messages), tools.map(toToolDeclaration));
    if (changes.toolsAdded.length || changes.toolsRemoved.length) {
      messages = [...messages, {
        role: "system", content: "", ...changes, timestamp: Date.now(),
      }];
    }
    if (this.trackToolActivation && this.declarationPolicy) {
      messages = syncToolActivation(messages, toolActivationSection(
        this.declarationPolicy.key, this.activeDeferredToolNames,
      ));
    }
    for (const message of messages.slice(context.messages.length)) {
      this.agent.state.messages.push(message);
    }
    return { context: { ...context, messages, tools } };
  }

  private setAgentTools(tools: AgentTool[]): void {
    this.agent.state.tools = this.declarationPolicy?.tools ?? tools;
    if (this.trackToolActivation && this.declarationPolicy) {
      const section = toolActivationSection(this.declarationPolicy.key, this.activeDeferredToolNames);
      this.composedSections = { ...this.composedSections, [TOOL_ACTIVATION_SECTION]: section };
      this.composedSystemPrompt = Object.values(this.composedSections).filter(Boolean).join("\n\n");
      this.agent.state.messages = syncToolActivation(this.agent.state.messages, section);
    }
  }

  private agentSystemPromptContent(): string {
    return this.agentUsesTranscriptSystemMessages()
      ? systemPromptContent(this.agent.state.messages)
      : this.agent.state.systemPrompt;
  }

  private composeSystemPrompt(): string {
    const projectPrompt = projectInstructionsPrompt(this.projectInstructions);
    const memoryPrompt = projectMemoryPrompt(this.projectMemory);
    const optionalToolsPrompt = this.optionalToolsPrompt();
    this.composedSections = {
      runtime: this.baseSystemPrompt,
      ...(this.trackToolActivation && this.declarationPolicy ? {
        [TOOL_ACTIVATION_SECTION]: toolActivationSection(this.declarationPolicy.key, this.activeDeferredToolNames),
      } : {}),
      ...pluginSkillsPromptSections(this.pluginSkills),
      // The resumable-delegation list deliberately stays out: it changes on
      // every settlement, and a system-prompt change rewrites the request
      // prefix provider prompt caches key on (ADR 0337). `TaskList` carries it
      // instead, so the parent pays for it only when it reads it.
      context: composeModeSystemPrompt(this.mode, [
        ...(this.customSystemPrompt?.append ? [this.customSystemPrompt.append] : []),
        ...(optionalToolsPrompt ? [optionalToolsPrompt] : []),
        ...(projectPrompt ? [projectPrompt] : []),
        ...(memoryPrompt ? [memoryPrompt] : []),
        ...(this.scratchDir ? [
          `Your scratch directory for this session is \`${formatScratchDirForShell(this.commandShell, this.scratchDir)}\` (in Bash: ${shellScratchVariable(this.commandShell)}).`,
        ] : []),
      ].join("\n\n"), this.modeState.instructions()),
    };
    const composed = Object.values(this.composedSections).filter(Boolean).join("\n\n");
    this.composedSystemPrompt = composed;
    return composed;
  }
  /**
   * Host failures and mutation-failure termination are recorded per tool-call
   * id while the call runs; this is where they reach pi's tool-error channel.
   * Subagents reuse it so a delegate's host failure behaves like the parent's.
   */
  private resolveOwnToolOutcome({
    toolCall,
  }: AfterToolCallContext): SubagentToolOutcome | undefined {
    const terminate = this.terminatingToolCalls.delete(toolCall.id);
    const failed = this.failedHostToolCalls.delete(toolCall.id);
    const error = this.delegateMutationTerminations.get(toolCall.id);
    this.delegateMutationTerminations.delete(toolCall.id);
    if (!failed) return terminate ? { terminate: true } : undefined;
    return {
      isError: true,
      ...(terminate ? { terminate: true } : {}),
      ...(error ? { error } : {}),
    };
  }

  private async afterToolCall(
    context: AfterToolCallContext,
  ): Promise<AfterToolCallResult | undefined> {
    const own = this.resolveOwnToolOutcome(context);
    const fromExtensions = await this.extensionToolResult(context, own);
    if (!fromExtensions) return own;
    return { ...(own ?? {}), ...fromExtensions };
  }

  /** `tool_call` hook: an extension may block a call with a reason (spec 16 §6). */
  private async extensionToolCall(
    context: BeforeToolCallContext,
  ): Promise<BeforeToolCallResult | undefined> {
    const runner = this.extensionRunner;
    if (!runner?.hasHandlers("tool_call")) return undefined;
    const result = await runner.emit<BeforeToolCallResult>("tool_call", {
      type: "tool_call",
      toolName: context.toolCall.name,
      toolCallId: context.toolCall.id,
      input: context.args,
    }, (acc, next) => (acc?.block ? acc : next));
    if (!result?.block) return undefined;
    return { block: true, reason: result.reason ?? "blocked by a trusted extension" };
  }

  /** `tool_result` hook: an extension may replace content, details, or the error flag. */
  private async extensionToolResult(
    context: AfterToolCallContext,
    own: AfterToolCallResult | undefined,
  ): Promise<AfterToolCallResult | undefined> {
    const runner = this.extensionRunner;
    if (!runner?.hasHandlers("tool_result")) return undefined;
    const result = await runner.emit<AfterToolCallResult>("tool_result", {
      type: "tool_result",
      toolName: context.toolCall.name,
      toolCallId: context.toolCall.id,
      input: context.args,
      content: context.result.content,
      details: context.result.details,
      isError: own?.isError ?? context.isError,
    }, (acc, next) => ({ ...(acc ?? {}), ...next }));
    if (!result) return undefined;
    const out: AfterToolCallResult = {};
    if (result.content !== undefined) out.content = result.content;
    if (result.details !== undefined) out.details = result.details;
    if (result.isError !== undefined) out.isError = result.isError;
    return Object.keys(out).length ? out : undefined;
  }

  /**
   * `context` hook: extensions may rewrite the message list of one provider
   * request. The replacement only shapes that request; the run's working
   * context and the transcript keep the original messages.
   */
  private async extensionContext(messages: AgentMessage[]): Promise<AgentMessage[]> {
    const runner = this.extensionRunner;
    if (!runner?.hasHandlers("context")) return messages;
    const result = await runner.emit<{ messages?: AgentMessage[] }>(
      "context",
      { type: "context", messages },
      (_acc, next) => next,
    );
    return Array.isArray(result?.messages) ? result.messages : messages;
  }

  /** Mirror pi-agent-core events to extension handlers (spec 16 §6). */
  private forwardAgentEventToExtensions(event: AgentEvent): void {
    const runner = this.extensionRunner;
    if (!runner) return;
    const payload: Record<string, unknown> | undefined = (() => {
      switch (event.type) {
        case "agent_start":
          return { type: "agent_start" };
        case "agent_end":
          return { type: "agent_end", messages: (event as { messages?: unknown }).messages ?? [] };
        case "turn_start":
          this.extensionTurnIndex += 1;
          return { type: "turn_start", turnIndex: this.extensionTurnIndex, timestamp: Date.now() };
        case "turn_end":
          return {
            type: "turn_end",
            turnIndex: this.extensionTurnIndex,
            message: (event as { message?: unknown }).message,
            toolResults: (event as { toolResults?: unknown }).toolResults ?? [],
          };
        case "message_start":
        case "message_update":
        case "message_end":
          return { type: event.type, message: (event as { message?: unknown }).message };
        case "tool_execution_start":
        case "tool_execution_update":
        case "tool_execution_end":
          return { ...(event as unknown as Record<string, unknown>) };
        default:
          return undefined;
      }
    })();
    if (!payload || !runner.hasHandlers(payload.type as string)) return;
    void runner.emit(payload.type as any, payload);
  }

  private async beforeToolCall(
    context: BeforeToolCallContext,
  ): Promise<BeforeToolCallResult | undefined> {
    if (this.pendingSteering.size && context.toolCall.name !== SUBAGENT_WAIT_TOOL_NAME) {
      return { block: true, reason: "Skipped because new user input is waiting." };
    }
    if (this.deferredToolNames.has(context.toolCall.name) && !this.activeDeferredToolNames.has(context.toolCall.name)) {
      return { block: true, reason: `Call ${TOOL_SEARCH_NAME} to activate ${context.toolCall.name} before using it. A tool declaration does not grant execution permission.` };
    }
    const toolCalls = context.assistantMessage.content.filter((block) => block.type === "toolCall");
    const transition = MODE_TRANSITION_TOOL_NAMES.has(context.toolCall.name);
    const transitionInBatch = toolCalls.some((block) =>
      MODE_TRANSITION_TOOL_NAMES.has(block.name),
    );
    if (transitionInBatch && toolCalls.length !== 1) {
      return {
        block: true,
        reason: `${[...MODE_TRANSITION_TOOL_NAMES].join(", ")} must be the only tool call in the assistant message.`,
      };
    }
    if (!transition) {
      if (!this.isToolAllowedInMode(context.toolCall.name)) {
        return { block: true, reason: modeToolDenial(context.toolCall.name, this.mode) };
      }
      const blocked = await this.extensionToolCall(context);
      if (blocked?.block) return blocked;
      await this.preparePathToolCall(context);
      // Composer prefetches run serially outside the assistant's tool batches.
      if (!this.fileLineReadCalls.has(context.toolCall.id)) await this.registerBatchCall(context);
      // A later tool in the same model response may depend on Bash finishing.
      // Yield only when the next action can see and respond to the running job.
      if (context.toolCall.name === "Bash" && this.mode === "agent"
          && !this.remoteWorkspace && !this.delegateToolCalls.has(context.toolCall.id)
          && toolCalls.at(-1)?.id === context.toolCall.id) {
        this.bashYieldCalls.add(context.toolCall.id);
      }
      return undefined;
    }
    const enterKind = enterToolKind(context.toolCall.name);
    const submitKind = submitToolKind(context.toolCall.name);
    // Goal is a staged mode the user selects (ADR mode-definitions); its
    // legacy negotiation tools only survive in older transcripts.
    if (enterKind === "goal" || submitKind === "goal") {
      return {
        block: true,
        reason: `${context.toolCall.name} is no longer available. Goal mode is selected by the user and runs as a staged mode; continue in the current mode.`,
      };
    }
    if (enterKind && this.mode !== "agent") {
      return {
        block: true,
        reason: `${context.toolCall.name} is available only in Agent mode.`,
      };
    }
    if (submitKind && this.mode !== submitKind) {
      return {
        block: true,
        reason: `${context.toolCall.name} is available only in ${modeLabel(submitKind)} mode.`,
      };
    }
    return undefined;
  }

  private setPlanningState(
    state: PlanningState,
    details: {
      kind?: ProposalKind;
      proposalId?: string;
      title?: string;
      markdown?: string;
      question?: string;
      artifact?: PlanProposal["artifact"];
      version?: number;
      plan?: string;
      action?: "approve" | "reject";
      targetPermissionMode?: "ask" | "accept-edits" | "auto";
      executionId?: string;
      executionState?: PlanProposal["executionState"];
      proposal?: PlanProposal;
    } = {},
  ): void {
    this.planningState = state;
    this.pendingPlanId = details.proposalId;
    this.emit({ type: "planning_state", state, ...details });
  }

  /**
   * First reason this runtime cannot be reused for the given config, or null
   * when it matches. Field names are diagnostics, not API: they name the
   * comparison that failed so a rebuild can be attributed (#1948) instead of
   * leaving "why did my cache reset" unanswerable.
   */
  firstMismatch(config: RuntimeMatchConfig): string | null {
    const requestedPluginTools = config.pluginTools ?? [];
    const current = safeJson([...this.pluginTools].sort((a, b) => a.name.localeCompare(b.name)));
    const next = safeJson([...requestedPluginTools].sort((a, b) => a.name.localeCompare(b.name)));
    const currentThinkingLevels = [
      ...(this.provider.supportedThinkingLevels ?? ["off"]),
    ]
      .sort()
      .join(",");
    const nextThinkingLevels = [
      ...(config.provider.supportedThinkingLevels ?? ["off"]),
    ]
      .sort()
      .join(",");
    const extensionAgentMatches =
      Boolean(this.provider.extensionAgentKey) &&
      this.provider.extensionAgentKey === config.provider.extensionAgentKey &&
      this.provider.modelId === config.provider.modelId;
    // An extension agent is identified by its key and model alone; the other
    // provider fields belong to the plugin that declared it.
    if (!extensionAgentMatches) {
      const providerChecks: Array<[string, boolean]> = [
        ["provider.id", this.provider.id === config.provider.id],
        ["provider.modelId", this.provider.modelId === config.provider.modelId],
        ["provider.baseUrl", (this.provider.baseUrl ?? "") === (config.provider.baseUrl ?? "")],
        ["provider.apiKey", this.provider.apiKey === config.provider.apiKey],
        ["provider.authKind", this.provider.authKind === config.provider.authKind],
        ["provider.apiStyle", (this.provider.apiStyle ?? "") === (config.provider.apiStyle ?? "")],
        ["provider.headers", providerHeadersEqual(this.provider.headers, config.provider.headers)],
        ["provider.supportsReasoning", this.provider.supportsReasoning === config.provider.supportsReasoning],
        ["provider.supportedThinkingLevels", currentThinkingLevels === nextThinkingLevels],
        ["provider.modelConfig", safeJson(this.provider.modelConfig ?? null) === safeJson(config.provider.modelConfig ?? null)],
      ];
      for (const [field, ok] of providerChecks) {
        if (!ok) return field;
      }
    }
    const checks: Array<[string, boolean]> = [
      ["disposed", !this.disposed],
      ["mode", this.mode === config.mode],
      ["jevApiKey", this.jevApiKey === config.jevApiKey],
      // Turning computer use on or off changes the tool list, so the runtime
      // is retired rather than left advertising a stale set.
      ["computerUseEnabled", this.computerUseEnabled === (config.computerUseEnabled === true)],
      // Codemode changes the tool list as well.
      ["codemodeEnabled", this.codemodeEnabled === (config.codemodeEnabled === true)],
      ["thinkingLevel", this.thinkingLevel === clampThinkingLevel(config.provider, config.thinkingLevel)],
      ["pluginTools", current === next],
      ["commandShell", safeJson(this.commandShell) === safeJson(config.commandShell)],
      ["projectInstructions", safeJson(this.baseProjectInstructions ?? null) === safeJson(config.projectInstructions ?? null)],
      // Editing SYSTEM.md / APPEND_SYSTEM.md retires the runtime so the next
      // prompt recomposes from the fresh content.
      ["customSystemPrompt", safeJson(this.customSystemPrompt ?? null) === safeJson(config.customSystemPrompt ?? null)],
      ["projectMemory", (this.projectMemory ?? "") === (config.projectMemory?.trim() ?? "")],
      ["projectPath", (this.projectPath ?? "") === (config.remoteWorkspace?.path ?? config.projectPath?.trim() ?? "")],
      ["remoteWorkspace", safeJson(this.remoteWorkspace ?? null) === safeJson(config.remoteWorkspace ?? null)],
      ["workspaceRoot", (this.workspaceRoot ?? "") === (config.workspaceRoot?.trim() ?? "")],
      // Editing `~/.agents/subagents/*.md` must reach the next prompt. Definition
      // bodies are part of the `Task` tool's behavior, so unlike skills they
      // are compared in full.
      ["subagents", safeJson(this.subagents) === safeJson(config.subagents ?? [])],
      ["subagentProviders", safeJson(this.subagentProviders) === safeJson(config.subagentProviders ?? {})],
      ["subagentModelKeys", safeJson([...this.subagentModelKeys].sort()) === safeJson([...new Set(config.subagentModelKeys ?? [])].sort())],
      // Enabling or disabling a trusted extension retires the runtime so the
      // next prompt reloads the set (spec 16 §4.3).
      ["trustedExtensions", trustedExtensionIds(this.trustedExtensionSpecs) === trustedExtensionIds(config.trustedExtensions ?? [])],
    ];
    for (const [field, ok] of checks) {
      if (!ok) return field;
    }
    return null;
  }

  /** True when this runtime can be reused for a prompt with the given config. */
  matches(config: RuntimeMatchConfig): boolean {
    return this.firstMismatch(config) === null;
  }

  /**
   * Load the enabled trusted extensions (D387). Called once by the sidecar
   * after construction; a failing entry is reported through diagnostics and
   * never fails the session.
   */
  async loadTrustedExtensions(): Promise<void> {
    if (this.disposed || this.extensionRunner || this.trustedExtensionSpecs.length === 0) return;
    if (this.trustedExtensionLoad) return this.trustedExtensionLoad;
    const loading = this.loadTrustedExtensionsForSession();
    this.trustedExtensionLoad = loading;
    try {
      await loading;
    } finally {
      if (this.trustedExtensionLoad === loading) this.trustedExtensionLoad = undefined;
    }
  }

  private async loadTrustedExtensionsForSession(): Promise<void> {
    const { TrustedExtensionRunner } = await import("./extensions/runner.js");
    if (this.disposed || this.extensionRunner || this.trustedExtensionSpecs.length === 0) return;
    const runner = new TrustedExtensionRunner({
      specs: this.trustedExtensionSpecs,
      bridge: this.createExtensionBridge(),
      reservedToolNames: () => this.toolCatalog.keys(),
    });
    this.extensionRunner = runner;
    await runner.load();
    if (this.disposed) return;
    this.rebuildToolCatalog();
    this.setAgentTools(this.activeTools());
  }

  /** Run a registered extension slash command in this session (spec 16 §8). */
  async runTrustedExtensionCommand(name: string, args: string): Promise<{ handled: boolean }> {
    if (!this.extensionRunner) return { handled: false };
    return { handled: await this.extensionRunner.runCommand(name, args) };
  }

  private extensionProviderFor(agent: RegisteredTrustedExtensionAgent, model: Model<Api>): RuntimeProviderConfig {
    const supportedThinkingLevels: ThinkingLevel[] = model.reasoning
      ? ["off", "low", "medium", "high"]
      : ["off"];
    return {
      id: agent.providerId,
      name: agent.name,
      modelId: model.id,
      apiKey: "",
      authKind: "none",
      extensionAgentKey: agent.key,
      supportsReasoning: model.reasoning,
      supportedThinkingLevels,
      modelConfig: genericModelConfig(model.id, ""),
    };
  }

  private applyExtensionAgent(agent: RegisteredTrustedExtensionAgent, model: Model<Api>): void {
    // `/fast` was authorized for the model the session launched with: Main only
    // sends it when that binding has `fastModeAllowed` (ADR 0334). An extension
    // model has no such opt-in, so switching to it must not carry the priority
    // tier along. The next launch re-applies the switch from the session's
    // stored model through `setFastMode`.
    this.fastMode = false;
    this.provider = this.extensionProviderFor(agent, model);
    this.model = model;
    this.models = createExtensionAgentModels({
      providerId: agent.providerId,
      providerName: agent.name,
      model,
      stream: { stream: agent.stream, streamSimple: agent.stream },
    });
    this.thinkingLevel = clampThinkingLevel(this.provider, this.thinkingLevel);
    this.agent.state.model = model;
    this.agent.state.thinkingLevel = agentThinkingLevel(this.thinkingLevel);
  }

  async activateTrustedExtensionAgent(agentKey: string, modelId: string): Promise<boolean> {
    const found = this.extensionRunner?.findAgent(agentKey, modelId);
    if (!found) return false;
    this.applyExtensionAgent(found.agent, found.model);
    return true;
  }

  private async setExtensionModel(model: unknown, signal?: AbortSignal): Promise<boolean> {
    if (!this.extensionRunner || !this.isIdle()) return false;
    const agent = this.extensionRunner.findAgentModel(model);
    if (!agent) return false;
    const modelId = model && typeof model === "object" && typeof (model as { id?: unknown }).id === "string"
      ? (model as { id: string }).id
      : "";
    const candidate = agent.models.find((item) => item.id === modelId);
    if (!candidate) return false;
    try {
      const result = await this.host.call<{ ok?: boolean }>("extensions.model.configure", {
        sessionId: this.sessionId,
        mode: this.mode,
        providerId: agent.providerId,
        modelId: candidate.id,
        thinkingLevel: this.thinkingLevel,
      });
      if (signal?.aborted || this.disposed || result?.ok === false) return false;
      this.applyExtensionAgent(agent, candidate);
      return true;
    } catch {
      return false;
    }
  }

  private isIdle(): boolean {
    return !this.agent.state.isStreaming;
  }

  private extensionModelRegistry(): Record<string, unknown> {
    const getRunner = () => this.extensionRunner;
    const models = () => [this.model, ...(getRunner()?.getAgentModels() ?? [])];
    const hasConfiguredProvider = (providerId: string) =>
      providerId === this.provider.id ||
      providerId === this.model.provider ||
      (getRunner()?.getAgents().some((agent) => agent.providerId === providerId) ?? false);
    return {
      getAll: () => [...new Map(models().map((model) => [`${model.provider}/${model.id}`, model])).values()],
      getAvailable: () => [...new Map(models().map((model) => [`${model.provider}/${model.id}`, model])).values()],
      find: (providerId: string, modelId: string) =>
        models().find((model) => model.provider === providerId && model.id === modelId),
      getProviderDisplayName: (providerId: string) =>
        getRunner()?.getAgents().find((agent) => agent.providerId === providerId)?.name ??
        (providerId === this.provider.id ? this.provider.name : providerId),
      getProviderAuthStatus: (providerId: string) => ({
        configured: hasConfiguredProvider(providerId),
        source: "plugin",
      }),
      hasConfiguredAuth: (model: { provider?: string }) =>
        typeof model.provider === "string" && hasConfiguredProvider(model.provider),
    };
  }

  getTrustedExtensionReports() {
    return this.extensionRunner?.getLoadReports() ?? [];
  }
  /**
   * The working directory extensions see: the project root, or the session
   * scratch for a temporary session. Scratch is otherwise created lazily by the
   * first host tool call (D114), so it is created here; a failure leaves the
   * path in place, because loading extensions must not fail the session.
   */
  private extensionCwd(): string {
    const root = this.workspaceRoot ?? this.projectPath;
    if (root) return root;
    if (!this.scratchDir) return process.cwd();
    try {
      mkdirSync(this.scratchDir, { recursive: true });
    } catch {
      // pi.exec reports the missing directory itself.
    }
    return this.scratchDir;
  }

  private createExtensionBridge(): TrustedExtensionBridge {
    const runtime = this;
    return {
      sessionId: this.sessionId,
      cwd: this.extensionCwd(),
      remoteWorkspace: Boolean(this.remoteWorkspace),
      getModel: () => runtime.model,
      setModel: (model, signal) => runtime.setExtensionModel(model, signal),
      modelRegistry: runtime.extensionModelRegistry(),
      getThinkingLevel: () => agentThinkingLevel(runtime.thinkingLevel),
      setThinkingLevel: (level) => {
        runtime.thinkingLevel = clampThinkingLevel(runtime.provider, level as ThinkingLevel);
        runtime.agent.state.thinkingLevel = agentThinkingLevel(runtime.thinkingLevel);
      },
      isIdle: () => !runtime.agent.state.isStreaming,
      abort: () => {
        void runtime.abort();
      },
      hasPendingMessages: () => false,
      getContextUsage: () => {
        const budget = runtime.contextBudget(runtime.agent.state.messages);
        return {
          tokens: budget.tokens,
          contextWindow: budget.hardLimit,
          percent: budget.hardLimit > 0 ? Math.round((budget.tokens / budget.hardLimit) * 100) : null,
          autoCompactAt: runtime.compactionEnabled ? automaticCompactionThresholdFor(budget) : null,
        };
      },
      compact: () => {
        runtime.pendingModelCompaction = true;
      },
      getSystemPrompt: () => runtime.agent.state.systemPrompt,
      getActiveTools: () => runtime.activeTools().map((tool) => tool.name),
      getAllTools: () => {
        const active = new Set(runtime.activeTools().map((tool) => tool.name));
        return [...runtime.toolCatalog.values()].map((tool) => ({
          name: tool.name,
          description: tool.description,
          active: active.has(tool.name),
        }));
      },
      setActiveTools: (names) => {
        const wanted = new Set(names);
        for (const name of runtime.deferredToolNames) {
          if (wanted.has(name)) runtime.activeDeferredToolNames.add(name);
          else runtime.activeDeferredToolNames.delete(name);
        }
        runtime.setAgentTools(runtime.activeTools());
      },
      getSessionName: () => runtime.extensionSessionName,
      setSessionName: async (name, signal) => {
        await runtime.host.call("session.rename", { id: runtime.sessionId, title: name });
        if (signal?.aborted || runtime.disposed) return;
        runtime.extensionSessionName = name;
        void runtime.extensionRunner?.emit("session_info_changed", {
          type: "session_info_changed",
          name,
        });
      },
      sendUserMessage: async (content, options, signal) => {
        const text = Array.isArray(content)
          ? content
              .map((part) => (isRecord(part) && typeof part.text === "string" ? part.text : ""))
              .join("")
          : String(content);
        // Host-owned queue (D386): Electron main routes this to the Agent
        // Host module, which drains it at the next turn boundary, or right
        // away when the session is idle. `steer` moves it to the head.
        const pushed = await runtime.host.call<{ id?: string }>("session.queuePush", {
          sessionId: runtime.sessionId,
          idempotencyKey: randomUUID(),
          content: text,
        });
        if (!signal?.aborted && !runtime.disposed && options?.deliverAs === "steer" && pushed?.id) {
          await runtime.host
            .call("session.queuePrioritize", { sessionId: runtime.sessionId, id: pushed.id })
            .catch(() => undefined);
        }
      },
      waitForIdle: () => runtime.agent.waitForIdle(),
      newSession: async () => {
        try {
          await runtime.host.call("session.create", {
            projectPath: runtime.projectPath,
            mode: runtime.mode,
          });
          return { cancelled: false };
        } catch {
          return { cancelled: true };
        }
      },
      fork: async (entryId) => {
        try {
          await runtime.host.call("session.fork", {
            sessionId: runtime.sessionId,
            throughMessageId: entryId || undefined,
          });
          return { cancelled: false };
        } catch {
          return { cancelled: true };
        }
      },
      requestUi: (extension, request, signal) => requestExtensionUi(
        (envelope) => runtime.host.call<TrustedExtensionUiResponse>("extensions.ui.request", envelope), {
          sessionId: runtime.sessionId,
          extensionId: extension.id,
          extensionLabel: extension.label,
          request,
        }, signal),
      publishCommands: (commands: TrustedExtensionCommand[]) => {
        void runtime.host
          .call("extensions.commands.publish", { sessionId: runtime.sessionId, commands })
          .catch(() => undefined);
      },
      publishDiagnostics: (diagnostics: TrustedExtensionDiagnostic[]) => {
        void runtime.host
          .call("extensions.diagnostics.publish", {
            sessionId: runtime.sessionId,
            diagnostics,
            reports: runtime.extensionRunner?.getLoadReports() ?? [],
          })
          .catch(() => undefined);
      },
    };
  }

  /* Rebuild pi-ai messages from the persisted transcript, including tool
   * call/result pairs and hosted-search replay blocks. Tool rows persist
   * toolCallId/toolName/toolArgs and the result (including deferred-tool
   * activation markers). Hosted search persists the adapter's raw content
   * parts on `hostedSearch.replay` so Anthropic/Responses can ground later
   * turns after a restart. Losing either (the pre-D120 tool behavior)
   * collapsed a reseeded session to bare chat text. Failed assistant turns
   * stay transcript-only. */
  private historyToEntries(history: UiMessage[], compactionThroughMessageId?: string): MessageEntry[] {
    const api = apiBindingForProviderModel(this.provider).api;
    const deepSeekCompletionsReplay =
      api === "openai-completions" &&
      (
        this.model.compat as
          | { requiresReasoningContentOnAssistantMessages?: boolean }
          | undefined
      )?.requiresReasoningContentOnAssistantMessages === true;
    const entries: MessageEntry[] = [];
    const append = (id: string, message: AgentMessage): MessageEntry => {
      const entry: MessageEntry = {
        type: "message",
        id,
        seq: entries.length,
        parentId: entries.at(-1)?.id ?? null,
        timestamp: timestampMs(message.timestamp),
        message,
      };
      entries.push(entry);
      return entry;
    };
    // Tool rows attach their calls to the assistant message that made them
    // (the nearest one above), keeping each call adjacent to its result as
    // the provider APIs require.
    let toolCarrier: AssistantMessage | undefined;
    // Function-call signatures of the carrier's row, restored by call id.
    let carrierToolSignatures = new Map<string, string>();
    let compactedCarrier: AssistantMessage | undefined;
    let previousRowId: string | undefined;
    for (const m of orderSystemRows(history)) {
      // A carrier before this boundary is removed by context compaction. Tool
      // rows after it must reconstruct their calls on a surviving carrier.
      if (compactionThroughMessageId && previousRowId === compactionThroughMessageId) {
        compactedCarrier = toolCarrier;
        toolCarrier = undefined;
      }
      previousRowId = m.id;
      // Subagent rows belong to the transcript and to review, never to the
      // parent's model context (ADR 0062): the parent only ever saw the `Task`
      // report, and replaying a delegate's messages would both contradict that
      // and reintroduce the context cost delegation exists to avoid.
      if (m.parentToolCallId) continue;
      // Calls a codemode script made are transcript children of the script's
      // call. The model only ever saw the script's own result, and these rows
      // have no issuing assistant call to attach to (ADR codemode-sandbox-boundary).
      if (m.nestedParentToolCallId) continue;
      const timestamp = Date.parse(m.createdAt) || Date.now();
      if (m.role === "system" && m.modelSystem) {
        // An update recorded while a tool ran sits between the call and its
        // result. It keeps the carrier: Pi holds the update until the results
        // are written, which is the shape the live request had.
        append(m.id, this.systemJournal.restore(m));
      } else if (m.role === "user") {
        toolCarrier = undefined;
        compactedCarrier = undefined;
        const attachments = (m.attachments ?? []).map((attachment) =>
          runtimeAttachmentFromMessage(
            attachment,
            attachment.data,
          ),
        );
        const content = promptContent({
          text: m.sessionMessage ? formatSessionMessage(m.content, m.sessionMessage) : m.content,
          attachments,
        });
        if (
          !(m.content || "").trim() &&
          !attachments.some((attachment) => attachment.data)
        ) {
          continue;
        }
        append(m.id, { role: "user", content, timestamp });
      } else if (m.role === "assistant") {
        toolCarrier = undefined;
        compactedCarrier = undefined;
        // Failed provider responses belong in the transcript for diagnosis,
        // but must never become model context on the next turn.
        if (m.status === "error" || m.isError || m.error) continue;
        const content: AssistantMessage["content"] = [];
        // A replay placeholder the model echoed is not its reasoning; sending
        // it back is what kept the model continuing it (#1945).
        const rawThinking = m.thinking ?? "";
        const thinking = withoutReasoningReplayPlaceholder(rawThinking);
        // Signed blocks restore the request the live runtime sent, so a
        // rebuild keeps the provider's prompt cache (#1972). Rows that were
        // cleaned above, or whose text no longer matches, keep the plain path.
        const replayed = thinking === rawThinking
          ? restoreAssistantProviderReplay(m.providerReplay, rawThinking, m.content ?? "")
          : undefined;
        if (replayed) {
          const firstText = replayed.findIndex((block) => block.type === "text");
          const hosted = restoreHostedSearchReplay(m.hostedSearch);
          if (firstText < 0) content.push(...replayed, ...hosted);
          else content.push(...replayed.slice(0, firstText), ...hosted, ...replayed.slice(firstText));
        } else {
          if (thinking.trim()) {
            // Completions DeepSeek replay needs thinkingSignature so convertMessages
            // maps the block to reasoning_content instead of dropping it (#296).
            content.push({
              type: "thinking" as const,
              thinking,
              ...(deepSeekCompletionsReplay
                ? { thinkingSignature: "reasoning_content" as const }
                : {}),
            });
          }
          content.push(...restoreHostedSearchReplay(m.hostedSearch));
          if (m.content?.trim()) {
            content.push({ type: "text" as const, text: m.content });
          }
        }
        // Kept even when empty: a call-only turn has no text of its own and
        // becomes the carrier for the tool rows that follow. Assistants that
        // end up with no content and no calls are dropped at the end.
        const assistant: AssistantMessage = {
          role: "assistant",
          content,
          api,
          // Persisted providerId identifies a local account; Pi compares its
          // vendor identity to decide whether native thinking can be replayed.
          // Keep known account/model switches distinct; legacy rows have no
          // source identity and retain the existing current-model fallback.
          provider: !m.providerId || m.providerId === this.provider.id
            ? this.model.provider : m.providerId,
          model: m.modelId || this.model.id,
          usage: usageToPi(m.usage),
          stopReason: "stop",
          timestamp,
        };
        append(m.id, assistant);
        toolCarrier = assistant;
        carrierToolSignatures = providerReplayToolCallSignatures(m.providerReplay);
      } else if (m.role === "tool") {
        if (!m.toolCallId || !m.toolName) continue;
        if (!toolCarrier) {
          // Tool row whose assistant row was lost (truncated branch):
          // synthesize a carrier so the call/result pair stays well-formed.
          toolCarrier = {
            role: "assistant",
            content: [],
            api: compactedCarrier?.api ?? api,
            provider: compactedCarrier?.provider ?? this.model.provider,
            model: compactedCarrier?.model ?? this.model.id,
            usage: usageToPi(undefined),
            stopReason: "toolUse",
            timestamp,
          };
          append(`${m.id}:carrier`, toolCarrier);
          if (!compactedCarrier) carrierToolSignatures = new Map();
          compactedCarrier = undefined;
        }
        const thoughtSignature = carrierToolSignatures.get(m.toolCallId);
        toolCarrier.content.push({
          type: "toolCall",
          id: m.toolCallId,
          name: m.toolName,
          arguments: toJsonObject(m.toolArgs),
          ...(thoughtSignature ? { thoughtSignature } : {}),
        });
        toolCarrier.stopReason = "toolUse";
        append(m.id, toolResultFromUi(m, timestamp));
      }
    }
    return entries.filter(
      (entry) =>
        // An empty call-only boundary still anchors the persisted checkpoint.
        entry.id === compactionThroughMessageId ||
        entry.message.role !== "assistant" || entry.message.content.length > 0,
    );
  }

  /**
   * A `tool_use` id has to be unique across the request: Anthropic-family
   * endpoints (DeepSeek's included) reject the whole turn with "tool_use ids
   * must be unique" (issue #718), and a session that hits that 400 cannot
   * continue. Every message the next request carries passes through here, so
   * this is the one place that can guarantee the provider's rule for both a
   * rebuilt context and one that grew during this process.
   *
   * The transcript is append-only and tolerates a retried append, so the same
   * call can reach the request twice: under the same row id (which the host's
   * keep-last dedupe already collapses) or a new one (which it cannot). The
   * first pending occurrence wins; a later completed pair is retained under
   * a fresh request id. New streamed executions are normalized before they
   * reach this guard or the journal. What was dropped is logged with its ids,
   * because the next report should name the writer instead of only the
   * provider's sentence.
   */
  private dropDuplicateToolCalls(messages: AgentMessage[]): AgentMessage[] {
    const drop = dedupeToolCallMessages(messages);
    reportDuplicateToolCallDrop(this.sessionId, drop);
    return drop.messages;
  }

  private entriesWithCompaction(
    checkpoint: ContextCompactionRecord | undefined = this.activeCompaction,
  ): Entry[] {
    const entries: Entry[] = [...this.fullEntries];
    if (!checkpoint) return entries;
    if (isRecord(checkpoint.details) && checkpoint.details.systemMessageJson) {
      this.systemJournal.rememberCheckpoint(checkpoint.details.systemMessageJson);
    }
    const throughIndex = entries.findIndex(
      (entry) => entry.id === checkpoint.throughMessageId,
    );
    if (throughIndex < 0) return entries;
    const compactionEntry: CompactionEntry = {
      type: "compaction",
      id: checkpoint.id,
      seq: throughIndex + 1,
      parentId: checkpoint.throughMessageId,
      timestamp: timestampMs(checkpoint.createdAt),
      summary: checkpoint.summary,
      tokensBefore: checkpoint.tokensBefore,
      // pi 0.84 dereferences `retainedTail` unconditionally when it finds a
      // previous compaction entry, so a checkpoint restored without a usable
      // tail has to read as empty rather than absent.
      retainedTail:
        retainedTailForContext(checkpoint.retainedTail, checkpoint.details) ??
        [],
      details: toJsonValue(checkpoint.details),
      // Desktop-owned checkpoints are not pi extension-hook compactions.
      fromHook: false,
      usage: checkpoint.usage as Usage | undefined,
    };
    entries.splice(throughIndex + 1, 0, compactionEntry);
    // Inserting mid-path breaks the seq/position correspondence the rest of
    // this file maintains. Renumber into fresh objects: `this.fullEntries`
    // holds the live entries and must not be mutated through the copy.
    return entries.map((entry, seq) =>
      entry.seq === seq ? entry : { ...entry, seq },
    );
  }

  private appendLiveEntry(id: string, message: AgentMessage): void {
    if (!id || this.fullEntries.some((entry) => entry.id === id)) return;
    this.fullEntries.push({
      type: "message",
      id,
      seq: this.fullEntries.length,
      parentId: this.fullEntries.at(-1)?.id ?? null,
      timestamp: timestampMs(message.timestamp),
      message,
    });
  }

  private buildToolDefinitions(): AgentTool[] {
    // With a scratch dir provisioned, file tools accept absolute paths into
    // it as a second root (D114); keep the wording in sync with host-core.
    const scratchPathHint = this.scratchDir
      ? " `path` is workspace-relative, or an absolute path inside the session scratch directory."
      : "";
    const externalPathHint =
      " An explicit path outside the workspace and session scratch roots requires permission unless the effective mode is Auto.";
    const describe = (toolName: string): string => {
      if (toolName === "GenerateImages") return imageGenerationDescription;
      if (toolName === "Computer") return computerUseDescription;
      if (scheduledToolDescriptions[toolName]) return scheduledToolDescriptions[toolName];
      switch (toolName) {
        case "BrowserPreview":
          return "Open an HTML file in PI-Desktop's built-in browser panel. `path` may be relative to a project folder or this session's scratch directory, or an absolute path inside those roots. No project is required for scratch previews. The preview live-reloads on later edits to the file or its sibling assets, so call once per page.";
        case "Read":
          return (
            "Read a bounded window from an existing regular text file, never a directory. " +
            "The result always includes `totalLines` so you know the file\'s scale upfront. " +
            "`content` is line-numbered (`N:`) under a `[path#TAG]` header; `tag` is the whole-file 4-hex Edit anchor. " +
            "`truncated` is true only when this window was cut short, not merely because the file continues. " +
            "For files beyond the default window, use Grep to locate the target content first, then Read " +
            "the relevant range with `offset` and `limit`. Activate and use Glob " +
            "when a directory must be listed or the file name is uncertain." +
            `${scratchPathHint}${externalPathHint}`
          );
        case "Glob":
          return (
            "List files by glob pattern, newest first. Use `path` to scope the " +
            "directory and `limit` to bound results; patterns use `/` as a " +
            "portable separator." +
            `${scratchPathHint}${externalPathHint}`
          );
        case "Grep":
          return (
            "Search file contents with a Rust-compatible regex. `path` may name one file " +
            "or a directory tree. Use `path` and " +
            "`include` to narrow the scan, `headLimit` to bound results, and " +
            'outputMode: "filesWithMatches" or "count" when content is unnecessary; ' +
            "`path` accepts portable relative paths." +
            `${scratchPathHint}${externalPathHint}`
          );
        case "Write":
          return `Create or overwrite a file. Deliverables go into the workspace; temporary/intermediate files go into the scratch directory.${scratchPathHint}${externalPathHint}`;
        case "Edit":
          return `Replace, insert, or delete lines in an existing file. Names positions and supplies new content only — never old_string. Required: path, tag (4 hex from the latest Read/Grep/Write/Edit), ops. Ops: PUT N.=M: replace inclusive lines N–M; PUT <N: insert before N; PUT >N: insert after N; PUT >$: append; CUT N.=M delete; REM delete the file; MV DEST rename after other ops. Body rows are + plus the final line text. Every PUT with body rows must include the trailing colon, for example PUT 48.=48:; PUT 48.=48 followed by + rows is invalid. A colonless PUT is only for a register paste such as PUT <1 @name. No -old or context rows. Ranges name only the lines being changed. Re-ground on the tag returned by every successful write. After one failed Edit, classify the error: Read the live file for a stale tag or unseen lines (or retry unchanged on a complete EDIT_LINES_UNSEEN reveal), but correct syntax or range errors directly; do not guess. Do not edit the same path concurrently.${scratchPathHint}${externalPathHint}`;
        case "Bash":
          return `${commandShellToolDescription(this.commandShell, this.scratchDir)} Use Edit or Write instead of apply_patch, git apply, or patch; do not retry a failed shell patch command repeatedly.`;
        case "TodoWrite":
          return todoWriteDescription;
        case ASK_TOOL_NAME:
          return `Ask the user one or more questions. Keep each question to ${MAX_ASK_TOOL_QUESTION_CHARS} characters or fewer. Use Markdown in question text and option labels when formatting helps (for example, emphasis, inline code, or lists); the desktop card renders it safely. Plain strings and existing { label, description? } options are accepted; descriptions remain plain text and answers return the selected source label. The card always provides a custom user-input option.`;
        case "PluginScaffold":
          return "Create a PI-Desktop plugin from a template and load it for development. `directory` is workspace-relative and must be empty or new; `template` is one of panel-basic, agent-tool-basic, skill-pack, full-demo. Use this instead of hand-writing plugin files.";
        case "PluginCheck":
          return "Validate a PI-Desktop plugin directory against every rule the installer enforces (manifest, entry file, panel, skills, permissions, package limits). `directory` is workspace-relative. Run this before packaging.";
        case "PluginPack":
          return "Package a PI-Desktop plugin directory into an installable dist/<id>-<version>.piplug. `directory` is workspace-relative. Runs the same validation as PluginCheck first and refuses to package a plugin with errors. Never build a .piplug with shell tools — the installer only accepts uncompressed archives.";
        default:
          return `${toolName} tool via PI-Desktop host-core`;
      }
    };
    // One entry per tool: the shapes diverge enough that a chain of ternaries
    // stopped being readable.
    const parameters: Record<string, Parameters<typeof Type.Object>[0]> = {
      GenerateImages: imageGenerationParameters,
      Computer: computerUseParameters,
      TodoWrite: todoWriteParameters,
      Read: {
        path: pathParam(
          "Existing regular file only, never a directory; workspace-relative or explicitly approved.",
        ),
        file_path: aliasParam("path"),
        offset: Type.Optional(
          Type.Number({ minimum: 0, description: "0-based line offset; defaults to 0." }),
        ),
        limit: Type.Optional(
          Type.Number({ minimum: 1, description: "Maximum lines to return; defaults to 2000." }),
        ),
      },
      BrowserPreview: {
        path: pathParam("File to preview inside the session's project folders or scratch directory."),
        file_path: aliasParam("path"),
      },
      Glob: {
        pattern: pathParam("Glob pattern, for example **/*.ts."),
        query: aliasParam("pattern"),
        path: Type.Optional(
          Type.String({
            description:
              "Directory to search; defaults to the workspace root and accepts an absolute scratch path.",
          }),
        ),
        limit: Type.Optional(
          Type.Number({ minimum: 1, description: "Maximum entries; defaults to 100." }),
        ),
      },
      Grep: {
        pattern: pathParam("Rust-compatible regex matched per line."),
        query: aliasParam("pattern"),
        path: Type.Optional(
          Type.String({
            description:
              "File or directory to search; defaults to the workspace root and accepts an absolute scratch path.",
          }),
        ),
        include: Type.Optional(
          Type.String({ description: "Glob filter, for example **/*.{ts,tsx}." }),
        ),
        outputMode: Type.Optional(
          Type.Union([
            Type.Literal("content"),
            Type.Literal("filesWithMatches"),
            Type.Literal("count"),
          ]),
        ),
        headLimit: Type.Optional(
          Type.Number({ minimum: 1, description: "Maximum matches or files; defaults to 200." }),
        ),
        caseInsensitive: Type.Optional(Type.Boolean()),
      },
      Write: {
        path: pathParam("File to write; workspace-relative."),
        file_path: aliasParam("path"),
        content: Type.String(),
      },
      Edit: {
        path: pathParam("File to edit; workspace-relative."),
        file_path: aliasParam("path"),
        tag: Type.Optional(
          Type.String({
            description:
              "4 uppercase hex from the latest Read, Grep, Write, or Edit for this path. Required unless legacy old_string/new_string is used.",
          }),
        ),
        ops: Type.Optional(
          Type.String({
            description:
              "One or more operation headers with + body rows, newline separated. A PUT with body rows must end its header with `:` (for example, `PUT 48.=48:`); `PUT 48.=48` followed by + rows is invalid. A colonless PUT is only for a register paste such as `PUT <1 @name`. Required unless legacy old_string/new_string is used.",
          }),
        ),
        old_string: Type.Optional(
          Type.String({
            description:
              "Legacy text replacement: exact text to be replaced (must match exactly once in the target file).",
          }),
        ),
        new_string: Type.Optional(
          Type.String({
            description:
              "Legacy text replacement: new text to replace old_string with.",
          }),
        ),
      },
      Bash: {
        command: Type.String(),
        timeout: Type.Optional(
          Type.Number({
            minimum: MIN_COMMAND_TIMEOUT_SECONDS,
            // Models routinely send milliseconds; a wider schema bound lets the
            // runtime read the intent instead of burning the turn (D273 / D329).
            maximum: MAX_ACCEPTED_COMMAND_TIMEOUT,
            description:
              `Optional command timeout in seconds from 1 to ${MAX_COMMAND_TIMEOUT_SECONDS}; defaults to 60 seconds.`,
          }),
        ),
        ...(this.backgroundJobContinuationEnabled && this.mode === "agent" && !this.remoteWorkspace ? {
          notifyOnExit: Type.Optional(Type.Boolean({ description: "With runInBackground, arrange automatic delivery to this conversation after a finite test/build completes, even after the current turn ends. No extra approval; existing permissions still apply. Do not use for servers/watchers. TaskWait may still collect the result first." })),
        } : {}),
        runInBackground: Type.Optional(
          Type.Boolean({
            description:
              "Start the command as a background task that outlives the turn (dev servers, watchers, builds). Returns backgroundTaskId immediately; ignored with timeout.",
          }),
        ),
      },
      PluginScaffold: {
        template: Type.String(),
        directory: Type.String(),
        id: Type.Optional(Type.String()),
        name: Type.Optional(Type.String()),
      },
      PluginCheck: { directory: Type.String() },
      PluginPack: { directory: Type.String() },
    };
    const exec = (toolName: string): AgentTool => {
      const run: AgentTool["execute"] = async (
        toolCallId,
        params,
        signal,
        onUpdate,
      ) => {
        const mutationPath = PATH_MUTATING_TOOLS.has(toolName) && isRecord(params) && typeof params.path === "string"
          ? this.remoteWorkspace
            ? remoteMutationIdentity(this.remoteWorkspace, params.path)
            : await mutationFailureKey(
                params.path,
                this.workspaceRoot ?? this.projectPath ?? this.scratchDir,
              )
          : undefined;
        const isBash = toolName === "Bash";
        const yieldAfterInitialWait = isBash && this.bashYieldCalls.delete(toolCallId)
          && !this.delegateToolCalls.has(toolCallId)
          && !this.modeGateCalls.has(toolCallId)
          && !(isRecord(params) && (params.runInBackground === true || isPatchCommand(params.command)));
        const timeoutMs = isBash ? commandTimeoutMs(params) : undefined;
        let progress = "";
        let progressDirty = false;
        let progressTimer: ReturnType<typeof setTimeout> | undefined;
        let settled = false;
        let abortRequested = false;
        let cleaned = false;
        let abortError: unknown;
        let abortPromise: Promise<void> | undefined;
        let cleanup: (flush: boolean) => void = () => undefined;
        const flushProgress = () => {
          progressTimer = undefined;
          if (!onUpdate || !progress || !progressDirty) return;
          progressDirty = false;
          try {
            onUpdate({
              content: [{ type: "text", text: progress }],
              details: { output: progress },
            });
          } catch {
            // Progress is advisory; a renderer callback must not fail the tool.
          }
        };
        const scheduleProgress = () => {
          if (!onUpdate || progressTimer || settled) return;
          progressTimer = setTimeout(flushProgress, TOOL_OUTPUT_UPDATE_THROTTLE_MS);
        };
        const unsubscribeOutput = isBash && this.host.onNotification
          ? this.host.onNotification((method, params) => {
              if (
                settled ||
                method !== "tools.output" ||
                !isToolsOutputParams(params) ||
                params.sessionId !== this.sessionId ||
                params.toolCallId !== toolCallId ||
                params.commandShellId !== this.commandShell.id
              ) {
                return;
              }
              progress = appendToolProgress(progress, params.chunk);
              progressDirty = true;
              scheduleProgress();
            })
          : undefined;
        // Read-only core tools may be abandoned locally if host-core is still
        // waiting on a blocking read/search. Mutating, MCP, and plugin calls
        // must settle before the turn is reported stopped. Bash and image
        // generation retain their host process-abort path and grace window.
        // Computer use joins them: main owns a loop that must settle before
        // the turn is reported stopped, not be abandoned mid-action.
        const hostAbortsProcess =
          isBash || toolName === "GenerateImages" || toolName === "Computer";
        const canAbandonWait = READ_ONLY_CORE_TOOLS.has(toolName);
        const abortedMarker = Symbol("tool-aborted");
        let resolveAborted: (marker: typeof abortedMarker) => void = () => undefined;
        const aborted = new Promise<typeof abortedMarker>((resolve) => {
          resolveAborted = resolve;
        });
        let abortGraceTimer: ReturnType<typeof setTimeout> | undefined;
        let stopped = false;
        let steeringAbortRequested = false;
        const steeringAbort = () => {
          if (steeringAbortRequested || settled) return;
          steeringAbortRequested = true;
          void this.host.call("tools.abort", {
            sessionId: this.sessionId, toolCallId, toolName,
          }).catch(() => undefined);
        };
        const abort = () => {
          if (abortRequested || settled) return;
          abortRequested = true;
          abortPromise = this.host
            .call("tools.abort", {
              sessionId: this.sessionId,
              toolCallId,
              toolName,
            })
            .then(
              () => undefined,
              (error) => {
                abortError = error;
              },
            );
          // Release progress/output resources before arming the grace window:
          // cleanup is idempotent and must not race the timer it would clear.
          cleanup(true);
          if (hostAbortsProcess) {
            // Bounded window for the partial output the host collected before
            // the kill; past it the turn ends regardless.
            abortGraceTimer = setTimeout(
              () => resolveAborted(abortedMarker),
              TOOL_ABORT_GRACE_MS,
            );
          } else if (canAbandonWait) {
            // These tools are read-only, so returning before their host-side
            // work drains cannot leave a write or external action behind.
            resolveAborted(abortedMarker);
          }
        };

        cleanup = (flush: boolean) => {
          if (cleaned) return;
          cleaned = true;
          settled = true;
          if (progressTimer) clearTimeout(progressTimer);
          if (flush) flushProgress();
          unsubscribeOutput?.();
          signal?.removeEventListener("abort", abort);
          this.activeToolProgressCleanups.delete(cleanup);
          this.activeToolAborts.delete(abort);
          this.steeringToolAborts.delete(toolCallId);
        };
        this.activeToolProgressCleanups.add(cleanup);
        if (signal?.aborted) {
          cleanup(false);
          throw Object.assign(new Error("tool execution aborted before it started"), {
            errorCode: "TOOL_ABORTED",
          });
        }
        const delegate = this.delegateExecution.getStore();
        if (signal) {
          signal.addEventListener("abort", abort, { once: true });
        }
        this.activeToolAborts.add(abort);
        // Remote cancellation only acknowledges the request, not the remote
        // operation's settlement. Keep waiting for those calls instead.
        if (!this.remoteWorkspace && (isBash || canAbandonWait) &&
            this.activeToolCalls.has(toolCallId) && !delegate &&
            !(isBash && isRecord(params) && params.runInBackground === true)) {
          this.steeringToolAborts.set(toolCallId, steeringAbort);
          if (this.pendingSteering.size) steeringAbort();
        }

        let result: {
          ok: boolean;
          content: unknown;
          isError?: boolean;
          errorCode?: string;
          denied?: boolean;
        } | undefined;
        let executionError: unknown;
        let executionFailed = false;
        try {
          const execution = this.host.call<{
              ok: boolean;
              content: unknown;
              isError?: boolean;
              errorCode?: string;
              denied?: boolean;
            }>("tools.execute", {
              sessionId: this.sessionId,
              turnId: delegate?.turnId ?? this.turnId,
              toolCallId,
              toolName,
              args: params,
              ...(this.fileLineReadCalls.has(toolCallId) ? { workspaceOnly: true } : {}),
              ...(this.batchPlanner.ticket(toolCallId) ? { fileBatchTicket: this.batchPlanner.ticket(toolCallId) } : {}),
              mode: this.mode,
              // A staged mode's `run` exit gate (ADR mode-definitions): the
              // Host checks the command against the snapshot and records the
              // exit code under this call id for `modes.gateResult`.
              ...(isBash && this.modeGateCalls.has(toolCallId)
                ? { modeGate: this.modeGateCalls.get(toolCallId) }
                : {}),
              ...(isBash
                ? {
                    expectedCommandShellId: this.commandShell.id,
                    expectedCommandShellDialect: this.commandShell.dialect,
                    timeoutMs,
                    ...(yieldAfterInitialWait ? { yieldAfterInitialWait } : {}),
                    ...(isRecord(params) && params.runInBackground === true
                      ? { runInBackground: true }
                      : {}),
                  }
                : {}),
              ...(toolName.startsWith("plugin_")
                ? (() => {
                    const def = this.pluginTools.find(
                      (tool) => tool.name === toolName,
                    );
                    return {
                      declaredRisk: def?.risk,
                      // Plan-safe action list lets host-core admit the
                      // plugin tool in Plan/Goal modes (ADR 0211).
                      ...(Array.isArray(def?.planSafeActions) &&
                      def!.planSafeActions.length > 0
                        ? { planSafeActions: [...def!.planSafeActions] }
                        : {}),
                    };
                  })()
                : {}),
              ...(delegate && delegate.permission !== DEFAULT_SUBAGENT_PERMISSION ? { permissionScope: delegate.permission } : {}),
              ...(delegate?.worktreeKey ? { delegationId: delegate.worktreeKey } : {}),
              ...scopedWriteMetadata(toolName, delegate?.writeScope),
            });
          // #1767: read-only host work must not keep the user-facing turn open
          // indefinitely. Other tool classes deliberately wait for the Host
          // result so a write or extension action cannot outlive a reported
          // stop.
          const raced = await Promise.race([execution, aborted]);
          if (raced === abortedMarker) {
            stopped = true;
          } else {
            result = raced;
          }
        } catch (error) {
          executionFailed = true;
          executionError = error;
        } finally {
          cleanup(true);
          // cleanup is a no-op once the abort path has run, so the grace timer
          // it armed is released here instead.
          if (abortGraceTimer) clearTimeout(abortGraceTimer);
        }
        // A failed transport or process-lifecycle result does not prove that
        // the interrupted shell and its descendants have stopped. Only an
        // explicit whole-turn Stop may release this uncertain operation.
        const uncertainShell = steeringAbortRequested && isBash &&
          (executionFailed || (result?.ok === false && result.errorCode === "TOOL_FAILED"));
        const uncertainRemote = this.pendingSteering.size > 0 && Boolean(this.remoteWorkspace) &&
          (executionFailed || result?.ok === false);
        const uncertainExternal = this.pendingSteering.size > 0 && !canAbandonWait && !isBash &&
          (executionFailed || result?.errorCode === "TOOL_TIMEOUT");
        if (!signal?.aborted && (uncertainShell || uncertainRemote || uncertainExternal)) {
          await new Promise<void>((resolve) => {
            if (!signal || signal.aborted) return resolve();
            signal.addEventListener("abort", () => resolve(), { once: true });
          });
        }
        // A local read-only stop cannot depend on the same Host answering a
        // second RPC. Its abort request already observes late rejections.
        // Other tools retain Host settlement ownership for their side effects.
        if (!canAbandonWait) {
          if (abortPromise) await abortPromise;
          if (abortError) throw abortError;
        }
        if (stopped) {
          throw Object.assign(
            new Error(`tool execution aborted while ${toolName} was running`),
            { errorCode: "TOOL_ABORTED" },
          );
        }
        if (executionFailed) throw executionError;
        if (!result) throw new Error("tool execution returned no result");
        const recordParams = isRecord(params) ? params : undefined;
        const fileLineRead = this.fileLineReadCalls.get(toolCallId);
        if (fileLineRead && (result.denied || result.errorCode === "PERMISSION_DENIED")) {
          fileLineRead.blocked = true;
        }
        const failedToolExecution = !result.ok && result.denied !== true;
        const failedEditPath =
          toolName === "Edit" &&
          failedToolExecution &&
          typeof recordParams?.path === "string"
            ? recordParams.path
            : undefined;
        const failedPatchCommand =
          toolName === "Bash" &&
          failedToolExecution &&
          isPatchCommand(recordParams?.command);
        const mutationOwner = delegate?.owner;
        const targetKey = failedEditPath
          ? mutationPath
          : failedPatchCommand
            ? BASH_PATCH_FAILURE_KEY
            : undefined;
        const failureKey = targetKey
          ? `${mutationOwner ?? "parent"}\0${targetKey}`
          : undefined;
        const mutationFailureKind = failedEditPath
          ? "edit"
          : failedPatchCommand
            ? "patch-command"
            : undefined;
        // A recoverable code is forgiven once per path, not once per call: a
        // stale tag followed by unseen lines is two different honest failures,
        // while the same code twice on the same path is a model that ignored
        // what the first error told it.
        const graceKey =
          failureKey !== undefined &&
          typeof result.errorCode === "string" &&
          RECOVERABLE_MUTATION_ERROR_CODES.has(result.errorCode)
            ? `${failureKey}${result.errorCode}`
            : undefined;
        const grantedRecoveryGrace =
          graceKey !== undefined && !this.mutationRecoveryGraces.has(graceKey);
        if (graceKey !== undefined && grantedRecoveryGrace) {
          this.mutationRecoveryGraces.add(graceKey);
        }
        const mutationFailureAttempt =
          failureKey && !grantedRecoveryGrace
            ? (this.mutationFailureCounts.get(failureKey) ?? 0) + 1
            : undefined;
        const terminateAfterMutationFailure =
          mutationFailureAttempt !== undefined &&
          mutationFailureAttempt >= MAX_MUTATION_RECOVERY_FAILURES;
        if (failureKey && mutationFailureAttempt !== undefined) {
          this.mutationFailureCounts.set(failureKey, mutationFailureAttempt);
        }
        // The guard counts consecutive failures. A write that landed is
        // progress, so it clears that path's history instead of leaving one
        // stale strike to terminate the next unrelated failure.
        if (!failureKey && result.ok) {
          const succeededTarget =
            PATH_MUTATING_TOOLS.has(toolName) && typeof recordParams?.path === "string"
              ? mutationPath
              : toolName === "Bash" && isPatchCommand(recordParams?.command)
                ? BASH_PATCH_FAILURE_KEY
                : undefined;
          const succeededKey = succeededTarget
            ? `${mutationOwner ?? "parent"}\0${succeededTarget}`
            : undefined;
          if (succeededKey !== undefined) {
            this.mutationFailureCounts.delete(succeededKey);
            for (const key of this.mutationRecoveryGraces) {
              if (key.startsWith(`${succeededKey}`)) {
                this.mutationRecoveryGraces.delete(key);
              }
            }
          }
        }
        if (terminateAfterMutationFailure) {
          this.terminatingToolCalls.add(toolCallId);
          // The loop stops after this batch, so nothing downstream would
          // explain why. Hold the reason for agent_end to turn into a visible
          // row instead of a turn that just ends.
          if (!mutationOwner) {
            this.pendingMutationTermination = {
              kind: mutationFailureKind ?? "edit",
              target: failedEditPath ?? "the patch command",
              ...(typeof result.errorCode === "string"
                ? { lastErrorCode: result.errorCode }
                : {}),
            };
          } else {
            const kind = mutationFailureKind ?? "edit";
            this.delegateMutationTerminations.set(toolCallId, {
              code: "MUTATION_RETRY_BUDGET_EXHAUSTED",
              message: mutationTerminationMessage(
                kind,
                failedEditPath ?? "the patch command",
                result.errorCode,
              ),
            });
          }
        }
        const rawContent = result.content;
        const imageBlocks: Array<{ type: "image"; data: string; mimeType: string }> = [];
        let text: string;
        let details: unknown = rawContent;
        const vision = visionFromModelConfig(this.provider.modelConfig);
        // Collect image blocks from a content-block array; only well-formed
        // image entries ({ type, data, mimeType }) are accepted.
        const collectImageBlocks = (blocks: unknown[]): void => {
          for (const block of blocks) {
            if (
              isRecord(block) &&
              block.type === "image" &&
              typeof block.data === "string" &&
              typeof block.mimeType === "string"
            ) {
              if (vision) {
                imageBlocks.push({
                  type: "image",
                  data: block.data,
                  mimeType: block.mimeType,
                });
              }
            }
          }
        };
        if (typeof rawContent === "string") {
          text = rawContent;
        } else if (Array.isArray(rawContent)) {
          // Plugin tools may return a bare content-block array
          // ([{ type: "text" }, { type: "image" }]); render the text blocks
          // and hand images to the model instead of stringifying (#1360).
          const textParts: string[] = [];
          for (const block of rawContent) {
            const blockText = hostContentBlockText(block);
            if (blockText !== undefined) textParts.push(blockText);
          }
          collectImageBlocks(rawContent);
          text =
            textParts.join("\n") ||
            JSON.stringify(withoutInlineBinary(rawContent), null, 2);
          details = { blocks: rawContent, imageCount: imageBlocks.length };
        } else if (isRecord(rawContent) && Array.isArray(rawContent.content)) {
          // MCP tools return `content: [{ type: "image" | "text", ... }]`.
          const contentBlocks = rawContent.content;
          const textParts: string[] = [];
          for (const block of contentBlocks) {
            const blockText = hostContentBlockText(block);
            if (blockText !== undefined) textParts.push(blockText);
          }
          collectImageBlocks(contentBlocks);
          text =
            textParts.join("\n") ||
            JSON.stringify(withoutInlineBinary(rawContent), null, 2);
          details = { ...rawContent, imageCount: imageBlocks.length };
        } else if (isRecord(rawContent) && Array.isArray(rawContent.images)) {
          text =
            typeof rawContent.text === "string"
              ? rawContent.text
              : JSON.stringify(
                  { ...rawContent, images: undefined },
                  null,
                  2,
                );
          for (const image of rawContent.images) {
            if (
              !isRecord(image) ||
              typeof image.data !== "string" ||
              typeof image.mimeType !== "string"
            ) {
              continue;
            }
            if (vision) {
              imageBlocks.push({
                type: "image",
                data: image.data,
                mimeType: image.mimeType,
              });
            }
          }
          const { images: _images, ...rest } = rawContent;
          details = {
            ...rest,
            ...(typeof rawContent.path === "string" ? { path: rawContent.path } : {}),
            imageCount: imageBlocks.length,
          };
        } else {
          text = JSON.stringify(rawContent, null, 2);
        }
        if (!result.ok) this.failedHostToolCalls.add(toolCallId);
        // A visualization fragment gets one cheap static check in its Write
        // result, so a broken card is fixed in one Edit instead of left blank.
        if (
          toolName === "Write" &&
          result.ok &&
          typeof recordParams?.content === "string" &&
          isGenUiFragmentPath(recordParams.path, this.visualizationsDir)
        ) {
          const issues = checkGenUiFragment(recordParams.content);
          if (issues.length > 0) text += `\n${genUiFragmentCheckNote(issues)}`;
        }
        return {
          content: [{ type: "text", text }, ...imageBlocks],
          details,
          ...(terminateAfterMutationFailure ? { terminate: true } : {}),
          isError: result.isError === true || result.ok === false,
        };
      };
      return {
        name: toolName,
        label: toolName,
        description: describe(toolName),
        parameters: Type.Object(
          scheduledToolParameters[toolName] ?? parameters[toolName] ?? { command: Type.String() },
        ),
        // Normalizing here, above the write lock, means every consumer below
        // this line — the lock key, the host call, the transcript record — sees
        // canonical argument names only (D273).
        execute: async (toolCallId, rawParams, signal, onUpdate) => {
          const prepared = typeof rawParams === "object" && rawParams !== null
            && this.preparedPathToolArgs.has(rawParams);
          // A prepared call was already checked by preparePathToolCall.
          if (!prepared) rejectConflictingAliasedParams(toolName, rawParams);
          const params = prepared
            ? this.preparedPathToolArgs.get(rawParams as object)
            : normalizeToolParams(toolName, rawParams);
          if (prepared) this.preparedPathToolArgs.delete(rawParams as object);
          requireAliasedParams(toolName, params);
          if (READ_ONLY_CORE_TOOLS.has(toolName)) {
            await this.waitForBatchWritableDelegations(toolCallId, signal);
          }
          // Direct/internal invocations retain preflight. pi invocations have
          // already committed instructions in the ordered preparation phase.
          if (!prepared) await this.loadPathInstructions(toolName, params, this.instructionExecution.getStore());
          if (!this.batchPlanner.supported && PATH_MUTATING_TOOLS.has(toolName)) {
            return this.writeLocks.run(
              this.pathLockKey(params),
              () => run(toolCallId, params, signal, onUpdate),
            );
          }
          if (!this.batchPlanner.supported && toolName === "Read") {
            return this.writeLocks.read(
              this.pathLockKey(params),
              () => run(toolCallId, params, signal, onUpdate),
            );
          }
          return run(toolCallId, params, signal, onUpdate);
        },
      };
    };

    const askTool: AgentTool = {
      name: ASK_TOOL_NAME,
      label: "Ask questions",
      description: describe(ASK_TOOL_NAME),
      parameters: Type.Object({
        questions: Type.Array(
          Type.Object({
            question: Type.String({ maxLength: MAX_ASK_TOOL_QUESTION_CHARS }),
            options: Type.Array(
              Type.Union([
                Type.String(),
                Type.Object({
                  label: Type.String(),
                  description: Type.Optional(Type.String()),
                }),
              ]),
            ),
            multiSelect: Type.Optional(Type.Boolean()),
          }),
        ),
      }),
      executionMode: "sequential",
      execute: async (toolCallId, params, signal) => {
        const questions = this.normalizeAskQuestions(params);
        if (!questions) {
          return {
            content: [
              {
                type: "text",
                text: `${ASK_TOOL_NAME} requires 1–20 questions. Each question must contain 1–${MAX_ASK_TOOL_QUESTION_CHARS} characters and at least one option.`,
              },
            ],
            details: { errorCode: "ASKTOOL_INVALID_ARGUMENT" },
            isError: true,
          };
        }
        const request: AskToolRequest = {
          requestId: randomUUID(),
          sessionId: this.sessionId,
          toolCallId,
          questions,
        };
        const answers = await this.waitForAskTool(request, signal);
        const text = formatAskToolOutput(questions, answers);
        return {
          content: [{ type: "text", text }],
          details: { questions, answers },
        };
      },
    };

    // BrowserPreview is non-mutating (renders an existing workspace file in
    // the work panel browser), so it ships in every mode. PluginCheck only
    // reads a directory; PluginScaffold and PluginPack write and remain
    // Agent-only. Write/Edit keep guarded declarations in contract modes.
    // The tool policy level, not the mode name, decides the set (ADR
    // mode-definitions): an agent-level custom mode or stage gets the Agent
    // tools, a contract-level one the Plan tools.
    const agentLevel = this.modeState.isAgentLevel();
    const tools =
      agentLevel
        ? [
            "Read",
            "Bash",
            "Edit",
            "Write",
            "Glob",
            "Grep",
            "BrowserPreview",
            "PluginCheck",
            "TodoWrite",
          ]
        : ["Read", "Glob", "Grep", "BrowserPreview", "Bash", "Write", "Edit"];
    if (agentLevel) tools.push("PluginScaffold", "PluginPack", "GenerateImages");
    // Scheduled tasks and computer use belong to the builtin Agent mode
    // itself; the Host refuses them in every other mode.
    if (agentLevel && this.modeState.offersAgentModeOnlyTools()) {
      tools.push(...Object.keys(scheduledToolParameters));
      if (this.computerUseEnabled) tools.push("Computer");
    }
    const builtins = tools.map(exec);
    for (const tool of builtins) this.builtinTools.add(tool);
    const jevTools: AgentTool[] =
      agentLevel && this.jevApiKey
        ? [createJevClassifierTool(this.jevApiKey)]
        : [];
    const codemodeTools: AgentTool[] =
      agentLevel && this.codemodeEnabled ? [this.buildCodemodeTool()] : [];

    // Plugins contribute Agent tools by default. Plan/Goal modes only
    // expose plugins that declare plan-safe actions (ADR 0211); the
    // host still enforces the per-action restriction at execute time.
    const visiblePluginTools =
      agentLevel
        ? this.pluginTools
        : this.pluginTools.filter(
            (def) =>
              Array.isArray(def.planSafeActions) &&
              def.planSafeActions.length > 0,
          );
    const pluginTools: AgentTool[] = visiblePluginTools.map((def) => {
      // Plan/Goal modes annotate the description so the model knows which
      // actions it may actually call.
      const baseDescription =
        def.description || `${def.name} plugin tool`;
      const description =
        !agentLevel &&
        Array.isArray(def.planSafeActions) &&
        def.planSafeActions.length > 0
          ? `${baseDescription} (${this.mode} mode: only ${def.planSafeActions.join(", ")} actions)`
          : baseDescription;
      return {
        name: def.name,
        label: def.name,
        description,
        parameters: (def.parameters ??
          Type.Object({})) as AgentTool["parameters"],
        executionMode: "sequential" as const,
        execute: exec(def.name).execute,
      };
    });
    // Only offered when a plugin actually taught a skill; Electron main serves
    // it locally (host-core never sees the skill documents).
    const skillTools: AgentTool[] =
      agentLevel && this.pluginSkills.length
      ? [
          {
            name: SKILL_TOOL_NAME,
            label: "Skill",
            description:
              "Load the full instructions of one skill listed in the Skills section of your system prompt. Pass its exact id (for example \"demo.hello/release-notes\"). Returns the skill document; follow it for the current task.",
            parameters: Type.Object({
              id: Type.String({
                description: "Skill id exactly as listed in the Skills section.",
              }),
            }),
            execute: exec(SKILL_TOOL_NAME).execute,
          },
        ]
      : [];
    // Only the builtin Agent enters Plan and only the builtin Plan submits a
    // proposal (ADR 0053). Goal is selected by the user and runs as a staged
    // mode, so EnterGoalMode and SubmitGoal are never offered. CompleteStage
    // exists only while this turn holds a run claim.
    const modeTools = [
      ...(this.mode === "agent" ? [this.buildEnterModeTool("plan")] : []),
      ...(this.mode === "plan" ? [this.buildSubmitTool("plan")] : []),
      ...(this.modeState.modeTurn ? [this.buildCompleteStageTool()] : []),
    ];
    // Job controls are available without subagents. Contract modes retain
    // declarations for history but reject execution before these handlers.
    const subagentTools = [
      ...(this.subagents.length ? [this.buildSubagentTool(), this.buildSubagentSendTool()] : []),
      ...buildJobTools({
        wait: this.buildSubagentWaitTool(),
        list: this.buildSubagentListTool(),
        stop: this.buildSubagentStopTool(),
      }, {
        host: this.host,
        sessionId: this.sessionId,
        remote: Boolean(this.remoteWorkspace),
        defaultTimeoutSeconds: TASKWAIT_DEFAULT_TIMEOUT_SECONDS,
        maxTimeoutSeconds: TASKWAIT_MAX_TIMEOUT_SECONDS,
        wait: async (run, signal) => {
          const steeringAbort = new AbortController();
          this.steeringWaitAbort = steeringAbort;
          if (this.pendingSteering.size) steeringAbort.abort();
          try {
            return await run(signal ? AbortSignal.any([signal, steeringAbort.signal]) : steeringAbort.signal);
          } catch (error) {
            const interruptedByInput = isRecord(error) && error.errorCode === "TOOL_ABORTED" &&
              steeringAbort.signal.aborted && !signal?.aborted &&
              !this.runCancelled && !this.disposed && !this.turnHadError;
            if (!interruptedByInput) throw error;
            return {
              content: [{ type: "text", text: "Interrupted by new user input. The background command keeps running; handle the user's message before waiting again." }],
              details: { status: "interrupted" },
            };
          } finally {
            if (this.steeringWaitAbort === steeringAbort) this.steeringWaitAbort = undefined;
          }
        },
      }),
    ];
    for (const tool of subagentTools) this.builtinTools.add(tool);
    const contextTools = this.compactionEnabled
      ? [this.buildContextCompactionTool()]
      : [];
    // Trusted extension tools are non-core: the per-mode allowlist and
    // ToolSearch deferral treat them like plugin tools (spec 16 §7).
    const extensionTools = this.extensionRunner?.getAgentTools() ?? [];
    return [
      ...builtins,
      ...jevTools,
      ...codemodeTools,
      askTool,
      ...pluginTools,
      ...skillTools,
      ...modeTools,
      ...subagentTools,
      ...contextTools,
      ...extensionTools,
    ];
  }

  /**
   * Build the complete registry before selecting fixed or on-demand
   * declarations. Execution activation and Host permissions remain separate
   * from the provider-visible schemas.
   */
  /**
   * The opt-in `codemode` tool. Scripts call the session's active tools
   * through the same hooks and Host path as direct calls; control,
   * interactive and delegation tools stay out of reach.
   */
  private buildCodemodeTool(): AgentTool {
    const tool = createSessionCodemodeTool({
      sessionId: this.sessionId,
      catalog: () => [...this.toolCatalog.values()],
      active: () => this.activeTools().filter((tool) => this.isToolAllowedInMode(tool.name)),
      excluded: CODEMODE_EXCLUDED_TOOL_NAMES,
      hooks: {
        beforeToolCall: (context) => this.beforeToolCall(context),
        afterToolCall: (context) => this.afterToolCall(context),
      },
      model: () => this.model,
      turnId: () => this.turnId,
      emit: (envelope) => this.onEvent(envelope),
      emitUsage: (usage, turnId) => this.emit({ type: "usage", usage }, turnId),
      activeToolCalls: this.activeToolCalls,
      settleBatch: (message) => this.batchPlanner.settleBatch(message),
      provider: () => this.provider,
      ...(this.jevApiKey ? { jevApiKey: this.jevApiKey } : {}),
    });
    return {
      ...tool,
      // Like a direct Read after a writable `Task` in the same message, a
      // script waits for that delegate before any nested call runs.
      execute: async (toolCallId, params, signal, onUpdate) => {
        await this.waitForBatchWritableDelegations(toolCallId, signal);
        return tool.execute(toolCallId, params, signal, onUpdate);
      },
    };
  }

  private guardSteeredTool(tool: AgentTool): AgentTool {
    return { ...tool, execute: async (id, args, signal, update) => {
      if (tool.name !== SUBAGENT_WAIT_TOOL_NAME && this.pendingSteering.size &&
          this.activeToolCalls.has(id) && !this.delegateExecution.getStore()) {
        return { content: [{ type: "text", text: "Skipped because new user input is waiting." }], details: {}, isError: true };
      }
      return tool.execute(id, args, signal, update);
    } };
  }

  private rebuildToolCatalog(): void {
    const catalog = new Map<string, AgentTool>();
    for (const tool of this.buildToolDefinitions()) {
      if (!this.isToolAllowedInMode(tool.name) && !retainModeToolDeclaration(tool.name)) continue;
      // The execution mode is decided here, in one place, so no tool can grow
      // an accidental parallel batch: unknown tools remain sequential.
      // pi runs a whole batch sequentially when it holds one sequential tool;
      // the batch-level policy also keeps Task mixed with any file tool
      // (Read/Glob/Grep/Write/Edit) sequential; only reads ordered after a
      // writable Task wait for that delegate to settle.
      // The provider-facing schema is settled here too, at the single origin of
      // every tool, so the session agent and a delegated `Task` run send the
      // same declaration (#864).
      const builtin = this.builtinTools.has(tool);
      const guarded = withModeExecutionGuard(
        withExplicitRequired({
          ...tool,
          executionMode: builtin ? toolExecutionMode(tool.name, this.batchPlanner.supported) : "sequential",
        }),
        () => this.isToolAllowedInMode(tool.name) ? undefined : modeToolDenial(tool.name, this.mode),
      );
      // Batch ordering wraps the mode guard: a call the guard rejects must
      // still release the calls ordered behind it in its batch.
      const steeringGuarded = this.guardSteeredTool(guarded);
      const catalogTool = withDynamicTaskExecutionMode(
        builtin && TOOL_EXECUTION_SPECS[tool.name]?.file ? withBatchTurn(steeringGuarded, this.batchPlanner) : steeringGuarded,
        () => this.agent?.state.messages.at(-1),
      );
      if (builtin) this.builtinTools.add(catalogTool);
      catalog.set(tool.name, catalogTool);
    }
    this.toolCatalog = catalog;
    this.deferredToolNames = new Set(
      [...this.toolCatalog.keys()].filter(
        (name) => !this.isCoreTool(name) && name !== TOOL_SEARCH_NAME,
      ),
    );
    for (const name of this.activeDeferredToolNames) {
      if (!this.deferredToolNames.has(name)) {
        this.activeDeferredToolNames.delete(name);
      }
    }
    if (this.deferredToolNames.size > 0) {
      this.toolCatalog.set(
        TOOL_SEARCH_NAME,
        this.guardSteeredTool(withExplicitRequired({
          ...this.buildToolSearchTool(),
          executionMode: "sequential",
        })),
      );
    }
    if (this.model) this.refreshToolDeclarationPolicy();
  }

  private refreshToolDeclarationPolicy(): void {
    const previous = this.declarationPolicy;
    const policy = toolDeclarationPolicy(this.model, [...this.toolCatalog.values()], this.deferredToolNames, this.composeSystemPrompt(), this.provider.id);
    if (previous && previous.key !== policy.key && this.trackToolActivation) {
      this.activeDeferredToolNames.clear();
      this.activationHydrated = true;
    }
    this.declarationPolicy = policy;
    this.trackToolActivation ||= Boolean(policy.tools || policy.fallback);
    if (policy.fallback && (previous?.key !== policy.key || previous.fallback !== policy.fallback)) {
      process.stderr.write(`[agent-runtime] fixed tool declarations unavailable (${policy.fallback}); using on-demand declarations; ToolSearch cache stability is not guaranteed.\n`);
    }
  }

  private declaredTools(): AgentTool[] {
    return this.declarationPolicy?.tools ?? this.activeTools();
  }

  private isPlanSafePluginTool(name: string): boolean {
    return this.pluginTools.some(
      (def) =>
        def.name === name &&
        Array.isArray(def.planSafeActions) &&
        def.planSafeActions.length > 0,
    );
  }

  private isToolAllowedInMode(name: string): boolean {
    if (this.modeState.isAgentLevel()) return true;
    // The contract level is read-only (Plan's hard deny, ADR mode-definitions
    // for every other contract mode or stage): inspection tools, plan-safe
    // plugin actions (ADR 0211), Plan's own submit tool, and CompleteStage
    // while this turn holds a run claim. Unknown modes fail closed here.
    if (this.isPlanSafePluginTool(name)) return true;
    if (name === SUBMIT_TOOL_NAMES.plan) return this.mode === "plan";
    if (name === COMPLETE_STAGE_TOOL_NAME) return this.modeState.modeTurn !== undefined;
    return CONTRACT_ALLOWED_TOOL_NAMES.has(name);
  }

  private isCoreTool(name: string): boolean {
    return (
      name === CONTEXT_COMPACTION_TOOL_NAME ||
      retainModeToolDeclaration(name) ||
      MODE_TRANSITION_TOOL_NAMES.has(name) ||
      // The whole delegation lifecycle stays in the core set rather than the
      // on-demand catalog: a capability the model has to go looking for is one
      // it will not use, and delegation is worth the extra schemas per request.
      name === SUBAGENT_TOOL_NAME ||
      name === SUBAGENT_WAIT_TOOL_NAME ||
      name === SUBAGENT_LIST_TOOL_NAME ||
      name === SUBAGENT_STOP_TOOL_NAME ||
      name === SUBAGENT_SEND_TOOL_NAME ||
      // A stage's completion must never hide behind ToolSearch.
      name === COMPLETE_STAGE_TOOL_NAME ||
      // Codemode is opt-in; once enabled it is declared up front.
      name === CODEMODE_TOOL_NAME ||
      (this.modeState.isAgentLevel()
        ? AGENT_CORE_TOOL_NAMES.has(name)
        : CONTRACT_CORE_TOOL_NAMES.has(name) || this.isPlanSafePluginTool(name))
    );
  }

  private activeTools(): AgentTool[] {
    return [...this.toolCatalog.entries()]
      .filter(
        ([name]) =>
          this.isCoreTool(name) ||
          name === TOOL_SEARCH_NAME ||
          this.activeDeferredToolNames.has(name),
      )
      .map(([, tool]) => tool);
  }

  private optionalToolsPrompt(): string {
    const entries: ToolCatalogEntry[] = [...this.deferredToolNames]
      .map((name) => this.toolCatalog.get(name))
      .filter((tool): tool is AgentTool => tool !== undefined)
      .map((tool) => ({
        name: tool.name,
        description: this.toolCatalogDescription(tool),
      }));
    if (entries.length === 0) return "";

    const visibleEntries = entries.slice(0, MAX_ON_DEMAND_TOOL_PROMPT_ENTRIES);
    const lines = visibleEntries.map(
      (entry) => `- ${entry.name}: ${this.compactToolDescription(entry.description)}`,
    );
    if (entries.length > visibleEntries.length) {
      lines.push(
        `- ... ${entries.length - visibleEntries.length} more; search by exact name or capability`,
      );
    }
    return [
      "# On-demand tools",
      `The following capabilities are available on demand. Call ${TOOL_SEARCH_NAME} with an exact tool name or a short capability description before using an on-demand tool that has not been activated. A visible schema is not activation; the tool_activation section, when present, records active names.`,
      ...lines,
    ].join("\n");
  }

  private compactToolDescription(description: string): string {
    const compact = description.replace(/\s+/g, " ").trim();
    return compact.length <= 120 ? compact : `${compact.slice(0, 117)}...`;
  }

  private toolCatalogDescription(tool: AgentTool): string {
    switch (tool.name) {
      case "BrowserPreview":
        return "Preview an HTML file in the built-in browser panel.";
      case "PluginCheck":
        return "Validate a PI-Desktop plugin directory.";
      case "PluginScaffold":
        return "Create a PI-Desktop plugin from a template.";
      case "PluginPack":
        return "Validate and package a PI-Desktop plugin.";
      default:
        return this.compactToolDescription(tool.description);
    }
  }

  private buildToolSearchTool(): AgentTool {
    return {
      name: TOOL_SEARCH_NAME,
      label: "Tool Search",
      description:
        "Find and activate an on-demand tool by exact name or capability. Use this before calling an inactive tool listed under On-demand tools, even when its schema is already visible. Activation does not bypass approval or mode restrictions.",
      parameters: Type.Object({
        query: Type.String({
          description:
            "Exact tool name or a short capability description, for example `BrowserPreview` or `validate plugin`.",
        }),
      }),
      execute: async (_toolCallId, params) => {
        const query =
          isRecord(params) && typeof params.query === "string"
            ? params.query.trim()
            : "";
        const matches = this.findDeferredTools(query);
        const activated = this.activateDeferredTools(matches);
        const available = [...this.deferredToolNames];
        const availablePreview = available.slice(0, MAX_TOOL_SEARCH_RESULT_NAMES);
        const remaining = available.length - availablePreview.length;
        const text =
          activated.length > 0
            ? `Activated on-demand tools: ${activated.join(", ")}. They are available on the next model turn.`
            : matches.length > 0
              ? `These tools are already active: ${matches.join(", ")}.`
              : `No matching on-demand tool. Available names: ${availablePreview.join(", ")}${remaining > 0 ? `, and ${remaining} more` : ""}.`;
        return {
          content: [{ type: "text", text }],
          details: {
            query,
            matches,
            activated,
            ...(activated.length > 0 ? { addedToolNames: activated } : {}),
          },
        };
      },
    };
  }

  private buildEnterModeTool(kind: ProposalKind): AgentTool {
    const name = ENTER_TOOL_NAMES[kind];
    const label = modeLabel(kind);
    return {
      name,
      label: `Enter ${label} Mode`,
      description:
        kind === "plan"
          ? "Switch this same agent into Plan mode after the host confirms the durable session transition. Use when the user wants to agree on the implementation steps before any change is made."
          : "Switch this same agent into Goal mode after the host confirms the durable session transition. Use when the user states an outcome and wants you to agree on the goal and its acceptance criteria, then reach it autonomously.",
      parameters: Type.Object({}),
      executionMode: "sequential",
      execute: async (toolCallId) => {
        await this.host.call("plans.enter", {
          sessionId: this.sessionId,
          turnId: this.turnId,
          toolCallId,
          kind,
        });
        // The host is authoritative. Rebuild the live prompt and tool set only
        // after plans.enter has committed the new mode.
        this.setMode(kind);
        return {
          content: [
            {
              type: "text",
              text:
                kind === "plan"
                  ? "Plan mode is active. Inspect the workspace, formulate the plan, then call SubmitPlan for approval."
                  : "Goal mode is active. Clarify the outcome and how it will be verified, then call SubmitGoal for approval.",
            },
          ],
          details: { mode: kind, kind, planningState: "planning" },
        };
      },
    };
  }

  /** `CompleteStage` for the run turn this prompt claimed (ADR mode-definitions). */
  private buildCompleteStageTool(): AgentTool {
    return createCompleteStageTool({
      host: this.host,
      sessionId: this.sessionId,
      context: () => {
        const modeTurn = this.modeState.activeTurn;
        return modeTurn && this.turnId ? { turnId: this.turnId, modeTurn } : undefined;
      },
      runGateCommand: (request, signal, onUpdate) => this.runModeGateCommand(request, signal, onUpdate),
      // A terminal outcome ends the turn at the next boundary, the same way
      // a graceful Stop does.
      endTurn: () => {
        this.gracefulStopRequested = true;
      },
      failTurn: (failure) => {
        this.terminateParentTurn();
        this.gracefulStopRequested = true;
        const error = { ...classifyAgentError(new Error(failure.message)), code: failure.code, retriable: false };
        this.finalizeCurrentAssistant("error", error);
        this.emit({ type: "error", error });
      },
    });
  }

  /**
   * A `run` exit gate goes through the same Host `tools.execute` Bash path as
   * the model's own Bash calls, so permission prompting and the shell policy
   * apply unchanged; `modeGate` lets the Host bind the exit code to the run.
   */
  private async runModeGateCommand(
    request: ModeGateCommand,
    signal: AbortSignal | undefined,
    onUpdate: Parameters<AgentTool["execute"]>[3],
  ): Promise<ModeGateRunResult> {
    const bash = this.toolCatalog.get("Bash");
    if (!bash) throw Object.assign(new Error("Bash is not available in this session"), { errorCode: "TOOL_NOT_FOUND" });
    this.modeGateCalls.set(request.toolCallId, request.modeGate);
    try {
      const result = await bash.execute(
        request.toolCallId,
        { command: request.command, timeout: request.timeoutSeconds },
        signal,
        onUpdate,
      );
      const text = result.content
        .map((block) => (block.type === "text" ? block.text : ""))
        .filter(Boolean)
        .join("\n");
      return { isError: (result as { isError?: boolean }).isError === true, text };
    } finally {
      // Not a model tool call: no afterToolCall consumes its bookkeeping.
      this.modeGateCalls.delete(request.toolCallId);
      this.failedHostToolCalls.delete(request.toolCallId);
      this.terminatingToolCalls.delete(request.toolCallId);
    }
  }

  private modeArtifactReader(): ModeArtifactReader {
    return createHostModeArtifactReader({
      host: this.host,
      sessionId: this.sessionId,
      turnId: () => this.turnId,
      mode: () => this.mode,
    });
  }

  /** Provider a delegate runs on: the definition's pin resolved by Electron
   * main, or the session's own provider when it pins nothing. */
  private subagentProvider(
    definition: SubagentDefinition,
  ): RuntimeProviderConfig | undefined {
    if (!definition.model) return this.provider;
    return this.subagentProviders[subagentModelKey(definition.model)];
  }

  /**
   * An explicit override that names the session's own provider/model is
   * semantically the same as omitting `Task.model`. Models sometimes echo the
   * current model id even when the delegation catalog is empty; accepting this
   * exact inheritance case avoids turning that harmless echo into a false
   * "model is not available" tool error while keeping other overrides gated.
   */
  private isSessionModelOverride(key: string): boolean {
    const slash = key.indexOf("/");
    if (slash < 1) return false;
    const requestedProvider = key
      .slice(0, slash)
      .trim()
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "");
    const requestedModel = key.slice(slash + 1).trim().toLowerCase();
    if (!requestedProvider || requestedModel !== this.provider.modelId.toLowerCase()) {
      return false;
    }
    return [this.provider.id, this.provider.vendorKey, this.provider.name]
      .filter((value): value is string => Boolean(value))
      .some(
        (value) =>
          value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "") ===
          requestedProvider,
      );
  }

  /**
   * Repeating the target definition's own pin is omit, not an override. The
   * Task catalog prints that key, and models copy it back into `model`.
   */
  private isDefinitionPinOverride(
    definition: SubagentDefinition,
    key: string,
  ): boolean {
    if (!definition.model) return false;
    if (key === subagentModelKey(definition.model)) return true;
    const slash = key.indexOf("/");
    if (slash < 1) return false;
    const requestedProvider = key
      .slice(0, slash)
      .trim()
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "");
    const requestedModel = key.slice(slash + 1).trim().toLowerCase();
    const pinProvider = definition.model.providerId
      .trim()
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "");
    return (
      Boolean(requestedProvider) &&
      requestedProvider === pinProvider &&
      requestedModel === definition.model.modelId.toLowerCase()
    );
  }

  /**
   * On-demand model resolution for Task-time model overrides. Asks Electron
   * main to authorize and resolve a `providerId/modelId` key outside the
   * opted-in launch catalog. Grants live in a separate cache so they cannot
   * rewrite definition pins or change launch-time reuse matching. Each new
   * parent turn replaces the cache so revoked grants must be authorized again.
   */
  private async resolveSubagentModel(
    key: string,
    fresh = false,
  ): Promise<RuntimeProviderConfig | undefined> {
    const grants = this.subagentOverrideProviders;
    const cached = !fresh && Object.hasOwn(grants, key) ? grants[key] : undefined;
    if (cached) return cached;
    try {
      const result = await this.host.call<RuntimeProviderConfig | null>("provider.resolveSubagentModel", { key });
      // A late response cannot authorize work in a newer turn or after disposal.
      if (this.disposed || this.runCancelled || grants !== this.subagentOverrideProviders) return undefined;
      if (result && typeof result.id === "string" && typeof result.modelId === "string") {
        const provider = result;
        const pinned = this.subagentProviders[key];
        if (pinned && pinned.id !== provider.id) {
          // Another account's opt-in must use its exact provider-id key.
          return undefined;
        }
        // Vendor-account (OAuth) providers need a resolveAuth callback so
        // pi-ai can obtain short-lived credentials per request. The JSON-RPC
        // result does not carry the callback, so we attach one that calls
        // back to Electron main — the same pattern sidecar.ts uses at launch.
        if (provider.authKind === OAUTH_AUTH_KIND) {
          provider.resolveAuth = () =>
            (this.host as any).call("provider.resolveAuth", {
              sessionId: this.sessionId,
              providerId: provider.id,
            });
        }
        if (!fresh) grants[key] = provider;
        return provider;
      }
    } catch {
      // Host does not support on-demand resolution or the key is invalid.
    }
    return undefined;
  }

  /**
   * Keys explicitly enabled for Task.model at launch or authorized by main
   * on demand. A binding resolved only for a definition pin is not an opt-in.
   */
  private availableSubagentModelKeys(): string[] {
    const keys = new Set<string>();
    for (const key of this.subagentModelKeys) {
      if (this.subagentProviders[key] || this.subagentOverrideProviders[key]) {
        keys.add(key);
      }
    }
    for (const key of Object.keys(this.subagentOverrideProviders)) keys.add(key);
    return [...keys];
  }

  /**
   * Build a markdown summary of models available for delegation, so the parent
   * agent can make informed model choices for Task.model overrides.
   */
  private subagentModelSummary(): string | undefined {
    const keys = this.availableSubagentModelKeys();
    if (keys.length === 0) {
      return [
        "No delegation model overrides are configured.",
        DELEGATION_DEFAULT_MODEL_GUIDANCE,
        DELEGATION_MODEL_OPT_IN_GUIDANCE,
      ].join(" ");
    }
    const lines: string[] = [
      "Available models for delegation (pass as `model` parameter on Task):\n",
    ];
    for (const key of keys) {
      const provider =
        this.subagentProviders[key] ?? this.subagentOverrideProviders[key];
      if (!provider) continue;
      const reasoning = provider.supportsReasoning ? "reasoning" : "standard";
      const levels = provider.supportedThinkingLevels?.length
        ? provider.supportedThinkingLevels.join("/")
        : "none";
      lines.push(
        `- \`${key}\` — ${provider.name}, ${reasoning}, thinking: ${levels}`,
      );
    }
    lines.push(
      "",
      "Pick cheaper/faster models for simple searches and read-only reviews. Reserve expensive reasoning models for complex multi-step analysis.",
    );
    return lines.join("\n");
  }

  /**
   * Session facts a delegate needs and cannot discover: the shell dialect, the
   * scratch directory, and the project's own instruction chain. The parent's
   * collaboration rules are deliberately left out — a delegate has no user to
   * talk to, and its report format is set by `composeSubagentSystemPrompt`.
   */
  private subagentGuidance(toolNames: readonly string[], instructions = this.projectInstructions ?? null, scoped = false): string[] {
    const tools = new Set(toolNames);
    const blocks: string[] = [];
    if (tools.has("Read") || tools.has("Grep") || tools.has("Glob")) {
      blocks.push(
        "Searching and reading: prefer Read, Grep, and Glob over shell text utilities. Read accepts only an existing regular text file, never a directory. If a file name is uncertain or a directory must be listed, use Glob when it is available; otherwise use a bounded available search or listing tool instead of guessing a file name or reading the directory. Scope every call — Grep takes a file-or-directory `path` plus `include`, `outputMode`, and `headLimit`; Glob takes a directory `path` and `limit`; Read takes `offset` and `limit` and always reports `totalLines`; use Grep to locate content in large files before reading a targeted range. Use `outputMode: \"filesWithMatches\"` or `\"count\"` when contents are not needed. Grep uses the system's `rg` when installed and an in-process searcher otherwise — call Grep rather than shelling out to `rg`. Your context is finite too: an unscoped search over the whole workspace costs the tokens you need to finish.",
      );
    }
    if (tools.has("Edit") || tools.has("Write")) {
      blocks.push(
        "Editing: use Edit for one small unique replacement and Write for a coherent whole-file rewrite. Treat a failed edit as stale content — Read the file once, regenerate the change, and if it fails again report the exact mismatch instead of looping. Never write a file the task did not ask you to change; another agent may be working in the same tree.",
      );
    }
    if (tools.has("Bash")) {
      blocks.push(commandShellGuidance(this.commandShell, this.scratchDir));
    }
    if (!scoped && this.scratchDir && (tools.has("Bash") || tools.has("Write"))) {
      blocks.push(
        `Write temporary and intermediate files into the session scratch directory \`${formatScratchDirForShell(this.commandShell, this.scratchDir)}\` (in Bash: ${shellScratchVariable(this.commandShell)}) using absolute paths, never into the workspace.`,
      );
    }
    if (tools.has(SKILL_TOOL_NAME)) {
      const skillsPrompt = pluginSkillsPrompt(this.pluginSkills);
      if (skillsPrompt) blocks.push(skillsPrompt);
    }
    const projectPrompt = projectInstructionsPrompt(instructions ?? undefined);
    if (projectPrompt) blocks.push(projectPrompt);
    return blocks;
  }

  /**
   * A `Task` call that never reached a delegate. pi ignores an `isError` field
   * on a tool result — only a thrown error or `afterToolCall` marks one — so
   * the failure is registered the same way host tool failures are, and throwing
   * is avoided to keep the explanation in the result the model reads.
   */
  private subagentToolError(
    toolCallId: string,
    text: string,
  ): AgentToolResult<unknown> {
    this.failedHostToolCalls.add(toolCallId);
    return {
      content: [{ type: "text", text }],
      details: { error: text },
    };
  }

  /** Every delegation still working; a resume of one is a queueing attempt. */
  private runningDelegationIds(): Set<string> {
    return new Set(
      this.runningDelegations().map((record) => record.delegationId),
    );
  }

  /**
   * Resolve a `Task.resume` id to its chain, or fail with a message that tells
   * the model how to proceed (ADR 0276). The parent only ever sees
   * `delegationId`; the chain identity behind it stays internal.
   */
  private resolveResumeChain(
    resume: string,
    agentName: string,
  ):
    | { ok: true; chain: DelegationChain }
    | { ok: false; message: string } {
    const lookup = this.delegationChains.resolveResume({
      resume,
      agentName,
      runningDelegationIds: this.runningDelegationIds(),
    });
    if (lookup.ok) return lookup;
    const error = lookup.error;
    switch (error.kind) {
      case "unknown":
        return { ok: false, message: this.unknownResumeMessage(resume) };
      case "running":
        return {
          ok: false,
          message: `Delegation ${error.delegationId} is still running. Use TaskSend to append a correction or TaskWait to converge. Resuming a running delegation is not queued.`,
        };
      case "not-resumable":
        return {
          ok: false,
          message:
            error.status === "interrupted"
              ? `Delegation ${resume} was interrupted — the app closed while it worked — so there is nothing to continue. Start a new delegation instead.`
              : `Delegation ${resume} ended as "${error.status}" and cannot be resumed. Only completed or failed delegations continue; start a new delegation instead.`,
        };
      case "agent-mismatch":
        return {
          ok: false,
          message: `Delegation ${resume} belongs to the ${error.expected} subagent, not ${error.actual}. Resume it with the matching agent name, or start a new delegation.`,
        };
      case "over-budget":
        return {
          ok: false,
          message: `Delegation ${resume} has read too much to resume cheaply. Start a new delegation and point it at the specific files it should re-read.`,
        };
    }
  }

  private unknownResumeMessage(resume: string): string {
    return this.delegationChains.unknownResumeError(
      resume,
      this.delegationChains.resumableList({
        runningDelegationIds: this.runningDelegationIds(),
      }),
    );
  }

  /**
   * A chain resolved but has nothing to replay. The caller drops it first, so
   * the id can never be advertised as reusable in its own error (ADR 0279 §4).
   */
  private noHistoryResumeMessage(resume: string): string {
    return this.delegationChains.noHistoryResumeError(
      resume,
      this.delegationChains.resumableList({
        runningDelegationIds: this.runningDelegationIds(),
      }),
    );
  }

  /**
   * The binding a resumed run keeps (ADR 0279 §4). A live chain records the
   * `providerId/modelId` key it resolved, which is preferred here; a chain
   * rebuilt from the transcript only knows the model id. Both paths are limited
   * to this definition's pins, session inheritance, and current override grants.
   */
  private async resumedChainProvider(
    chain: DelegationChain,
    definition: SubagentDefinition,
  ): Promise<RuntimeProviderConfig | undefined> {
    const modelId = chain.latestModelId?.trim().toLowerCase();
    if (!modelId) return undefined;
    const keys = new Set(this.availableSubagentModelKeys());
    if (definition.model) keys.add(subagentModelKey(definition.model));
    for (const pin of definition.fallbackModels ?? []) keys.add(subagentModelKey(pin));
    const binding = (key: string) => keys.has(key)
      ? this.subagentProviders[key] ?? this.subagentOverrideProviders[key]
      : undefined;
    const matches = (candidate: RuntimeProviderConfig | undefined) =>
      candidate?.modelId.trim().toLowerCase() === modelId;
    if (chain.latestModelKey) {
      const keyed = binding(chain.latestModelKey) ??
        await this.resolveSubagentModel(chain.latestModelKey);
      // A known binding must not silently become a different account with the
      // same model id after its grant disappears.
      return matches(keyed) ? keyed : undefined;
    }
    return [
      this.subagentProvider(definition),
      this.provider,
      ...[...keys].map(binding),
    ].find(matches);
  }

  private delegationOverrideProvider(key: string, fresh = false): Promise<RuntimeProviderConfig | undefined> {
    return !fresh && this.subagentModelKeys.has(key) && Object.hasOwn(this.subagentProviders, key)
      ? Promise.resolve(this.subagentProviders[key])
      : this.resolveSubagentModel(key, fresh);
  }

  private async revalidateDelegationModel(model: DelegationModelSelection, role: SubagentDefinition): Promise<RuntimeProviderConfig | undefined> {
    let provider: RuntimeProviderConfig | undefined;
    if (model.source === "pin") {
      if ([role.model, ...(role.fallbackModels ?? [])].some((pin) => pin && subagentModelKey(pin) === model.key)) {
        provider = this.subagentProviders[model.key];
      }
    } else if (model.source === "session") {
      provider = this.provider;
    } else {
      provider = await this.delegationOverrideProvider(model.key, true);
    }
    return matchesDelegationModel(provider, model) ? provider : undefined;
  }

  private legacyDelegationModelSelection(provider: RuntimeProviderConfig, role: SubagentDefinition): DelegationModelSelection | undefined {
    const pin = [role.model, ...(role.fallbackModels ?? [])].find((candidate) =>
      candidate && this.subagentProviders[subagentModelKey(candidate)] === provider,
    );
    if (pin) return delegationModelSelection("pin", subagentModelKey(pin), provider);
    if (provider === this.provider) return delegationModelSelection("session", `${provider.id}/${provider.modelId}`, provider);
    const key = this.availableSubagentModelKeys().find((candidate) =>
      (this.subagentProviders[candidate] ?? this.subagentOverrideProviders[candidate]) === provider,
    );
    if (key) return delegationModelSelection("override", key, provider);
    return undefined;
  }

  /**
   * Rebuild the delegate's prior conversation from its transcript rows. The
   * rows carry `parentToolCallId` for exactly the chain's `Task` calls, so the
   * replay never picks up the parent's own rows or a sibling delegate's.
   */
  private seedResumedDelegate(
    chain: DelegationChain,
    provider: RuntimeProviderConfig,
  ): AgentMessage[] | undefined {
    const originalTask =
      chain.originalTask ??
      originalTaskFromTranscript(this.transcriptHistory, chain);
    if (!originalTask) return undefined;
    const rows = selectChainRows(this.transcriptHistory, chain);
    if (rows.length === 0) return undefined;
    // The seed is truncated against the delegate's own budget (ADR 0299 §7),
    // derived from the same model the resumed run will use, so the first
    // request fits the window instead of overflowing on arrival.
    const model = buildProviderModel(provider);
    return seedDelegateMessages({
      originalTask,
      rows,
      provider,
      model,
      budget: contextBudgetLimitsFor(model),
    });
  }

  /**
   * `Task`: delegate one bounded piece of work to a subagent (ADR 0062).
   *
   * The catalog of definitions rides in this tool's description rather than in
   * the system prompt, because the two change together: a project adding an
   * agent file changes the tool, and nothing else about the prompt.
   */
  private buildSubagentTool(): AgentTool {
    const names = this.subagents.map((definition) => definition.name);
    const catalog = this.subagents
      .map((definition) => {
        const defaultModel = definition.model
          ? `${subagentModelKey(definition.model)}; omit model or repeat this key to keep this default.`
          : "inherits the session.";
        return `- ${definition.name} (tools: ${subagentToolsLabel(definition)}): ${definition.description} Default model: ${defaultModel}`;
      })
      .join("\n");
    return {
      name: SUBAGENT_TOOL_NAME,
      label: "Task",
      description: [
        "Start one subagent in the background and return immediately; you keep working while it runs, then converge with TaskWait when you need its report.\n\nPrefer doing the work yourself. Only delegate when it saves significant context or enables genuine parallelism — not for tasks you can finish in a few tool calls.",
        "Use it only when the work is genuinely separable and substantial: parallel exploration of independent directions that each need many tool calls (one Task per direction in the same assistant message), a large multi-file implementation with a complete spec (fixer), an adversarial read-only review of a non-trivial change you already finished (code-reviewer), or a wide search whose raw output would fill this context (explorer, test-runner). A single file lookup or a small edit does not warrant delegation.",
        "Do not delegate what you can finish in a couple of tool calls, and do not delegate anything that needs the user — a subagent cannot ask a question or propose a plan on your behalf.",
        ...(this.availableSubagentModelKeys().length
          ? [
              "Only pass `model` to intentionally use a listed delegation model or the session's exact model. Repeating the role's own Default model key keeps the pin. Changing a mode-private role's pinned model requires explicit user confirmation for this Task.",
            ]
          : [
              `No delegation model overrides are configured. ${DELEGATION_DEFAULT_MODEL_GUIDANCE} ${DELEGATION_MODEL_OPT_IN_GUIDANCE}`,
            ]),
        "The delegate cannot see this conversation. If the user explicitly names an expert, use that exact role and copy only the relevant, contiguous user text into `userRequest` (required for @expert). Put your paths, assumptions and reporting instructions in `task`, not in `userRequest`. Preserve all user restrictions; report conflicts, and ask for clarification rather than inventing a quote or substituting a role.",
        "Use `scope.write` on a new Task to enforce a one-off write boundary. It only narrows the role's existing access; tools such as Bash that cannot enforce the boundary are withheld. An empty write list forbids writing; omitting scope keeps existing behavior.",
        "Make several Task calls in one assistant message to run them concurrently. Use TaskSend for corrections to a running delegate, TaskWait to converge and TaskStop to cancel. For a settled delegate, pass its `resume` delegationId and omit `model` and `scope`; its original role and restrictions still apply.",
        `Available subagents:\n${catalog}`,
      ].join("\n\n"),
      parameters: Type.Object({
        agent: Type.String({
          description: `Name of the subagent to run: ${names.join(", ")}.`,
        }),
        task: Type.String({
          description:
            "The complete brief: goal, context the delegate cannot infer, and the exact report you want back.",
        }),
        userRequest: Type.Optional(Type.String({ description: "Verbatim relevant words from a user message for this exact expert. Required for an explicit @expert. No paraphrases, coordinator instructions, or unrelated messages." })),
        scope: Type.Optional(Type.Object({
          write: Type.Array(Type.String(), { description: "File or directory paths the delegate may write under; [] forbids all writes." }),
        }, { additionalProperties: false, description: "One-off write boundary for a new delegation; omit on resume." })),
        description: Type.Optional(
          Type.String({
            description:
              "Short label for this delegation (3-6 words), shown to the user.",
          }),
        ),
        model: Type.Optional(
          Type.String({
            description:
              "Override the delegate's model for this run, e.g. 'anthropic/claude-sonnet-4-20250514'. Omit to use the subagent's default. Repeating the definition's own Default model key is the same as omitting this parameter. Only choose a different override from the available delegation model catalog. Forbidden when `resume` is set.",
          }),
        ),
        resume: Type.Optional(
          Type.String({
            description:
              "delegationId of a settled subagent in this conversation to continue. Omit to start a new session.",
          }),
        ),
      }),
      // Set in `rebuildToolCatalog`, which owns every execution mode; repeated
      // here so the intent survives a tool built outside that path.
      executionMode: "parallel",
      execute: async (toolCallId, params, signal) => {
        const requested = isRecord(params) ? String(params.agent ?? "") : "";
        const role = this.subagents.find(
          (candidate) => candidate.name === normalizeSubagentName(requested),
        );
        if (!role) {
          return this.subagentToolError(
            toolCallId,
            `Unknown subagent "${requested}". Available: ${names.join(", ")}.`,
          );
        }
        const definition = structuredClone(role);
        const args = isRecord(params) ? params : {};
        const task = typeof args.task === "string" ? args.task.trim() : "";
        const resume = typeof args.resume === "string" ? args.resume.trim() : "";
        const modelOverride = typeof args.model === "string" ? args.model.trim() : "";
        const fail = (message: string) => this.subagentToolError(toolCallId, message);
        const launchEpoch = this.turnEpoch;
        const launchMode = this.mode;
        const promptSource = this.delegationPrompt;
        const awaitAuthorization = <T>(work: Promise<T>) => signal ? waitForOperation(work, signal) : work;
        const cancelled = () => signal?.aborted || this.disposed || this.runCancelled || this.turnHadError ||
          launchEpoch !== this.turnEpoch || this.pendingSteering.size > 0 || this.delegationPrompt !== promptSource;
        const parentEnded = "The parent turn ended or received new input before delegation could start.";
        if (cancelled()) return fail(parentEnded);
        if ((definition.catalogMode && definition.catalogMode !== launchMode) || (definition.modeOwner && definition.modeOwner !== launchMode)) {
          return fail(`The ${definition.name} role does not belong to the active delegation catalog.`);
        }
        if (!task) return fail(`Delegating to ${definition.name} needs a non-empty \`task\` brief.`);
        if (resume && modelOverride) return fail("Resuming a subagent cannot change its model. Omit `model` or start a new delegation.");
        const parsedScope = parseWriteScope(args.scope);
        if (parsedScope.kind === "invalid") return fail(parsedScope.reason);
        const resumeLookup = resume ? this.resolveResumeChain(resume, definition.name) : undefined;
        if (resumeLookup && !resumeLookup.ok) return fail(resumeLookup.message);
        const resumedChain = resumeLookup?.chain;
        const prior = resumedChain?.policy;
        if (resumedChain?.incompleteSnapshot || (resumedChain && !prior && (definition.catalogMode || definition.modeOwner))) {
          return fail("This delegation has no verifiable role and scope snapshot. Start a new delegation instead.");
        }
        if (resume && parsedScope.kind === "scoped" && (!prior || !sameWriteScope(prior.writeScope, parsedScope.entries))) {
          return fail("Resuming a delegation cannot change its write scope. Omit `scope` to keep its original limits.");
        }
        const writeScope = resume ? prior?.writeScope : parsedScope.kind === "scoped" ? parsedScope.entries : undefined;
        const roleHash = delegationPolicyHash(definition);
        const selectTools = () => selectDelegationTools({
          names: resolveSubagentToolNames(definition, [...this.toolCatalog.keys()]).filter(
            (name) => this.isToolAllowedInMode(name),
          ), catalog: this.toolCatalog, builtins: this.builtinTools, writeScope,
          scopedWritesSupported: !this.remoteWorkspace,
        });
        const { tools, withheld } = selectTools();
        const declaredToolNames = tools.map((tool) => tool.name);
        const policy: DelegationPolicy = {
          mode: launchMode, roleHash,
          workspaceHash: delegationPolicyHash([this.projectPath, this.workspaceRoot, this.remoteWorkspace]),
          toolHash: delegationPolicyHash(tools.map((tool) => [tool.name, this.builtinTools.has(tool), tool.parameters])),
          toolNames: declaredToolNames,
          ...(writeScope ? { writeScope } : {}),
        };
        if (prior && !canResumeDelegation(prior, policy)) {
          return fail("The original workspace, mode, role or tools have changed. Do not reuse its context; start a new delegation under the current permissions.");
        }
        if (!tools.length) return fail(`The ${definition.name} subagent has no available tool${writeScope ? " within this write scope" : " in this session"}.`);

        let currentPrompt: DelegationUserPrompt | undefined;
        if (promptSource) {
          try { currentPrompt = await awaitAuthorization(promptSource()); }
          catch { return fail(cancelled() ? parentEnded : "Could not verify the current user's delegation request. No work was started."); }
          if (cancelled()) return fail(parentEnded);
          if (!currentPrompt) return fail("The current user's delegation request could not be found. No work was started.");
        }
        const quote = validateUserRequest({ value: args.userRequest, agent: definition.name, current: currentPrompt, history: this.transcriptHistory });
        if (!quote.ok) return fail(quote.reason);
        const brief = composeDelegateBrief({ task, userRequest: quote.userRequest });

        const pinKey = definition.model && subagentModelKey(definition.model);
        const override = modelOverride && !this.isDefinitionPinOverride(definition, modelOverride) ? modelOverride : undefined;
        const sessionKey = `${this.provider.id}/${this.provider.modelId}`;
        let provider: RuntimeProviderConfig | undefined;
        let selected: DelegationModelSelection | undefined;
        let modelChangedFrom: string | undefined;
        if (resumedChain?.latestModel) {
          selected = resumedChain.latestModel;
          provider = await awaitAuthorization(this.revalidateDelegationModel(selected, definition)).catch(() => undefined);
          if (cancelled()) return fail(parentEnded);
          if (!provider) return fail("The delegation's recorded model is no longer authorized or available. Start a new delegation to change models.");
        } else if (resumedChain) {
          // Legacy transcript rows know only a model id. Preserve the previous
          // authorization and fallback behavior for legacy global roles.
          const restored = await awaitAuthorization(this.resumedChainProvider(resumedChain, definition)).catch(() => undefined);
          if (cancelled()) return fail(parentEnded);
          provider = restored ?? this.subagentProvider(definition);
          if (!restored) modelChangedFrom = resumedChain.latestModelId;
          if (provider) selected = this.legacyDelegationModelSelection(provider, definition);
        } else if (override && !this.isSessionModelOverride(override)) {
          provider = await awaitAuthorization(this.delegationOverrideProvider(override, !!definition.modeOwner)).catch(() => undefined);
          if (cancelled()) return fail(parentEnded);
          if (provider) selected = delegationModelSelection("override", override, provider);
        } else {
          provider = override ? this.provider : this.subagentProvider(definition);
          if (provider) selected = !override && pinKey
            ? delegationModelSelection("pin", pinKey, provider)
            : delegationModelSelection("session", sessionKey, provider);
        }
        if (!provider || !selected) {
          if (override) {
            const available = this.availableSubagentModelKeys();
            return fail(`Model "${override}" is not available for delegation. ${available.length ? `Available: ${available.join(", ")}.` : `${DELEGATION_DEFAULT_MODEL_GUIDANCE} ${DELEGATION_MODEL_OPT_IN_GUIDANCE}`}`);
          }
          return fail(`The ${definition.name} subagent pins ${pinKey}, which is not configured in PI-Desktop.`);
        }
        if (definition.modeOwner && definition.model && selected.source !== "pin" &&
            !matchesDelegationModel(this.subagentProvider(definition), selected)) {
          const approved = await approveRoleModelChange({
            role: definition, model: `${provider.id}/${provider.modelId}`, sessionId: this.sessionId, toolCallId,
            ask: (request) => this.waitForAskTool(request, signal),
          });
          if (cancelled()) return fail(parentEnded);
          if (!approved) return fail(`The user did not authorize a model change for ${definition.name}. Omit \`model\` on a new Task to keep its configured model.`);
          // Opt-in may have changed while the confirmation was open. The
          // user's one-shot consent only applies to the exact resolved binding.
          if (selected.source === "override") {
            provider = await awaitAuthorization(this.revalidateDelegationModel(selected, definition)).catch(() => undefined);
            if (cancelled()) return fail(parentEnded);
            if (!provider) return fail("The approved model is no longer available for delegation. No work was started.");
          }
        }
        const initialMessages = resumedChain ? this.seedResumedDelegate(resumedChain, provider) : undefined;
        if (resume && !initialMessages) {
          if (resumedChain && this.delegationChains.lookup(resume) === resumedChain) this.delegationChains.drop(resumedChain.delegateSessionId);
          return fail(this.noHistoryResumeMessage(resume));
        }
        const launchError = () => {
          if (cancelled()) return parentEnded;
          const current = this.subagents.find((role) => role.name === definition.name);
          const currentTools = selectTools().tools;
          if (this.mode !== launchMode || this.modeState.closingOut || !this.isToolAllowedInMode(SUBAGENT_TOOL_NAME) || !current ||
              delegationPolicyHash(current) !== roleHash || currentTools.length !== tools.length ||
              currentTools.some((tool, index) => tool !== tools[index])) {
            return `The ${definition.name} role or its tool policy changed. No work was started.`;
          }
          if (resume) {
            const currentChain = this.resolveResumeChain(resume, definition.name);
            if (!currentChain.ok) return currentChain.message;
            if (currentChain.chain !== resumedChain) return "The delegate's history changed while preparing the resume. Read TaskList before trying again.";
          }
          if (this.runningDelegations().length >= MAX_SUBAGENT_CONCURRENCY) {
            return `${MAX_SUBAGENT_CONCURRENCY} subagents are already running for this session. Use TaskWait or TaskStop before delegating more.`;
          }
          return undefined;
        };
        const errorBeforePreparation = launchError();
        if (errorBeforePreparation) return fail(errorBeforePreparation);
        const delegationId = randomUUID();
        const worktreeKey = this.delegateNeedsWorktree(declaredToolNames) ? resumedChain?.delegateSessionId ?? delegationId : undefined;
        let preparedWorktree = false;
        if (worktreeKey && this.preparingDelegateWorktrees.has(worktreeKey)) return fail("This delegate's worktree is already being prepared. Wait for the pending resume.");
        if (worktreeKey) this.preparingDelegateWorktrees.add(worktreeKey);
        try {
          if (worktreeKey) {
            await this.host.call("worktree.delegate.create", { sessionId: this.sessionId, delegationId: worktreeKey });
            preparedWorktree = true;
            const error = launchError();
            if (error) return fail(error);
          }
          // Do not cache role grants or validate before an approval/worktree
          // await: either could have outlived a mode switch or a role edit.
          if (definition.catalogMode) {
            const result = await awaitAuthorization(this.host.call<{ allowed?: boolean }>("delegation.validateRole", {
              sessionId: this.sessionId, mode: definition.catalogMode, role: definition,
            }));
            const error = launchError();
            if (error) return fail(error);
            if (result?.allowed !== true) return fail(`The ${definition.name} role is no longer authorized in this mode. No work was started.`);
          }
          preparedWorktree = false; // ownership transfers to the run below
        } catch (error) {
          if (cancelled()) return fail(parentEnded);
          if (worktreeKey && !preparedWorktree) {
            return fail(`Could not prepare an isolated worktree for the ${definition.name} subagent: ${error instanceof Error ? error.message : String(error)}. No work was started.`);
          }
          return fail(`Could not revalidate the ${definition.name} role. No work was started.`);
        } finally {
          if (worktreeKey) {
            if (preparedWorktree) void this.settleDelegateWorktree(worktreeKey, false, delegationId)
              .finally(() => this.preparingDelegateWorktrees.delete(worktreeKey));
            else this.preparingDelegateWorktrees.delete(worktreeKey);
          }
        }
        const fallbacks = definition.fallbackModels ?? [];
        const lastFallback = resumedChain && selected.source === "pin" && selected.key !== pinKey
          ? fallbacks.findIndex((pin) => subagentModelKey(pin) === selected.key) : -1;
        const startedAt = Date.now();
        const controller = new AbortController();
        const inheritedThinkingLevel = resumedChain?.policy?.inheritedThinkingLevel ?? this.thinkingLevel;
        const thinkingLevel = thinkingForDelegationModel({ role: definition, provider, model: selected, inherited: inheritedThinkingLevel });
        policy.inheritedThinkingLevel = inheritedThinkingLevel;
        // Only TaskStop, user Stop, dispose, and a parent fatal error abort a
        // delegate (D328 / D352). The Task tool call returns immediately; tying
        // the background run to that call's signal would kill it when the parent
        // loop idled.
        const abortSignal = controller.signal;
        let resolveCompletion: () => void = () => {};
        const completion = new Promise<void>((resolve) => {
          resolveCompletion = resolve;
        });
        const label = typeof args.description === "string" ? args.description.trim() : "";
        const chain = this.delegationChains.start({
          delegateSessionId: resumedChain?.delegateSessionId ?? delegationId,
          delegationId,
          toolCallId,
          agentName: definition.name,
          originalTask: resumedChain?.originalTask ?? brief,
          objective: label || task,
          latestModelId: provider.modelId,
          latestModelKey: selected.key,
          policy,
          latestModel: selected,
          resumedFrom: resumedChain,
        });
        const inbox = new DelegationInbox();
        const record: DelegationRecord = {
          delegationId,
          parentToolCallId: toolCallId,
          writable: declaredToolNames.some((name) => PATH_MUTATING_TOOLS.has(name)),
          taskTurnId: this.turnId,
          agentName: definition.name,
          modelId: provider.modelId,
          thinkingLevel,
          status: "running",
          startedAt,
          completion,
          resolveCompletion,
          abort: () => { inbox.close(); controller.abort(); },
          stopRequested: false,
          turns: 0,
          toolCalls: 0,
          lastActivityAt: startedAt,
          lastPhase: "waiting-model",
          startedEpoch: this.turnEpoch,
          reportDelivered: false,
          delegateSessionId: chain.delegateSessionId,
          policy,
          modelSelection: selected,
          instructions: inbox,
          ...(worktreeKey ? { worktreeKey } : {}),
          ...(resumedChain ? { resumedFrom: resume } : {}),
          ...(modelChangedFrom ? { modelChangedFrom } : {}),
        };
        this.delegations.set(delegationId, record);
        let subagentRun: SubagentRun;
        try {
          const delegatePrompt = (instructions: ProjectInstructions | null | undefined) => composeSubagentSystemPrompt({
            definition,
            guidance: this.subagentGuidance(declaredToolNames, instructions, writeScope !== undefined),
            toolNames: declaredToolNames,
            writeScope,
          });
          const applyInstructions = (instructions: ProjectInstructions | undefined) => {
            subagentRun.setSystemPrompt(delegatePrompt(instructions));
          };
          const builtinToolNames = new Set(tools.filter((tool) => this.builtinTools.has(tool)).map((tool) => tool.name));
          const scopedTools = this.scopeDelegateTools(tools, definition, delegationId, worktreeKey, applyInstructions, writeScope);
          subagentRun = new SubagentRun({
            definition,
            sessionId: this.sessionId,
            turnId: this.turnId,
            parentToolCallId: toolCallId,
            delegationId: record.delegationId,
            scratchDir: this.scratchDir,
            task: brief,
            writeScope,
            provider,
            infiniteProviderRetry: this.infiniteProviderRetry,
            thinkingLevel,
            fallbackModels: fallbacks.slice(lastFallback + 1).map((pin) => ({
              key: subagentModelKey(pin),
              provider: this.subagentProviders[subagentModelKey(pin)],
              thinkingLevel: pin.thinkingLevel,
            })),
            inheritedThinkingLevel,
            onModelChange: (next, level, key) => {
              record.modelId = next.modelId;
              record.thinkingLevel = level;
              record.modelSelection = delegationModelSelection("pin", key, next);
              this.delegationChains.retarget(record.delegateSessionId, { modelKey: key, modelId: next.modelId, selection: record.modelSelection });
              this.publishDelegationSettlement(record);
            },
            onInstructionDelivered: (id, content) => {
              if (!inbox.markDelivered(id)) return;
              // Keep the delivered correction in the same runtime's resume seed,
              // never in the parent's model context or as a top-level user row.
              this.transcriptHistory.push({
                id, role: "user", content, createdAt: nowIso(), status: "complete",
                parentToolCallId: toolCallId, agentName: definition.name,
              });
            },
            systemPrompt: delegatePrompt(this.projectInstructions),
            tools: scopedTools,
            beforeToolCall: async (context) => {
              await this.preparePathToolCall(context, applyInstructions, builtinToolNames);
              await this.registerBatchCall(context, builtinToolNames, worktreeKey);
              return undefined;
            },
            onTurnEnd: (message) => this.batchPlanner.settleBatch(message),
            onEvent: (envelope) => {
              this.noteDelegationActivity(record, envelope);
              this.onEvent(envelope);
            },
            // A host failure inside a delegate reaches its tool-error channel
            // through the same bookkeeping the parent uses.
            resolveToolOutcome: (context) => this.resolveOwnToolOutcome(context),
            signal: abortSignal,
            // A resumed run replays its chain before this turn's `task` (ADR 0276).
            ...(initialMessages ? { initialMessages } : {}),
          });
          record.appendInstruction = (instruction) => subagentRun.appendInstruction(instruction);
        } catch {
          // A constructor/scope failure happens after registry allocation. Make
          // it terminal before returning or idle auto-resume will await a
          // completion promise for a worker that never existed.
          record.reportDelivered = true;
          if (worktreeKey) void this.settleDelegateWorktree(worktreeKey, false, delegationId);
          this.settleDelegation(record, {
            agentName: definition.name,
            modelId: provider.modelId,
            thinkingLevel,
            status: "failed",
            report: "",
            turns: 0,
            toolCalls: 0,
            error: {
              code: "SUBAGENT_INITIALIZATION_FAILED",
              message: "The subagent runtime could not be initialized.",
            },
          });
          return this.subagentToolError(
            toolCallId,
            `Could not initialize the ${definition.name} subagent. No work was started.`,
          );
        }

        let runPromise: Promise<SubagentRunResult>;
        try {
          runPromise = subagentRun.run();
        } catch (error) {
          runPromise = Promise.reject(error);
        }
        void runPromise
          .then((result) => this.finishDelegation(record, result))
          .catch((error: unknown) => {
            void this.finishDelegation(record, {
              agentName: definition.name,
              modelId: provider.modelId,
              thinkingLevel,
              status: "failed",
              report: "",
              turns: 0,
              toolCalls: 0,
              error: {
                code: "UNEXPECTED_DELEGATION_REJECTION",
                message:
                  error instanceof Error ? error.message : "unknown error",
              },
            });
          });

        const scopeNote = withheld.length ? ` Write scope withheld these tools: ${withheld.join(", ")}.` : "";
        return {
          content: [
            {
              type: "text",
              text: `Delegation ${delegationId} started: the ${definition.name} subagent is working in the background${label ? ` (${label})` : ""}. Use TaskSend to correct it, TaskWait to converge or TaskStop to stop it.${scopeNote} Job reference: ${JSON.stringify({ kind: "delegation", id: delegationId })}.`,
            },
          ],
          details: {
            delegationId,
            job: { kind: "delegation", id: delegationId },
            agent: definition.name,
            status: "running",
            startedAt,
            modelId: provider.modelId,
            thinkingLevel,
            delegationPolicy: policy,
            delegationModel: selected,
            ...(withheld.length ? { withheldTools: withheld } : {}),
            ...(resumedChain ? { resumedFrom: resume } : {}),
          },
        };
      },
    };
  }

  /** Wrap a delegate's tools with its permission and mutation-recovery scope. */
  private scopeDelegateTools(
    tools: AgentTool[],
    definition: SubagentDefinition,
    mutationOwner: string,
    worktreeKeyOrApply?: string | ((instructions: ProjectInstructions | undefined) => void),
    applyInstructions?: (instructions: ProjectInstructions | undefined) => void,
    writeScope?: readonly string[],
  ): AgentTool[] {
    const worktreeKey = typeof worktreeKeyOrApply === "string" ? worktreeKeyOrApply : undefined;
    const apply = typeof worktreeKeyOrApply === "function" ? worktreeKeyOrApply : applyInstructions;
    const scope = definition.permission ?? DEFAULT_SUBAGENT_PERMISSION;
    // A delegate outlives the turn that started it; keep that turn's identity.
    const turnId = this.delegateExecution.getStore()?.turnId ?? this.turnId;
    return tools.map((tool) => ({
      ...tool,
      execute: (toolCallId, args, signal, onUpdate) => this.delegateExecution.run(
        { owner: mutationOwner, permission: scope, worktreeKey, writeScope, turnId },
        () => this.instructionExecution.run(apply ?? (() => undefined), () => tool.execute(toolCallId, args, signal, onUpdate)),
      ),
    }));
  }

  /**
   * Only inside an isolated session, and only for delegates that can edit
   * files (Write/Edit); Bash-only and read-only delegates share the session
   * worktree (ADR 0329, Q11).
   */
  private delegateNeedsWorktree(toolNames: readonly string[]): boolean {
    return (
      this.workspaceRoot !== undefined &&
      toolNames.some((name) => name === "Write" || name === "Edit")
    );
  }

  /**
   * Settle a delegate's worktree before its report is published: a completed
   * run is merged back into the session worktree, anything else is kept for a
   * resume. The outcome is appended to the report the parent reads.
   */
  private async finishDelegation(
    record: DelegationRecord,
    result: SubagentRunResult,
  ): Promise<void> {
    record.instructions?.close();
    record.appendInstruction = undefined;
    if (record.worktreeKey && record.status === "running") {
      const note = await this.settleDelegateWorktree(
        record.worktreeKey,
        result.status === "completed",
        record.delegationId,
      );
      if (note) result = { ...result, report: result.report ? `${result.report}\n\n${note}` : note };
    }
    const instructionNote = delegationInstructionNote(record);
    if (instructionNote) result = { ...result, report: `${result.report}\n\n${instructionNote}`.trim() };
    this.settleDelegation(record, result);
  }

  /** Ask host-core to settle a delegate worktree; returns a report note. */
  private async settleDelegateWorktree(
    worktreeKey: string,
    merge: boolean,
    delegationId: string,
  ): Promise<string> {
    const resume = `Task(resume: "${delegationId}")`;
    try {
      const { settlement } = await this.host.call<{ settlement: DelegateWorktreeSettlement }>(
        "worktree.delegate.settle",
        { sessionId: this.sessionId, delegationId: worktreeKey, merge },
      );
      return delegateWorktreeNote(settlement, resume);
    } catch (error) {
      return `Isolated worktree: merge-back failed (${
        error instanceof Error ? error.message : String(error)
      }); the subagent's changes are kept. Continue with ${resume} to retry.`;
    }
  }

  /** Records a settled run and wakes every TaskWait waiting on it. */
  private settleDelegation(
    record: DelegationRecord,
    result: SubagentRunResult,
  ): void {
    if (record.status !== "running") return;
    record.instructions?.close();
    record.appendInstruction = undefined;
    if (result.status === "aborted" && record.parentErrorInterrupted && !record.stopRequested) {
      const message = `The parent turn failed and interrupted this delegation. Continue it with Task(resume: "${record.delegationId}").`;
      result = {
        ...result,
        status: "failed",
        report: truncateTextWithMarker(`${message}\n\n${result.report}`, MAX_SUBAGENT_REPORT_CHARS, "\n[report truncated]\n"),
        error: { code: "SUBAGENT_PARENT_FAILED", message, resumeId: record.delegationId },
      };
    }
    record.status =
      record.stopRequested && result.status === "aborted"
        ? "stopped"
        : result.status;
    record.result = result;
    record.completedAt = Date.now();
    // Resolve before event publication or bookkeeping: none of those side
    // effects may strand TaskWait or the parent's idle auto-resume.
    record.resolveCompletion();
    try {
      if (result.usage) {
        this.turnSubagentUsage = addUsage(this.turnSubagentUsage, result.usage);
      }
      this.delegationChains.settle(record.delegateSessionId, record.status);
      // An aborted call never sends `tool_end`, so a settled run drops whatever
      // its calls left behind rather than pinning those arguments for the session.
      for (const toolCallId of record.pendingToolCallIds ?? []) {
        this.delegateToolCalls.delete(toolCallId);
        this.delegateMutationTerminations.delete(toolCallId);
      }
      record.pendingToolCallIds = undefined;
      this.publishDelegationSettlement(record);
    } catch {
      process.stderr.write(
        `[agent-runtime] delegation settlement side effect failed (session=${this.sessionId} delegation=${record.delegationId})\n`,
      );
    } finally {
      this.clearMutationRecovery(record.delegationId);
      this.refreshDelegationWait();
      // The settlement reaches `TaskList` on its next read; nothing here may
      // touch the system prompt, which would invalidate the provider's prompt
      // cache mid-session (ADR 0337).
      this.pruneFinishedDelegations();
    }
  }

  private publishDelegationSettlement(record: DelegationRecord): void {
    if (!record.taskMessage) return;
    const original = record.taskMessage.toolResult;
    const details = isRecord(original) && isRecord(original.details) ? original.details : undefined;
    if (record.status === "running" && details?.modelId === record.modelId && details?.thinkingLevel === record.thinkingLevel) return;
    this.emit(
      {
        type: "message_end",
        message: settledDelegationMessage(record.taskMessage, delegationSummary(record)),
      },
      record.taskTurnId,
    );
  }

  /** Cap retained history so a long session cannot grow the registry forever.
   * Finished records are dropped oldest-first; running ones never are. */
  private pruneFinishedDelegations(): void {
    const finished = [...this.delegations.values()]
      .filter((record) => record.status !== "running")
      .sort((left, right) => (left.completedAt ?? 0) - (right.completedAt ?? 0));
    const excess = finished.length - MAX_RETAINED_DELEGATIONS;
    for (const record of finished.slice(0, Math.max(0, excess))) {
      this.delegations.delete(record.delegationId);
    }
  }

  private runningDelegations(): DelegationRecord[] {
    return [...this.delegations.values()].filter(
      (record) => record.status === "running",
    );
  }

  /** Abort every running delegation (user Stop, dispose, parent fatal error). */
  private abortRunningDelegations(parentErrorInterrupted = false): void {
    for (const record of this.runningDelegations()) {
      record.parentErrorInterrupted = parentErrorInterrupted;
      record.abort();
    }
  }

  private currentTurnDelegations(): DelegationRecord[] {
    return this.runningDelegations().filter(
      (record) => record.startedEpoch === this.turnEpoch,
    );
  }

  /**
   * Current-turn delegates whose report the parent has not seen yet: still
   * running, or settled before the parent idled and never read through
   * `TaskWait`. A delegate that finished in a few hundred milliseconds is
   * "done and unpublished", not "unfinished"; keying the idle resume on
   * running delegates alone dropped such reports (#226). Stopped and
   * aborted runs are not auto-delivered.
   */
  private pendingCurrentTurnDelegations(): DelegationRecord[] {
    return [...this.delegations.values()].filter(
      (record) =>
        record.startedEpoch === this.turnEpoch &&
        !record.reportDelivered &&
        record.status !== "stopped" &&
        record.status !== "aborted",
    );
  }

  private abortDelegationsFromPreviousTurns(): void {
    for (const record of this.runningDelegations()) {
      if (record.startedEpoch !== this.turnEpoch) record.abort();
    }
  }

  /**
   * Parent fatal error: abort leftover delegates so the session can go idle
   * and Continue is not rejected as `AGENT_BUSY` (D352).
   */
  private terminateParentTurn(): void {
    this.turnHadError = true;
    this.acceptingSteering = false;
    this.steeringWaitAbort?.abort();
    this.retainPendingSteering();
    this.abortRunningDelegations(!this.runCancelled && !this.disposed);
    this.delegationWaitTargets = undefined;
    this.clearAgentActivity();
  }

  /** D328 keeps the turn open on parent idle, not on a fatal parent error. */
  private keepTurnOpenForDelegates(): boolean {
    return (
      (this.runningDelegations().length > 0 ||
        this.pendingCurrentTurnDelegations().length > 0) &&
      !this.runCancelled &&
      !this.turnHadError
    );
  }

  private noteDelegationActivity(
    record: DelegationRecord,
    envelope: AgentEventEnvelope,
  ): void {
    record.lastActivityAt = Date.now();
    const event = envelope.event;
    if (event.type === "turn_start") {
      record.turns += 1;
      this.touchDelegationPhase(record, "waiting-model");
      return;
    }
    if (event.type === "tool_start") {
      record.toolCalls += 1;
      this.touchDelegationPhase(record, "tool", event.toolName);
      // The row a later `resume` replays needs the call's arguments, and
      // `tool_end` carries only the result (ADR 0279 §3).
      this.delegateToolCalls.set(event.toolCallId, {
        name: event.toolName,
        args: (envelope.event as ToolStartEvent).args,
      });
      (record.pendingToolCallIds ??= new Set()).add(event.toolCallId);
      return;
    }
    if (event.type === "tool_end") {
      this.touchDelegationPhase(record, "waiting-model");
      this.appendDelegationRow(record, envelope, this.toolRowFromEnvelope(envelope));
      // The call is finished; its arguments are no longer needed.
      this.delegateToolCalls.delete(event.toolCallId);
      record.pendingToolCallIds?.delete(event.toolCallId);
      return;
    }
    if (event.type === "message_end" && event.message.role === "assistant") {
      this.appendDelegationRow(record, envelope, event.message);
    }
    if (
      (event.type === "message_start" || event.type === "message_update") &&
      event.message.role === "assistant"
    ) {
      const thinking = Boolean(
        event.message.thinking?.trim() ||
          (event.type === "message_update" && event.deltaThinking),
      );
      const text = Boolean(
        event.message.content?.trim() ||
          (event.type === "message_update" && event.deltaText),
      );
      if (thinking && !text) this.touchDelegationPhase(record, "thinking");
    }
  }

  /**
   * Keep `transcriptHistory` current with what a delegate produced, so a later
   * `Task.resume` in the same session replays the chain without waiting on
   * persistence (ADR 0276). A retried stream reuses the row id and appends once.
   */
  private appendDelegationRow(
    record: DelegationRecord,
    envelope: AgentEventEnvelope,
    row: UiMessage,
  ): void {
    const tagged: UiMessage = {
      ...row,
      parentToolCallId: envelope.parentToolCallId ?? row.parentToolCallId,
      nestedParentToolCallId: envelope.nestedParentToolCallId ?? row.nestedParentToolCallId,
      agentName: envelope.agentName ?? row.agentName,
    };
    const key =
      tagged.role === "tool"
        ? `tool:${tagged.toolCallId ?? ""}`
        : `message:${tagged.id ?? ""}`;
    if (key.endsWith(":")) return;
    if (this.appendedDelegationRowIds.has(key)) return;
    this.appendedDelegationRowIds.add(key);
    this.transcriptHistory.push(tagged);
    if (tagged.role === "tool" && isReadOnlyToolName(tagged.toolName ?? "")) {
      const { files, lineCount } = extractReadFiles([tagged]);
      this.delegationChains.noteReads(record.delegateSessionId, files, lineCount);
    }
  }

  private toolRowFromEnvelope(envelope: AgentEventEnvelope): UiMessage {
    const event = envelope.event as ToolEndEvent;
    const call = this.delegateToolCalls.get(event.toolCallId);
    const ts = new Date(envelope.ts ?? Date.now()).toISOString();
    return {
      id: `delegate-tool-${event.toolCallId}`,
      role: "tool",
      content: "",
      createdAt: ts,
      toolCompletedAt: ts,
      toolCallId: event.toolCallId,
      toolName: call?.name ?? "",
      toolArgs: call?.args,
      toolResult: event.result,
      toolStatus: event.isError ? "error" : "success",
      isError: Boolean(event.isError),
      parentToolCallId: envelope.parentToolCallId,
      nestedParentToolCallId: envelope.nestedParentToolCallId,
      agentName: envelope.agentName,
    };
  }

  private touchDelegationPhase(
    record: DelegationRecord,
    phase: AgentActivityAgentPhase,
    toolName?: string,
  ): void {
    const nextTool = toolName ?? record.lastToolName;
    if (record.lastPhase === phase && record.lastToolName === nextTool) return;
    record.lastPhase = phase;
    if (toolName) record.lastToolName = toolName;
    this.refreshDelegationWait();
  }

  private beginDelegationWait(targets: DelegationRecord[]): void {
    const running = targets.filter((record) => record.status === "running");
    if (running.length === 0) return;
    this.delegationWaitTargets = targets;
    const since =
      this.agentActivity?.phase === "waiting-subagents"
        ? this.agentActivity.since
        : Date.now();
    this.setAgentActivity(waitingSubagentsActivity(targets, since));
  }

  private refreshDelegationWait(): void {
    if (
      !this.delegationWaitTargets ||
      this.agentActivity?.phase !== "waiting-subagents"
    ) {
      return;
    }
    const running = this.delegationWaitTargets.filter(
      (record) => record.status === "running",
    );
    if (running.length === 0) return;
    this.setAgentActivity(
      waitingSubagentsActivity(
        this.delegationWaitTargets,
        this.agentActivity.since,
      ),
    );
  }

  private endDelegationWait(): void {
    this.delegationWaitTargets = undefined;
    if (this.agentActivity?.phase === "waiting-subagents") {
      this.clearAgentActivity();
    }
  }

  /**
   * Keep the parent turn open until running delegates finish, then feed their
   * reports back so the main agent can continue (D328). User Stop / dispose
   * set `runCancelled` and abort the delegates instead. A parent fatal error
   * aborts leftover delegates and returns without a resume prompt (D352).
   */
  private async resumeAfterDelegations(): Promise<void> {
    if (this.disposed || this.runCancelled || this.turnHadError) {
      if (this.turnHadError) this.terminateParentTurn();
      return;
    }
    const epoch = this.turnEpoch;
    while (
      !this.disposed &&
      !this.runCancelled &&
      !this.turnHadError &&
      epoch === this.turnEpoch &&
      this.pendingCurrentTurnDelegations().length > 0
    ) {
      const targets = this.pendingCurrentTurnDelegations();
      this.beginDelegationWait(targets);
      const waitAbort = new AbortController();
      this.steeringWaitAbort = waitAbort;
      try {
        if (!this.pendingSteering.size) {
          await this.waitForDelegations(targets, targets.length, null, waitAbort.signal);
        }
      } finally {
        if (this.steeringWaitAbort === waitAbort) this.steeringWaitAbort = undefined;
        this.endDelegationWait();
      }
      if (this.pendingSteering.size && !this.runCancelled && !this.turnHadError) {
        await this.waitForIdleAndSteering();
        if (!(await this.runPendingRecoveries())) return;
        continue;
      }
      if (
        this.disposed ||
        this.runCancelled ||
        this.turnHadError ||
        epoch !== this.turnEpoch
      ) {
        if (this.turnHadError) this.terminateParentTurn();
        return;
      }
      const settled = targets.filter(
        (record) => record.status !== "running" && !record.reportDelivered,
      );
      if (settled.length === 0) return;
      const results = settled.map((record) => ({
        delegationId: record.delegationId,
        agent: record.agentName,
        status: record.status,
        report:
          record.result?.report ?? `(${record.status} without a report)`,
      }));
      const still = this.currentTurnDelegations();
      const heartbeat =
        still.length > 0
          ? `Still running:\n${still.map(formatDelegationHeartbeat).join("\n")}`
          : "";
      const formatted = formatDelegationResults(results);
      for (const record of settled) {
        if (formatted.includedDelegationIds.has(record.delegationId)) {
          record.reportDelivered = true;
        }
      }
      const text = [
        DELEGATION_RESUME_PROMPT,
        formatted.text,
        heartbeat,
      ]
        .filter((part) => part.trim())
        .join("\n\n");
      this.requestStartedAt = Date.now();
      await this.agent.prompt(text);
      await this.waitForIdleAndSteering();
      if (!(await this.runPendingRecoveries())) return;
      if (this.turnHadError || epoch !== this.turnEpoch) {
        if (this.turnHadError) this.terminateParentTurn();
        return;
      }
    }
  }

  private buildSubagentSendTool(): AgentTool {
    return {
      name: SUBAGENT_SEND_TOOL_NAME,
      label: "Task Send",
      description: "Queue a coordinator instruction for a running Task in this conversation. It can reach the same run only at the next model or tool boundary. A queued reply is not delivery confirmation; use TaskList or TaskWait for the instruction's status. This does not change the role, model, or write permissions.",
      parameters: Type.Object({
        delegationId: Type.String({ description: "The running delegationId returned by Task." }),
        instruction: Type.String({ maxLength: MAX_DELEGATE_INSTRUCTION_CHARS, description: "The correction or additional context, not a new task or a user quote." }),
      }),
      execute: async (toolCallId, params, signal) => {
        const args = isRecord(params) ? params : {};
        const delegationId = typeof args.delegationId === "string" ? args.delegationId.trim() : "";
        const record = this.delegations.get(delegationId);
        if (signal?.aborted || this.disposed || this.runCancelled || this.turnHadError ||
            record?.status !== "running" || !record.instructions || !record.appendInstruction || record.policy?.mode !== this.mode) {
          return this.subagentToolError(toolCallId, "No matching delegate in this conversation is accepting instructions. For a settled delegation, use Task.resume if eligible.");
        }
        const id = randomUUID();
        const accepted = record.instructions.accept({ id, text: typeof args.instruction === "string" ? args.instruction : "" });
        if (!accepted.ok) return this.subagentToolError(toolCallId, accepted.reason);
        if (!record.appendInstruction(accepted.instruction)) {
          record.instructions.close();
          return this.subagentToolError(toolCallId, "The delegation already ended. The instruction was not delivered.");
        }
        return {
          content: [{ type: "text", text: `Instruction ${id} queued for ${delegationId}, not yet delivered. Check TaskList or TaskWait for delivery status.` }],
          details: { delegationId, instructionId: id, status: "queued" },
        };
      },
    };
  }

  /** `TaskWait`: converge on running delegations (ADR 0089). */
  private buildSubagentWaitTool(): AgentTool {
    return {
      name: SUBAGENT_WAIT_TOOL_NAME,
      label: "Task Wait",
      description:
        "Wait for one or more subagents started by Task and return their reports. `delegationIds` defaults to every running subagent; use mode \"any\" with `minCompleted` to converge as soon as the first (or first N) finish. Settled delegations return immediately, so re-reading a report by id is cheap. New user input interrupts the wait without canceling delegates; handle it before waiting again. A wait timeout is not a failure: unfinished delegates keep working and the runtime delivers their reports when they finish.",
      parameters: Type.Object({
        delegationIds: Type.Optional(
          Type.Array(
            Type.String({ description: "Delegation ids returned by Task." }),
            { description: "Defaults to all running subagents." },
          ),
        ),
        mode: Type.Optional(
          Type.Union([Type.Literal("all"), Type.Literal("any")], {
            description: "Wait for every target (all) or the first to finish (any).",
          }),
        ),
        minCompleted: Type.Optional(
          Type.Number({
            minimum: 1,
            description: "With mode \"any\": wait until at least this many finished.",
          }),
        ),
        timeoutSeconds: Type.Optional(
          Type.Number({
            minimum: 1,
            maximum: TASKWAIT_MAX_TIMEOUT_SECONDS,
            description: `Max seconds to wait; defaults to ${TASKWAIT_DEFAULT_TIMEOUT_SECONDS}.`,
          }),
        ),
      }),
      executionMode: "sequential",
      execute: async (_toolCallId, params, signal) => {
        const ids =
          isRecord(params) && Array.isArray(params.delegationIds)
            ? params.delegationIds.map(String)
            : [];
        const mode = isRecord(params) && params.mode === "any" ? "any" : "all";
        const minCompleted =
          isRecord(params) && typeof params.minCompleted === "number"
            ? Math.max(1, Math.floor(params.minCompleted))
            : 1;
        const timeoutSeconds =
          isRecord(params) && typeof params.timeoutSeconds === "number"
            ? Math.min(
                Math.max(1, Math.floor(params.timeoutSeconds)),
                TASKWAIT_MAX_TIMEOUT_SECONDS,
              )
            : TASKWAIT_DEFAULT_TIMEOUT_SECONDS;

        const targets = ids.length
          ? ids
              .map((id) => this.delegations.get(id))
              .filter((record): record is DelegationRecord => record !== undefined)
          : this.runningDelegations();
        if (targets.length === 0) {
          const text = ids.length
            ? "None of the requested delegation ids exist in this session. Call TaskList to see them."
            : "No subagents are currently running.";
          return {
            content: [{ type: "text", text }],
            details: { delegations: [] },
          };
        }
        const unknownIds = ids.filter((id) => !this.delegations.has(id));
        const targetCompleted =
          mode === "all"
            ? targets.length
            : Math.min(Math.max(minCompleted, 1), targets.length);
        const deadline = Date.now() + timeoutSeconds * 1000;
        this.beginDelegationWait(targets);
        const waitAbort = new AbortController();
        this.steeringWaitAbort = waitAbort;
        let timedOut = false;
        try {
          if (!this.pendingSteering.size) {
            timedOut = await this.waitForDelegations(
              targets,
              targetCompleted,
              deadline,
              signal ? AbortSignal.any([signal, waitAbort.signal]) : waitAbort.signal,
            );
          }
        } finally {
          if (this.steeringWaitAbort === waitAbort) this.steeringWaitAbort = undefined;
          this.endDelegationWait();
        }
        const interrupted = this.pendingSteering.size > 0 && !signal?.aborted &&
          !this.runCancelled && !this.disposed && !this.turnHadError;
        // A settled report included in this bounded result reached the parent;
        // the idle resume must not deliver it a second time. Omitted reports
        // stay pending so the idle resume can deliver them later. Running
        // delegates keep their shot: a timeout or early `any` convergence has
        // not consumed it.
        const results = targets.map((record) => ({
          delegationId: record.delegationId,
          agent: record.agentName,
          status: record.status,
          modelId: record.modelId,
          thinkingLevel: record.thinkingLevel,
          startedAt: record.startedAt,
          ...(record.completedAt ? { completedAt: record.completedAt } : {}),
          ...delegationInstructionDetails(record),
          ...(record.result?.error ? { error: record.result.error } : {}),
          ...(record.result?.scratchReportPath
            ? { scratchReportPath: record.result.scratchReportPath }
            : {}),
          report:
            record.status === "running"
              ? formatDelegationHeartbeat(record)
              : (record.result?.report ?? `(${record.status} without a report)`),
        }));
        const note = interrupted
          ? "Interrupted by new user input. Unfinished subagents keep working; handle the user's message before waiting again."
          : timedOut
            ? `Still running after ${timeoutSeconds}s: ${results.filter((r) => r.status !== "running").length}/${targets.length} finished. This is not a failure — unfinished delegates keep working and the runtime will deliver their reports when they finish. Call TaskStop only to cancel.\n${targets
                .filter((record) => record.status === "running")
                .map(formatDelegationHeartbeat)
                .join("\n")}`
            : mode === "any"
              ? `Converged after ${results.filter((r) => r.status !== "running").length} of ${targets.length} finished.`
              : undefined;
        const unknownNote =
          unknownIds.length > 0
            ? `Unknown delegation ids (not found in this session): ${unknownIds.join(", ")}.`
            : undefined;
        const formatted = formatDelegationResults(
          results,
          [note, unknownNote].filter(Boolean).join("\n") || undefined,
        );
        for (const record of targets) {
          if (
            record.status !== "running" &&
            formatted.includedDelegationIds.has(record.delegationId)
          ) {
            record.reportDelivered = true;
          }
        }
        return {
          content: [
            {
              type: "text",
              text: formatted.text,
            },
          ],
          details: {
            status: interrupted ? "interrupted" : timedOut ? "timeout" : "completed",
            ...(unknownIds.length ? { unknownIds } : {}),
            delegations: results,
          },
        };
      },
    };
  }

  /**
   * Resolve once `targetCompleted` of the targets are settled, or the deadline
   * passes, or the calling run aborts. Returns true on timeout/abort.
   * `deadline` null waits until they settle (D328 auto-resume).
   */
  private waitForDelegations(
    targets: DelegationRecord[],
    targetCompleted: number,
    deadline: number | null,
    signal?: AbortSignal,
  ): Promise<boolean> {
    const settledCount = () =>
      targets.filter((record) => record.status !== "running").length;
    if (settledCount() >= targetCompleted) return Promise.resolve(false);
    if (signal?.aborted) return Promise.resolve(true);
    return new Promise<boolean>((resolve) => {
      let done = false;
      const finish = (timedOut: boolean) => {
        if (done) return;
        done = true;
        if (timer !== undefined) clearTimeout(timer);
        signal?.removeEventListener("abort", onAbort);
        resolve(timedOut);
      };
      const check = () => {
        if (settledCount() >= targetCompleted) finish(false);
      };
      for (const record of targets) {
        if (record.status === "running") {
          record.completion.then(check);
        }
      }
      const onAbort = () => finish(true);
      signal?.addEventListener("abort", onAbort, { once: true });
      const timer =
        deadline === null
          ? undefined
          : setTimeout(() => finish(true), Math.max(0, deadline - Date.now()));
    });
  }

  /** `TaskList`: report on the session's delegations (ADR 0089). */
  private buildSubagentListTool(): AgentTool {
    return {
      name: SUBAGENT_LIST_TOOL_NAME,
      label: "Task List",
      description:
        "List the subagents started by Task in this session with their status, plus the subagent sessions that `Task(resume: ...)` can continue. Use it to check progress without waiting, to find a resumable delegation id, or before TaskStop to choose what to stop.",
      parameters: Type.Object({}),
      executionMode: "sequential",
      execute: async () => {
        const delegations = [...this.delegations.values()].sort(
          (left, right) => left.startedAt - right.startedAt,
        );
        // Resumability is reported here rather than in the system prompt
        // (ADR 0337): the list changes on every settlement, and rewriting the
        // instructions mid-session invalidates the provider's cached request
        // prefix. A result the model reads on demand costs nothing otherwise.
        const runningDelegationIds = this.runningDelegationIds();
        const resumable = this.delegationChains.resumableList({
          runningDelegationIds,
        });
        const text = [
          delegations.length === 0
            ? "No subagents have been started in this session."
            : delegations
                .map((record) => `- ${formatDelegationHeartbeat(record)}; delegationIds=${JSON.stringify([record.delegationId])} ${delegationInstructionNote(record)}`.trimEnd())
                .join("\n"),
          this.delegationChains.resumableBlock({ runningDelegationIds }),
        ]
          .filter((part) => part.trim())
          .join("\n\n");
        return {
          content: [{ type: "text", text }],
          details: {
            delegations: delegations.map(record => ({ ...delegationSummary(record), job: { kind: "delegation", id: record.delegationId } })),
            resumable: resumable.map((chain) => ({
              agent: chain.agentName,
              delegationId: chain.latestDelegationId,
              objective: chain.latestObjective,
              ...listedReadFiles(chain.readFiles),
            })),
          },
        };
      },
    };
  }

  /** Shared cancellation path for TaskStop and explicit desktop controls. */
  async stopSubagents(ids: string[] = []) {
    const targets = ids.length
      ? [...new Set(ids)]
          .map((id) => this.delegations.get(id))
          .filter(
            (record): record is DelegationRecord =>
              record !== undefined && record.status === "running",
          )
      : this.runningDelegations();
    for (const record of targets) {
      record.stopRequested = true;
      record.abort();
    }
    // Cancellation is cooperative: bound the wait so a worker that ignores
    // abort cannot wedge the caller. Still-running workers are
    // explicitly returned as pending, never mislabeled as stopped.
    let stopTimeout: ReturnType<typeof setTimeout> | undefined;
    await Promise.race([
      Promise.all(targets.map((record) => record.completion)),
      new Promise<void>((resolve) => {
        stopTimeout = setTimeout(resolve, 5_000);
      }),
    ]);
    if (stopTimeout !== undefined) clearTimeout(stopTimeout);
    const pending = targets.filter((record) => record.status === "running");
    const stopped = targets.filter((record) => record.status === "stopped");
    const settled = targets.filter(
      (record) => record.status !== "running" && record.status !== "stopped",
    );
    const text =
      targets.length === 0
        ? "No matching running subagents to stop."
        : pending.length > 0
          ? `Cancellation requested for ${targets.length} subagent${targets.length === 1 ? "" : "s"}; ${pending.length} have not confirmed termination and remain running.`
          : settled.length > 0
            ? `Cancellation settled for ${targets.length} subagent${targets.length === 1 ? "" : "s"}: ${stopped.length} stopped and ${settled.length} had already finished.`
            : `Stopped ${stopped.length} subagent${stopped.length === 1 ? "" : "s"}.`;
    return {
      content: [{ type: "text" as const, text }],
      details: {
        stopped: stopped.map(delegationSummary),
        ...(pending.length > 0
          ? { stopPending: pending.map(delegationSummary) }
          : {}),
        ...(settled.length > 0
          ? { settled: settled.map(delegationSummary) }
          : {}),
      },
    };
  }

  /** `TaskStop`: stop running delegations (ADR 0089). */
  private buildSubagentStopTool(): AgentTool {
    return {
      name: SUBAGENT_STOP_TOOL_NAME,
      label: "Task Stop",
      description:
        "Request cancellation for one or more running subagents. `delegationIds` defaults to every running subagent. A subagent is reported as stopped only after it confirms termination; an unresponsive subagent remains running.",
      parameters: Type.Object({
        delegationIds: Type.Optional(
          Type.Array(
            Type.String({ description: "Delegation ids returned by Task." }),
            { description: "Defaults to all running subagents." },
          ),
        ),
      }),
      executionMode: "sequential",
      execute: async (_toolCallId, params) => {
        const ids =
          isRecord(params) && Array.isArray(params.delegationIds)
            ? params.delegationIds.map(String)
            : [];
        return this.stopSubagents(ids);
      },
    };
  }

  private selectedMcpTools(input: string | RuntimePrompt): string[] {
    return resolveMcpToolSelection(
      typeof input === "string" ? undefined : input.mcpServerIds,
      this.pluginTools,
      name => this.toolCatalog.has(name) && this.isToolAllowedInMode(name),
      typeof input === "string" ? undefined : input.mcpToolNames,
    );
  }

  private activateDeferredTools(names: readonly string[]): string[] {
    const activated = names.filter(name => this.deferredToolNames.has(name)
      && !this.activeDeferredToolNames.has(name));
    for (const name of activated) this.activeDeferredToolNames.add(name);
    return activated;
  }

  private findDeferredTools(query: string): string[] {
    const normalizedQuery = query.toLowerCase();
    if (!normalizedQuery) return [];
    const terms = normalizedQuery.split(/[\s,;|/]+/).filter(Boolean);
    return [...this.deferredToolNames]
      .map((name) => {
        const tool = this.toolCatalog.get(name);
        const normalizedName = name.toLowerCase();
        const description = tool?.description.toLowerCase() ?? "";
        let score = 0;
        if (normalizedName === normalizedQuery) score += 10_000;
        else if (normalizedName.includes(normalizedQuery)) score += 2_000;
        for (const term of terms) {
          if (normalizedName.includes(term)) score += 300;
          if (description.includes(term)) score += 25;
        }
        return { name, score };
      })
      .filter((candidate) => candidate.score > 0)
      .sort((left, right) => right.score - left.score)
      .slice(0, 4)
      .map((candidate) => candidate.name);
  }

  private resetDeferredToolsForPrompt(): void {
    // Sticky activation (#1225): on-demand tools stay active for the whole
    // session instead of being reset at every prompt. A context-only restore
    // drops the activation whenever the announcing rows fall out of the window
    // (compaction, long turns), and the next direct call then fails with
    // "Tool <name> not found" at name resolution — the intermittent 0 ms
    // rejection on Windows. `rebuildToolCatalog` still prunes names that left
    // the catalog (mode switches, extension reloads), so the set cannot
    // outlive the tools it names.
    this.restoreDeferredToolsFromContext();
    this.setAgentTools(this.activeTools());
  }

  /**
   * Re-activates the on-demand tools whose successful activation the model
   * can still see. The context keeps every ToolSearch result that announced
   * "Activated on-demand tools: X" and every result X itself produced, so
   * starting a turn with an empty set while those rows remain leaves the
   * model calling tools that are missing from the schema (#225). Only
   * successful results count, and only for names still in the deferred
   * catalog, which `rebuildToolCatalog` already limits to the current mode.
   */
  private restoreDeferredToolsFromContext(): void {
    if (this.deferredToolNames.size === 0) return;
    if (this.trackToolActivation && this.activationHydrated) return;
    const { messages } = this.liveSessionContext();
    const restored = this.declarationPolicy && restoredToolActivation(messages, this.declarationPolicy.key);
    if (restored !== undefined) {
      this.trackToolActivation = true;
      for (const name of restored.active) {
        if (this.deferredToolNames.has(name)) this.activeDeferredToolNames.add(name);
      }
    }
    this.activationHydrated = true;
    const lastSystem = restored ? restored.replayFrom - 1 : messages.map((message) => message.role).lastIndexOf("system");
    if (!restored && lastSystem >= 0) {
      for (const tool of getCurrentTools(messages)) {
        if (this.deferredToolNames.has(tool.name)) this.activeDeferredToolNames.add(tool.name);
      }
    }
    // Legacy histories lack declarations. For current histories, only results
    // after the last declaration can represent an activation not yet declared.
    for (const message of messages.slice(lastSystem + 1)) {
      if (restored && (message.role !== "toolResult" || message.toolName !== TOOL_SEARCH_NAME)) continue;
      if (message.role !== "toolResult" || message.isError) continue;
      if (isMissingToolResultPlaceholder(message.content)) continue;
      const names =
        message.toolName === TOOL_SEARCH_NAME
          ? toolSearchActivatedNames(
              message.details,
              (message as unknown as { addedToolNames?: unknown }).addedToolNames,
            )
          : [message.toolName];
      for (const name of names) {
        if (this.deferredToolNames.has(name)) {
          this.activeDeferredToolNames.add(name);
        }
      }
    }
  }

  private buildSubmitTool(kind: ProposalKind): AgentTool {
    const name = SUBMIT_TOOL_NAMES[kind];
    return {
      name,
      label: kind === "plan" ? "Submit plan" : "Submit goal",
      description:
        kind === "plan"
          ? "Submit one new complete Markdown implementation plan for user approval. Prior submissions are immutable historical checkpoints; after a rejected, expired, or interrupted approval, revise the plan and submit a new full snapshot in this turn. Do not use this until the plan is concrete."
          : "Submit one new complete Markdown goal contract for user approval: the outcome to reach, the acceptance criteria that prove it, and the boundaries you must not cross. Prior submissions are immutable historical checkpoints; after a rejected, expired, or interrupted approval, revise the contract and submit a new full snapshot in this turn. Do not use this until the goal is unambiguous and every criterion is checkable.",
      parameters: Type.Object({
        title: Type.String({
          description:
            kind === "plan"
              ? "A concise title for the implementation plan."
              : "A concise title naming the goal.",
        }),
        markdown: Type.String({
          description:
            kind === "plan"
              ? "The exact Markdown implementation plan, including files, behavior, and validation."
              : "The exact Markdown goal contract, with a Goal section, an Acceptance criteria section of objectively checkable items, and a Boundaries section. Describe outcomes, not implementation steps.",
        }),
        question: Type.String({
          description:
            kind === "plan"
              ? "The question or decision the user should answer when approving this plan."
              : "The question or decision the user should answer when approving this goal contract.",
        }),
      }),
      executionMode: "sequential",
      execute: async (toolCallId, params) => {
        const title =
          isRecord(params) && typeof params.title === "string"
            ? params.title.trim()
            : "";
        const markdown =
          isRecord(params) && typeof params.markdown === "string"
            ? params.markdown
            : "";
        const question =
          isRecord(params) && typeof params.question === "string"
            ? params.question.trim()
            : "";
        if (!title || !markdown.trim() || !question) {
          return {
            content: [
              {
                type: "text",
                text: `${name} requires non-empty title, markdown, and question.`,
              },
            ],
            details: { errorCode: "PLAN_INVALID_ARGUMENT" },
            isError: true,
          };
        }
        let result: { status?: string; proposal?: PlanProposal };
        try {
          result = await this.host.call("plans.submit", {
            sessionId: this.sessionId,
            // This is the durable host turn ID passed into the runtime for the
            // current prompt, not a newly generated provider-side identifier.
            turnId: this.turnId,
            toolCallId,
            kind,
            title,
            markdown,
            question,
          });
        } catch (error) {
          const recovery = planWorkspaceRequiredResult(error);
          if (recovery) return recovery;
          const errorCode =
            (error as { data?: { errorCode?: string } })?.data?.errorCode ??
            "PLAN_SUBMIT_FAILED";
          return {
            content: [
              {
                type: "text",
                text: `${modeLabel(kind)} submission failed: ${errorCode}`,
              },
            ],
            details: { errorCode },
            isError: true,
            terminate: true,
          };
        }

        const proposal = result.proposal;
        if (
          result.status !== "pending" ||
          !proposal ||
          typeof proposal.id !== "string" ||
          !proposal.artifact ||
          typeof proposal.artifact.relativePath !== "string" ||
          typeof proposal.artifact.sha256 !== "string" ||
          typeof proposal.artifact.sizeBytes !== "number"
        ) {
          return {
            content: [
              {
                type: "text",
                text: `${modeLabel(kind)} submission returned an invalid proposal.`,
              },
            ],
            details: { errorCode: "PLAN_SUBMIT_FAILED" },
            isError: true,
            terminate: true,
          };
        }

        this.setPlanningState("awaiting_approval", {
          kind,
          proposalId: proposal.id,
          title: proposal.title || title,
          markdown: proposal.markdown || markdown,
          question: proposal.question || question,
          artifact: proposal.artifact,
          version: proposal.version,
          plan: proposal.markdown || markdown,
          executionId: proposal.executionId,
          executionState: proposal.executionState,
          proposal,
        });
        return {
          content: [
            {
              type: "text",
              text:
                kind === "plan"
                  ? "Plan submitted for approval. Execution will begin only after approval."
                  : "Goal contract submitted for approval. Autonomous execution will begin only after approval.",
            },
          ],
          details: { proposal },
          terminate: true,
        };
      },
    };
  }

  private normalizeAskQuestions(params: unknown): AskToolQuestion[] | undefined {
    if (!isRecord(params) || !Array.isArray(params.questions)) return undefined;
    const questions: AskToolQuestion[] = [];
    for (const raw of params.questions) {
      if (!isRecord(raw)) return undefined;
      const question = typeof raw.question === "string" ? raw.question.trim() : "";
      if (!question || !isAskToolQuestionWithinLimit(question)) return undefined;
      const options: AskToolQuestion["options"] = [];
      const seenLabels = new Set<string>();
      if (Array.isArray(raw.options)) {
        for (const rawOption of raw.options) {
          const option = normalizeAskToolOption(rawOption);
          if (!option) continue;
          const label = askToolOptionLabel(option);
          if (seenLabels.has(label)) continue;
          seenLabels.add(label);
          options.push(option);
        }
      }
      if (options.length === 0) return undefined;
      questions.push({
        question,
        options,
        ...(raw.multiSelect === true ? { multiSelect: true } : {}),
      });
    }
    return questions.length > 0 && questions.length <= 20 ? questions : undefined;
  }

  private waitForAskTool(
    request: AskToolRequest,
    signal?: AbortSignal,
  ): Promise<Array<string[] | null>> {
    return new Promise((resolve) => {
      let settled = false;
      const finish = (answers: Array<string[] | null>) => {
        if (settled) return;
        settled = true;
        signal?.removeEventListener("abort", abort);
        this.pendingAskTools.delete(request.requestId);
        resolve(answers);
      };
      const abort = () => finish(request.questions.map(() => null));
      this.pendingAskTools.set(request.requestId, { request, resolve: finish });
      this.emit({ type: "asktool_request", request });
      if (signal?.aborted) abort();
      else signal?.addEventListener("abort", abort, { once: true });
    });
  }

  resolveAskTool(resolution: AskToolResolution): { ok: boolean } {
    if (resolution.sessionId !== this.sessionId) {
      throw Object.assign(new Error("asktool session mismatch"), {
        errorCode: "ASKTOOL_NOT_FOUND",
      });
    }
    const pending = this.pendingAskTools.get(resolution.requestId);
    if (!pending) {
      throw Object.assign(new Error("asktool request is no longer pending"), {
        errorCode: "ASKTOOL_NOT_FOUND",
      });
    }
    if (!Array.isArray(resolution.answers) || resolution.answers.length !== pending.request.questions.length) {
      throw Object.assign(new Error("asktool answer count does not match questions"), {
        errorCode: "ASKTOOL_INVALID_ARGUMENT",
      });
    }
    const answers = resolution.answers.map((answer, index) => {
      if (answer === null) return null;
      if (!Array.isArray(answer)) {
        throw Object.assign(new Error(`asktool answer ${index + 1} must be an array or null`), {
          errorCode: "ASKTOOL_INVALID_ARGUMENT",
        });
      }
      const values = answer
        .filter((value): value is string => typeof value === "string")
        .map((value) => value.trim())
        .filter(Boolean);
      if (!pending.request.questions[index].multiSelect && values.length > 1) {
        throw Object.assign(new Error(`asktool question ${index + 1} accepts one answer`), {
          errorCode: "ASKTOOL_INVALID_ARGUMENT",
        });
      }
      return [...new Set(values)];
    });
    pending.resolve(answers);
    return { ok: true };
  }

  private resolvePendingAskTools(): void {
    const pending = [...this.pendingAskTools.values()];
    this.pendingAskTools.clear();
    for (const entry of pending) {
      entry.resolve(entry.request.questions.map(() => null));
    }
  }

  private pathLockKey(params: unknown): string {
    const rawPath = isRecord(params) ? String(params.path ?? "") : "";
    if (!rawPath) return "";
    const worktreeKey = this.delegateExecution.getStore()?.worktreeKey;
    return worktreeKey ? `${worktreeKey}\0${rawPath}` : rawPath;
  }

  /**
   * When a parent assistant message mixes `Task` with `Read`/`Glob`/`Grep`, any
   * read ordered after a writable `Task` in that same message waits for the
   * preceding writable delegation(s) from that message to settle before reading
   * the workspace, while `Task` itself still returns its ADR 0089 started state.
   */
  private async waitForBatchWritableDelegations(
    toolCallId: string,
    signal?: AbortSignal,
  ): Promise<void> {
    if (!toolCallId || this.delegateExecution.getStore()) return;
    const messages = this.agent?.state.messages ?? [];
    for (let index = messages.length - 1; index >= 0; index -= 1) {
      const message = messages[index];
      if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
      const toolCalls = message.content.filter(
        (block): block is Extract<AssistantMessage["content"][number], { type: "toolCall" }> =>
          block.type === "toolCall",
      );
      const currentIndex = toolCalls.findIndex((call) => call.id === toolCallId);
      if (currentIndex < 0) continue;
      if (currentIndex === 0) return;
      const precedingTaskIds = new Set(
        toolCalls
          .slice(0, currentIndex)
          .filter((call) => call.name === SUBAGENT_TOOL_NAME)
          .map((call) => call.id),
      );
      if (precedingTaskIds.size === 0) return;
      const running = [...this.delegations.values()].filter(
        (record) =>
          record.status === "running" &&
          record.writable === true &&
          record.parentToolCallId !== undefined &&
          precedingTaskIds.has(record.parentToolCallId),
      );
      if (running.length === 0) return;
      const completions = Promise.all(running.map((record) => record.completion));
      if (!signal) {
        await completions;
        return;
      }
      if (signal.aborted) return;
      await new Promise<void>((resolve) => {
        const onAbort = () => resolve();
        signal.addEventListener("abort", onAbort, { once: true });
        void completions.finally(() => {
          signal.removeEventListener("abort", onAbort);
          resolve();
        });
      });
      return;
    }
  }

  /**
   * Records what a prepared builtin call will touch so the batch can order it
   * (`withBatchTurn`). Runs after every check that can block the call. Tools
   * without claims are sequential, or Task, whose mixed batches pi already
   * runs sequentially.
   */
  private async registerBatchCall(
    context: BeforeToolCallContext,
    builtinToolNames?: ReadonlySet<string>,
    delegationId?: string,
  ): Promise<void> {
    const name = context.toolCall.name;
    if (!this.batchPlanner.supported || !TOOL_EXECUTION_SPECS[name]?.file) return;
    // pi prepares/executes sequential batches one call at a time. They must
    // not seal a partial registration and later try to append to it.
    const calls = context.assistantMessage.content.filter((block) => block.type === "toolCall");
    if (resolveBatchExecutionMode(context.assistantMessage) === "sequential"
      || calls.some((call) => context.context?.tools?.find((tool) => tool.name === call.name)?.executionMode !== "parallel")) return;
    const selected = context.context?.tools?.find((tool) => tool.name === name);
    const builtin = builtinToolNames ? builtinToolNames.has(name) : selected && this.builtinTools.has(selected);
    const batch: unknown = context.assistantMessage;
    if (!builtin || !isRecord(context.args) || !isRecord(batch)) return;
    await this.batchPlanner.register(
      batch,
      context.args,
      { toolName: name, toolCallId: context.toolCall.id,
        ordinal: context.assistantMessage.content.findIndex((block) => block.type === "toolCall" && block.id === context.toolCall.id),
        args: normalizeToolParams(name, context.args), delegationId },
    );
  }

  private async preparePathToolCall(
    context: BeforeToolCallContext,
    apply?: (instructions: ProjectInstructions | undefined) => void,
    builtinToolNames?: ReadonlySet<string>,
  ): Promise<void> {
    const name = context.toolCall.name;
    const selected = context.context?.tools?.find((tool) => tool.name === name);
    const builtin = builtinToolNames ? builtinToolNames.has(name) : selected && this.builtinTools.has(selected);
    if (!builtin) return;
    if (!builtinToolNames && READ_ONLY_CORE_TOOLS.has(name)) {
      await this.waitForBatchWritableDelegations(context.toolCall.id);
    }
    if (!PATH_SCOPED_INSTRUCTION_TOOLS.has(name)) return;
    rejectConflictingAliasedParams(name, context.args);
    const params = normalizeToolParams(name, context.args);
    requireAliasedParams(name, params);
    await this.loadPathInstructions(name, params, apply);
    if (typeof context.args === "object" && context.args !== null) {
      this.preparedPathToolArgs.set(context.args, params);
    }
  }

  private async loadPathInstructions(
    toolName: string,
    params: unknown,
    apply?: (instructions: ProjectInstructions | undefined) => void,
  ): Promise<void> {
    if (this.remoteWorkspace || !PATH_SCOPED_INSTRUCTION_TOOLS.has(toolName)) {
      return undefined;
    }
    const path = isRecord(params) && typeof params.path === "string"
      ? params.path.trim()
      : "";
    if (!path) return undefined;

    const key = `${this.projectPath ?? ""}\u0000${pathInstructionScope(path)}`;
    let resolution = this.pathInstructionClaims.get(key);
    if (!resolution) {
      resolution = this.host
        .call<ProjectInstructions | undefined>(
          "project.instructions.resolve",
          {
            sessionId: this.sessionId,
            path,
            ...(this.projectPath ? { projectPath: this.projectPath } : {}),
          },
          PATH_INSTRUCTION_RESOLUTION_TIMEOUT_MS,
        )
        .then((instructions) => ({ instructions, fallback: false }))
        .catch(() => ({
          // Path-scoped rules are best-effort. Do not carry a sibling path's
          // rules into this tool call when the resolver or host is unavailable.
          instructions: undefined,
          fallback: true,
        }));
      this.pathInstructionClaims.set(key, resolution);
    }
    const resolved = await resolution;
    // Rules are scoped to the file currently being accessed. Rebuild the
    // complete chain so sibling-directory rules never leak into one another
    // and edits to an existing instruction file take effect immediately.
    (apply ?? ((instructions) => this.applyProjectInstructions(instructions)))(
      resolved.fallback ? this.baseProjectInstructions : resolved.instructions,
    );
  }

  private applyProjectInstructions(resolved: ProjectInstructions | undefined): void {
    this.projectInstructions = resolved;
    this.setAgentSystemPrompt(this.composeSystemPrompt());
  }

  /**
   * The model side of compaction, copied from Codex: a parameterless request
   * for a new context window. It only records the request — compaction happens
   * at the next turn boundary, where the host already owns it, so a model that
   * calls this mid-batch does not lose the results it is still holding.
   */
  private buildContextCompactionTool(): AgentTool {
    return {
      name: CONTEXT_COMPACTION_TOOL_NAME,
      label: "New Context",
      description: CONTEXT_COMPACTION_TOOL_DESCRIPTION,
      parameters: Type.Object({}),
      execute: async () => {
        this.pendingModelCompaction = true;
        return {
          content: [
            {
              type: "text",
              text: CONTEXT_COMPACTION_TOOL_REPLY[this.compactionStrategy],
            },
          ],
          details: { queued: true },
        };
      },
    };
  }

  private emit(event: AgentEventEnvelope["event"], turnId?: string, ts = Date.now()) {
    // Business state is answer-only. Only the transcript transports the original
    // signed text, so an old or restarted host can replay the same provider input.
    if (this.liveCommentary &&
        (event.type === "message_start" || event.type === "message_update" || event.type === "message_end") &&
        event.message.id === this.currentAssistant?.id) {
      const replay = event.type === "message_end" ? event.message.providerReplay : this.liveCommentary.replay;
      // A failed or oversized terminal replay cannot identify raw progress on reload.
      if (replay?.blocks.length) {
        event = { ...event, message: { ...event.message, content: this.liveCommentary.text, providerReplay: replay } };
      }
    }
    this.onEvent({
      sessionId: this.sessionId,
      turnId: turnId ?? this.turnId,
      ts,
      event,
    });
  }

  private setAgentActivity(activity: AgentActivity): void {
    if (agentActivityEqual(this.agentActivity, activity)) return;
    this.agentActivity = activity;
    this.emit({ type: "status", status: this.getStatus() });
  }

  private retryActivityError(
    error: ReturnType<typeof classifyAgentError>,
  ): AgentActivityError {
    const detailStatus = isRecord(error.details)
      ? error.details.providerStatus
      : undefined;
    const detailNetworkCode = isRecord(error.details)
      ? error.details.networkCode
      : undefined;
    const providerStatus =
      typeof detailStatus === "number"
        ? detailStatus
        : this.providerResponseStatus;
    return {
      code: error.code,
      message: error.message,
      ...(typeof providerStatus === "number" ? { providerStatus } : {}),
      // While the turn is still retrying, the transport errno is the only thing
      // that tells a DNS failure from a TLS failure from a dropped socket; the
      // localized summary cannot (issue #234).
      ...(typeof detailNetworkCode === "string"
        ? { networkCode: detailNetworkCode }
        : {}),
    };
  }

  private clearAgentActivity(): void {
    if (!this.agentActivity) return;
    this.agentActivity = undefined;
    this.emit({ type: "status", status: this.getStatus() });
  }

  /**
   * Claim a retry without exposing an intermediate error to the user. Rate
   * limits use one shared ten-retry budget across request setup and stream
   * recovery. Other transient failures — upstream gateway 5xx, dropped sockets,
   * timeouts, truncated streams — share their own bounded budget across both
   * phases, so a flapping gateway is retried instead of surfacing an error
   * after a single attempt.
   */
  private claimProviderRetry(
    error: ReturnType<typeof classifyAgentError>,
    phase: "request" | "stream",
  ): number | undefined {
    if (!error.retriable || error.details?.origin === "local") return undefined;
    const infinite = this.infiniteProviderRetry;
    if (error.code === "PROVIDER_RATE_LIMITED") {
      if (
        !infinite &&
        this.providerRateLimitRetryAttempt >=
        PROVIDER_RATE_LIMIT_MAX_RETRIES
      ) {
        return undefined;
      }
      const attempt = ++this.providerRateLimitRetryAttempt;
      this.activeProviderRetryAttempt = attempt;
      return attempt;
    }

    // Request setup and stream delivery share this counter. An upstream
    // gateway that fails before headers on one attempt and mid-stream on the
    // next must not multiply the budget or reset it by changing phase.
    void phase;
    if (!isTransientProviderRetryCode(error.code)) return undefined;
    if (
      !infinite &&
      this.providerTransientRetryAttempt >= PROVIDER_TRANSIENT_MAX_RETRIES
    ) {
      return undefined;
    }
    const attempt = ++this.providerTransientRetryAttempt;
    this.activeProviderRetryAttempt = attempt;
    return attempt;
  }

  private providerErrorWithDiagnostics(
    error: ReturnType<typeof classifyAgentError>,
    phase: "request" | "stream",
    providerWaitMs?: number,
    streamMs?: number,
  ): ReturnType<typeof classifyAgentError> {
    // Local preparation never reached the provider: keep its phase and cause
    // instead of attaching stale HTTP status or a synthetic stream phase.
    if (error.details?.origin === "local") return error;
    const explained = withProviderFetchFailure(error, this.providerFetchFailure);
    const existingDetails = explained.details ?? {};
    const retryAttempt = error.code === "PROVIDER_RATE_LIMITED"
      ? this.providerRateLimitRetryAttempt
      : isTransientProviderRetryCode(error.code) ? this.providerTransientRetryAttempt : 0;
    // A capture exists only for an attempt that rejected before any response, so
    // it is also the honest phase: whatever the message lifecycle that surfaced
    // the failure looks like, this request never reached the provider, and
    // pi-agent-core's synthetic `message_start` must not read as a started
    // stream (issue #234).
    const captured =
      this.providerFetchFailure !== undefined &&
      explainsProviderFetchFailure(error.code)
        ? this.providerFetchFailure
        : undefined;
    return {
      ...explained,
      details: {
        ...existingDetails,
        phase: captured ? "request" : phase,
        // Correlation for a failure that produced no response to inspect: how
        // much context and how many bytes the attempt carried, and which
        // compaction generation the session was on (issue #234). Counts, flags
        // and sizes only — never message content.
        ...(this.providerRequestMessages !== undefined
          ? { requestMessages: this.providerRequestMessages }
          : {}),
        ...(this.providerRequestBytes !== undefined
          ? { requestBytes: this.providerRequestBytes }
          : {}),
        ...(this.activeCompaction
          ? {
              compactionGeneration: checkpointGeneration(
                this.activeCompaction.details,
              ),
            }
          : {}),
        ...(providerWaitMs !== undefined ? { providerWaitMs } : {}),
        ...(streamMs !== undefined ? { streamMs } : {}),
        ...(this.providerResponseStatus !== undefined &&
        existingDetails.providerStatus === undefined
          ? { providerStatus: this.providerResponseStatus }
          : {}),
        ...(retryAttempt > 0 ? { retryAttempt } : {}),
      },
    };
  }

  /**
   * Rebuild the shared provider transport once the same origin has failed
   * repeatedly without ever answering (issue #234).
   *
   * A rejection that produced no response is the only transport event that says
   * the connection itself never worked, so `createProviderTransportHealth`
   * counts them per origin and asks for a rebuild after the second one. The
   * rebuild swaps a dispatcher every session shares, which is safe precisely
   * because the swap is not a teardown: undici resolves the global dispatcher per
   * dispatch, in-flight requests keep finishing on the pool they started on, and
   * the replaced pool is closed gracefully by its owner in `node-proxy.ts`. A
   * process-wide throttle there bounds how often any session can spend that cost,
   * and the capture is reported either way, so a rebuild that does not help
   * still leaves an accurate record.
   */
  private recoverProviderTransport(failure: ProviderFetchFailure): void {
    if (!this.providerTransportHealth.observeFailure(failure)) return;
    const result = rebuildNodeNetworkTransport();
    process.stderr.write(
      `[agent-runtime] provider transport ${
        result.rebuilt ? "rebuilt after" : "rebuild skipped within throttling for"
      } a ${failure.category} failure (session=${this.sessionId} route=${result.route})\n`,
    );
  }

  private clearMutationRecovery(owner: string): void {
    const prefix = `${owner}\0`;
    for (const key of this.mutationFailureCounts.keys()) {
      if (key.startsWith(prefix)) this.mutationFailureCounts.delete(key);
    }
    for (const key of this.mutationRecoveryGraces) {
      if (key.startsWith(prefix)) this.mutationRecoveryGraces.delete(key);
    }
  }

  /**
   * Clear the per-run recovery state that every entry point driving the agent
   * loop must start from. Each recovery arms itself mid-run by setting a
   * `pending*` flag and suppressing that run's end events; a flag left behind
   * suppresses the *next* run's `turn_end` and `agent_end` instead, so the
   * following turn ends invisibly even though nothing went wrong in it.
   */
  private resetRunRecoveryState(): void {
    this.pendingOverflow = false;
    this.overflowRecoveryAttempted = false;
    this.overflowRecoveryInProgress = false;
    this.suppressOverflowRunEnd = false;
    this.pendingProviderRetry = undefined;
    this.providerTransientRetryAttempt = 0;
    this.providerRateLimitRetryAttempt = 0;
    this.providerRetryHeaders = undefined;
    this.providerFetchFailure = undefined;
    this.providerTransportHealth.reset();
    this.activeProviderRetryAttempt = 0;
    this.providerRetryInProgress = false;
    this.suppressProviderRetryRunEnd = false;
    this.pendingSilentTurnRerun = false;
    this.silentTurnRerunAttempted = false;
    this.allowSilentCompletion = false;
    this.silentTurnRerunInProgress = false;
    this.suppressSilentTurnRunEnd = false;
    this.pendingProgressTurnRerun = false;
    this.progressTurnRerunAttempted = false;
    this.progressTurnRerunInProgress = false;
    this.suppressProgressTurnRunEnd = false;
    this.providerRetryAbort?.abort();
    this.providerRetryAbort = undefined;
    this.clearMutationRecovery("parent");
    this.pendingMutationTermination = undefined;
    this.turnHadError = false;
  }

  private async retryPendingProviderFailure(): Promise<void> {
    if (!this.pendingProviderRetry) return;
    const retryError = this.pendingProviderRetry;
    // Fall back to the budget the error actually draws from. Hardcoding 1 here
    // under-reported `retryAttempt` once non-429 failures gained a multi-attempt
    // budget, so a third 502 was diagnosed as if it were the first.
    const retryAttempt =
      this.activeProviderRetryAttempt ||
      (retryError.code === "PROVIDER_RATE_LIMITED"
        ? this.providerRateLimitRetryAttempt
        : this.providerTransientRetryAttempt || 1);
    this.activeProviderRetryAttempt = retryAttempt;
    this.pendingProviderRetry = undefined;

    // A failed stream can be represented by more than one trailing assistant
    // message after a tool round. Compaction may already have replaced the
    // failed assistant with a summary or retained user message, so an
    // assistant tail is optional. Remove any failed suffix before continuing;
    // pi-agent-core rejects an assistant-terminated transcript.
    const messages = removeTrailingAssistantMessages(this.agent.state.messages);
    this.setAgentMessages(messages);

    this.providerRetryInProgress = true;
    this.requestStartedAt = Date.now();
    this.providerRetryAbort = new AbortController();
    try {
      const delayMs =
        retryError.code === "PROVIDER_RATE_LIMITED"
          ? providerRateLimitDelayMs(
              retryAttempt || this.providerRateLimitRetryAttempt,
              this.providerRetryHeaders,
            )
          : // The same 1s/2s/4s/8s schedule as a setup retry, so a fault that
            // moves between phases keeps one predictable rhythm. A
            // server-stated delay still wins outright.
            providerSetupRetryDelayMs(
              retryAttempt,
              undefined,
              this.providerRetryHeaders,
            );
      this.setAgentActivity({
        phase: "retrying",
        since: Date.now(),
        attempt: retryAttempt,
        ...(this.infiniteProviderRetry ? { infinite: true } : {}),
        retryDelayMs: delayMs,
        error: this.retryActivityError(retryError),
      });
      await delayWithAbort(delayMs, this.providerRetryAbort.signal);
      if (this.disposed) throw new Error("runtime disposed");
      // The failed attempt has already finished. Only its lifecycle events
      // are suppressed; the retry must close the visible run normally.
      this.suppressProviderRetryRunEnd = false;
      await this.agent.continue();
      await this.waitForIdleAndSteering();
    } finally {
      this.providerRetryAbort = undefined;
      this.activeProviderRetryAttempt = 0;
      this.providerRetryInProgress = false;
      this.suppressProviderRetryRunEnd = false;
    }
  }

  /**
   * Re-run the request that came back silent, once, with SILENT_TURN_NUDGE
   * appended. The nudge goes on `agent.state.systemPrompt` rather than through
   * `prepareNextTurn`, because that hook only shapes turns inside a live run
   * and this run has already ended; `continue()` rebuilds its context from
   * state. It is restored afterwards unless a path-scoped instruction reload
   * rewrote the prompt in the meantime — that rebuild is newer, so it wins.
   */
  private async rerunSilentTurn(): Promise<void> {
    if (!this.pendingSilentTurnRerun) return;
    this.pendingSilentTurnRerun = false;
    this.suppressSilentTurnRunEnd = false;

    // agentLoopContinue refuses a transcript ending in an assistant message,
    // and this one carries nothing worth resending anyway.
    const messages = removeTrailingAssistantMessages(this.agent.state.messages);
    this.setAgentMessages(messages);

    const promptBefore = this.agentSystemPromptContent();
    const promptWithNudge = `${promptBefore}\n\n${SILENT_TURN_NUDGE}`;
    this.setAgentSystemPrompt(promptWithNudge);
    this.silentTurnRerunInProgress = true;
    this.requestStartedAt = Date.now();
    this.setAgentActivity({ phase: "recovering", since: Date.now() });
    try {
      if (this.disposed) throw new Error("runtime disposed");
      await this.agent.continue();
      await this.waitForIdleAndSteering();
    } finally {
      if (this.agentSystemPromptContent() === promptWithNudge) {
        this.setAgentSystemPrompt(promptBefore);
      }
      this.silentTurnRerunInProgress = false;
      this.suppressSilentTurnRunEnd = false;
    }
  }

  /**
   * Run whatever recovery the finished loop armed for itself. Overflow, a
   * retriable provider stream failure, a silent turn, and an autonomous
   * progress-only turn all suppress their run's `turn_end` / `agent_end`
   * inside `message_end` and leave a `pending*` flag for the caller to act on
   * once the loop is idle. An entry point that skips this leaves the run with
   * no end events, no error, and no recovery — the turn simply stops, which is
   * exactly how an approved plan execution used to die on a silent turn.
   *
   * Returns false when overflow recovery could not create a checkpoint and the
   * caller must stop; the error event is already emitted.
   */
  private async runPendingRecoveries(): Promise<boolean> {
    while (
      this.pendingProviderRetry ||
      this.pendingOverflow ||
      this.pendingSilentTurnRerun ||
      this.pendingProgressTurnRerun
    ) {
      if (this.pendingProviderRetry) {
        await this.retryPendingProviderFailure();
        continue;
      }
      if (this.pendingOverflow) {
        this.pendingOverflow = false;
        this.suppressOverflowRunEnd = false;
        this.overflowRecoveryAttempted = true;
        this.overflowRecoveryInProgress = true;
        try {
          const messages = removeTrailingAssistantMessages(this.agent.state.messages);
          this.setAgentMessages(messages);
          const compacted = await this.runCompaction(
            "overflow",
            true,
            "active_turn",
          );
          if (!compacted) {
            this.terminateParentTurn();
            if (this.compactionAborted) {
              // The user stopped the turn while the checkpoint was being written.
              // That is an aborted turn, not a compaction failure: close it the
              // way a stopped stream closes, with no error row.
              this.finalizeCurrentAssistant("aborted");
              this.emit({ type: "turn_end" });
              this.emit({ type: "agent_end", messageIds: [] });
              return false;
            }
            const error = {
              code: "CONTEXT_COMPACTION_FAILED",
              message: "Context overflow recovery could not create a checkpoint",
              retriable: false,
            } satisfies ReturnType<typeof classifyAgentError>;
            this.finalizeCurrentAssistant("error", error);
            this.emit({ type: "error", error });
            return false;
          }
          this.turnHadError = false;
          this.requestStartedAt = Date.now();
          await this.agent.continue();
          await this.waitForIdleAndSteering();
        } finally {
          this.overflowRecoveryInProgress = false;
        }
        continue;
      }
      if (this.pendingSilentTurnRerun) {
        await this.rerunSilentTurn();
        continue;
      }
      await this.rerunProgressOnlyTurn();
    }
    return true;
  }

  /**
   * Continue once after an autonomous progress-only assistant message
   * (text, no toolCall). Mirrors `rerunSilentTurn` but keeps the visible
   * text and only appends PROGRESS_TURN_NUDGE (#43).
   */
  private async rerunProgressOnlyTurn(): Promise<void> {
    if (!this.pendingProgressTurnRerun) return;
    this.pendingProgressTurnRerun = false;
    this.suppressProgressTurnRunEnd = false;

    // pi-agent-core refuses `continue()` when the transcript ends in an
    // assistant message. The progress text is already visible in the reused
    // bubble, so it must not be sent back as model context.
    const messages = removeTrailingAssistantMessages(this.agent.state.messages);
    this.setAgentMessages(messages);

    const promptBefore = this.agentSystemPromptContent();
    const promptWithNudge = `${promptBefore}\n\n${PROGRESS_TURN_NUDGE}`;
    this.setAgentSystemPrompt(promptWithNudge);
    this.progressTurnRerunInProgress = true;
    this.requestStartedAt = Date.now();
    this.setAgentActivity({ phase: "recovering", since: Date.now() });
    try {
      if (this.disposed) throw new Error("runtime disposed");
      this.suppressProgressTurnRunEnd = false;
      await this.agent.continue();
      await this.waitForIdleAndSteering();
    } finally {
      if (this.agentSystemPromptContent() === promptWithNudge) {
        this.setAgentSystemPrompt(promptBefore);
      }
      this.progressTurnRerunInProgress = false;
      this.suppressProgressTurnRunEnd = false;
    }
  }

  private cleanupActiveToolProgress(): void {
    for (const cleanup of [...this.activeToolProgressCleanups]) cleanup(false);
    this.activeToolProgressCleanups.clear();
  }

  setCompactionSettings(settings?: ContextCompactionSettings): void {
    this.compactionEnabled = compactionEnabled(settings);
    this.pendingModelCompaction = false;
    this.rebuildToolCatalog();
    this.setAgentTools(this.activeTools());
  }

  private contextBudget(messages: AgentMessage[]): ContextBudget {
    const budget = contextBudgetFor(this.model, messages);
    // Calibration learns from message usage; the output-cap estimator adds the
    // active system prompt and tool schemas that the provider also receives.
    // Taking the larger full-request estimate avoids double-counting overhead
    // once unanchored calibration has learned it, while keeping that overhead as
    // a hard floor before the first usable sample.
    const calibratedMessageTokens = this.contextCalibration.correct(
      estimateContextTokens(messages, this.model),
    );
    const requestTokens = estimateOutputCapInputTokens(
      {
        messages: messages.filter(
          (message): message is Extract<AgentMessage, { content: unknown }> =>
            message.role !== "system" && "content" in message,
        ),
        ...(typeof this.agent.state.systemPrompt === "string"
          ? { systemPrompt: this.agent.state.systemPrompt }
          : {}),
        tools: this.declaredTools(),
      },
      this.model,
    );
    return {
      ...budget,
      tokens: Math.max(calibratedMessageTokens, requestTokens),
    };
  }

  /**
   * Fold one provider report into the estimate calibration.
   *
   * Only a completed, non-aborted response is a measurement: a failed stream
   * never carried the request, and counting one would teach the estimator from
   * a request the provider rejected. The pair is recorded against the estimate
   * parked by `streamFn`, which describes the same context.
   *
   * The measured value is the request side only (`input + cacheRead +
   * cacheWrite`): the response's own output is not in the projection the parked
   * estimate described, and it becomes part of the *next* request's anchor.
   */
  private recordContextCalibration(
    usage: MessageUsage | undefined,
    unusable: boolean,
  ): void {
    const estimate = this.inFlightContextEstimate;
    this.inFlightContextEstimate = undefined;
    if (!estimate || unusable || !usage) return;
    const realRequestTokens =
      usage.inputTokens +
      (usage.cacheReadTokens ?? 0) +
      (usage.cacheWriteTokens ?? 0);
    if (realRequestTokens <= 0) return;
    const anchored =
      estimate.lastUsageIndex !== null && estimate.usageTokens > 0;
    if (anchored) {
      this.contextCalibration.recordAnchored(
        estimate.usageTokens,
        estimate.trailingTokens,
        realRequestTokens,
      );
    } else {
      this.contextCalibration.recordUnanchored(
        Math.max(0, Math.round(estimate.tokens)),
        realRequestTokens,
      );
    }
  }

  private automaticCompactionNeeded(
    additionalMessages: AgentMessage[] = [],
  ): boolean {
    const context = this.liveSessionContext();
    const messages = [...context.messages, ...additionalMessages];
    const budget = this.contextBudget(messages);
    return (
      this.compactionEnabled &&
      budget.tokens >= automaticCompactionThresholdFor(budget)
    );
  }

  private automaticCompactionWouldExceedHardLimit(
    additionalMessages: AgentMessage[] = [],
  ): boolean {
    const context = this.liveSessionContext();
    const messages = [...context.messages, ...additionalMessages];
    const budget = this.contextBudget(messages);
    return budget.tokens >= budget.hardLimit;
  }

  private retainedUserMessageBudget(budget: ContextBudget): number {
    return retainedUserMessageBudget(budget);
  }

  /**
   * Prepare a checkpoint in Codex's shape: the summary covers every message
   * since the previous boundary, and the only messages carried past the
   * boundary are the latest user message only when the provider is still
   * continuing the same turn. A completed turn carries no naked historical
   * user messages into the next task.
   *
   * pi's cut point is still what marks the boundary, but the split it produces
   * is folded back together (see `codexShapedPreparation`), so
   * `budget.keepRecentTokens` no longer decides what survives. File operations
   * are collected from that whole folded range, including the retained tail.
   */
  private prepareCompactionInput(
    entries: Entry[],
    budget: ContextBudget,
    retainedUserTokens = this.retainedUserMessageBudget(budget),
    retentionMode: CompactionRetentionMode = "completed_turn",
  ) {
    const prepared = prepareCompaction(withPiFileOpToolNames(entries), {
      enabled: this.compactionEnabled,
      reserveTokens: budget.requestHeadroom,
      keepRecentTokens: budget.keepRecentTokens,
    } satisfies CompactionSettings);
    if (!prepared.ok || !prepared.value) return prepared;
    // pi picks `previousSummary` straight from the previous compaction entry.
    // A retained-tail fallback stores its carried-forward summary ahead of a
    // recovery notice; feeding the notice to the next run makes the model
    // *update* a summary that never existed and cements the failure. Strip the
    // notice while keeping the carried-forward summary, so the next
    // summarization request still sees the history it was carrying (#224).
    const previousSummary = stripCompactionFallbackNotice(
      prepared.value.previousSummary,
    );
    return {
      ok: true as const,
      value: this.codexShapedPreparation(
        {
          ...prepared.value,
          ...(previousSummary === prepared.value.previousSummary
            ? {}
            : { previousSummary }),
        },
        retainedUserTokens,
        retentionMode,
      ),
    };
  }

  /**
   * Reshape a pi preparation the way Codex compacts:
   *
   * - Everything pi would have split across `messagesToSummarize`,
   *   `turnPrefixMessages` and `retainedTail` is summarized as one range. The
   *   three are contiguous and ordered, so concatenating them loses nothing —
   *   and it is what makes dropping the tail safe: no message leaves the model
   *   context without the summary covering it.
   * - The retained tail is rebuilt from the latest user message only when the
   *   turn is still active. Completed turns retain no user messages: their
   *   summary is authoritative, and the next prompt becomes the sole new
   *   instruction after the checkpoint. Dropping assistant messages also drops
   *   their `toolCall` blocks, and their results go with them in the same pass,
   *   so no orphaned tool call can reach a provider.
   * - `firstKeptEntryId` points at the anchor the checkpoint is filed against.
   *   It is ours, not pi's (see `ShapedPreparation`): pi 0.84 takes its own
   *   boundary from the compaction entry, so this only feeds the persisted
   *   record and the `compaction_end` event.
   */
  private codexShapedPreparation(
    preparation: CompactionPreparation,
    retainedUserTokens: number,
    retentionMode: CompactionRetentionMode,
  ): ShapedPreparation {
    // pi 0.84 replays a previous checkpoint's `retainedTail` as virtual entries
    // at the head of the compactable range, so those messages already arrive in
    // `preparation` — prepending them again (which is what this had to do while
    // pi walked back to `firstKeptEntryId` instead) would duplicate every one.
    const messagesToSummarize = [
      ...preparation.messagesToSummarize,
      ...preparation.turnPrefixMessages,
      ...preparation.retainedTail,
    ];
    // pi records file operations for `messagesToSummarize` and, on a split
    // turn, `turnPrefixMessages`. The tail is summarized too — including the
    // suffix a split left uncollected — so copy the sets and record it there.
    // The sets pi returned stay unchanged. The tail's own collection obeys
    // the executed-call contract those guarded slices follow: a mid-batch
    // Stop leaves trailing calls with no result row and failed calls keep
    // an error row — either way the call never touched its file. The
    // lookup spans the whole transcript because a tail call's result row
    // can sit anywhere in it.
    const fileOps: CompactionPreparation["fileOps"] = {
      read: new Set(preparation.fileOps.read),
      written: new Set(preparation.fileOps.written),
      edited: new Set(preparation.fileOps.edited),
    };
    const executedCallIds = executedToolCallIdsInEntries(this.fullEntries);
    for (const message of preparation.retainedTail) {
      collectMessageFileOperations(message, fileOps, executedCallIds);
    }
    const latestUser = messagesToSummarize
      .filter((message): message is UserMessage => message.role === "user")
      .at(-1);
    const candidates =
      retentionMode === "active_turn" && latestUser ? [latestUser] : [];
    return {
      ...preparation,
      firstKeptEntryId: this.fullEntries.at(-1)?.id,
      messagesToSummarize,
      turnPrefixMessages: [],
      isSplitTurn: false,
      retainedTail: selectRetainedUserMessages(candidates, retainedUserTokens),
      fileOps,
    };
  }

  private rebuiltAgentContext(): AgentContext {
    const messages = this.liveSessionContext().messages;
    const tools = this.declaredTools();
    this.setAgentMessages(messages);
    this.setAgentTools(tools);
    return {
      // The loop owns its context array. pi appends every streamed assistant
      // message and every tool result to the context it was handed, and its own
      // `message_end` listener appends the same message object to
      // `state.messages`; handing over the live array makes both land in one
      // array, so every message of a run's later iterations is stored twice.
      // The next turn is then built from that array, and the duplicate of an
      // assistant message that carries text plus a tool call survives the
      // request guard as a text-only clone sitting between the call and the
      // result answering it. pi-ai then closes the still-pending call with a
      // synthesized "No result provided" output next to the real one — two
      // outputs for one call id, which the provider rejects (D620).
      // `createContextSnapshot()` copies for the same reason.
      messages: [...this.agent.state.messages],
      tools,
      systemPrompt: this.agent.state.systemPrompt,
    } as AgentContext;
  }

  /**
   * Shape the next in-run assistant turn. pi 0.84.4+ calls this only after
   * `shouldStopAfterTurn` and queued-message checks decide the loop will start
   * another assistant turn, including between a tool batch and the follow-up
   * model request. A new user prompt compacts separately in `prompt()` via
   * `automaticCompactionNeeded`, because that first turn does not go through
   * this hook.
   */
  private async prepareNextTurn(
    turn: PrepareNextTurnContext,
    _signal?: AbortSignal,
  ): Promise<AgentLoopTurnUpdate> {
    let context = this.rebuiltAgentContext();
    const budget = this.contextBudget(context.messages);
    const hardLimitReached = budget.tokens >= budget.hardLimit;
    if (!this.compactionEnabled) {
      this.pendingModelCompaction = false;
      if (hardLimitReached) {
        throw new Error(
          "CONTEXT_TOO_LARGE: context exceeds the safe model budget while automatic compaction is disabled",
        );
      }
      return { context };
    }

    const automaticThresholdReached =
      budget.tokens >= automaticCompactionThresholdFor(budget);
    // Compact deterministically before the request approaches the hard limit.
    // `new_context` remains an optional earlier model request.
    const modelRequested = this.pendingModelCompaction;
    this.pendingModelCompaction = false;
    if (!automaticThresholdReached && !modelRequested) {
      return { context: this.withContextBudgetReminder(context, budget) };
    }

    const retentionMode: CompactionRetentionMode =
      (turn.toolResults?.length ?? 0) > 0 ||
      turn.message?.stopReason === "toolUse"
        ? "active_turn"
        : "completed_turn";
    const compacted = await this.runCompaction(
      "threshold",
      false,
      retentionMode,
    );
    if (!compacted) {
      if (!hardLimitReached) return { context };
      // A user Stop that lands during the checkpoint aborts the compaction;
      // pi's loop is already aborting, so surface it as the abort it is.
      if (this.compactionAborted) {
        throw new Error("Turn aborted while compacting context");
      }
      // Continuing would immediately issue the provider request that this
      // guard exists to prevent. The Agent wrapper converts this failure to
      // the normal error/agent_end event sequence. The checkpoint's own cause
      // rides along so the turn error says why (#2494).
      const cause = this.lastCompactionFailure;
      throw new Error(
        `CONTEXT_COMPACTION_FAILED: unable to create a checkpoint before the next model request${cause ? `: ${cause}` : ""}`,
      );
    }
    context = this.rebuiltAgentContext();
    const postCompactionBudget = this.contextBudget(context.messages);
    if (postCompactionBudget.tokens >= postCompactionBudget.hardLimit) {
      throw new Error(
        "CONTEXT_COMPACTION_FAILED: checkpoint remained above the safe model context budget",
      );
    }
    return { context };
  }

  /** A replaceable reminder section expires when compaction opens a new window. */
  private withContextBudgetReminder(
    context: AgentContext,
    budget: ContextBudget,
  ): AgentContext {
    const remaining = Math.max(0, budget.hardLimit - budget.tokens);
    const reminder = this.claimContextBudgetReminder(remaining, budget);
    if (!reminder) return context;
    // The reminder changes on every claim, so it must never reach the request
    // prefix (issue #2458). A system section stays at the tail only where the
    // adapter keeps mid-conversation system messages; elsewhere pi-ai folds it
    // into the leading system message and invalidates the whole prefix cache.
    // There it rides as a request-only user message appended at the tail,
    // like steering, and is neither persisted nor carried into the next run.
    const message: AgentMessage = supportsMidConversationSystemMessages(this.model)
      ? { role: "system", content: "", sections: { [CONTEXT_BUDGET_SECTION]: reminder }, timestamp: Date.now() }
      : { role: "user", content: [{ type: "text", text: reminder }], timestamp: Date.now() };
    return { ...context, messages: [...context.messages, message] };
  }

  private claimContextBudgetReminder(
    remaining: number,
    budget: ContextBudget,
  ): string | undefined {
    if (
      remaining <= CONTEXT_FALLBACK_REMINDER_TOKENS &&
      !this.contextFallbackReminderClaimed
    ) {
      this.contextFallbackReminderClaimed = true;
      // The first tier is pointless once the second has fired.
      this.contextReminderClaimed = true;
      return contextFallbackReminder();
    }
    const threshold = Math.min(
      CONTEXT_REMINDER_MAX_TOKENS,
      Math.max(
        CONTEXT_REMINDER_MIN_TOKENS,
        Math.floor(budget.hardLimit * CONTEXT_REMINDER_RATIO),
      ),
    );
    if (remaining > threshold || this.contextReminderClaimed) return undefined;
    this.contextReminderClaimed = true;
    return contextBudgetReminder(remaining);
  }

  private async runCompaction(
    reason: ContextCompactionReason,
    willRetry: boolean,
    retentionMode: CompactionRetentionMode = "completed_turn",
  ): Promise<boolean> {
    if (this.compactionInProgress) return false;
    this.compactionInProgress = true;
    this.compactionAborted = false;
    this.lastCompactionFailure = undefined;
    const previous = this.agentActivity;
    this.setAgentActivity({
      phase: "compacting",
      since: Date.now(),
      reason,
    });
    try {
      const runner = this.extensionRunner;
      if (runner?.hasHandlers("session_before_compact")) {
        const decision = await runner.emit<{ cancel?: boolean }>(
          "session_before_compact",
          { type: "session_before_compact", reason, retentionMode },
          (acc, next) => (acc?.cancel ? acc : next),
        );
        if (decision?.cancel) return false;
      }
      const compacted = await this.performCompaction(reason, willRetry, retentionMode);
      // A run stage re-reads its `on.compaction` context into the prompt of
      // the new window (ADR mode-definitions).
      if (compacted && await this.modeState.afterCompaction(this.modeArtifactReader())) {
        this.setAgentSystemPrompt(this.composeSystemPrompt());
      }
      if (runner) {
        void runner.emit(compacted ? "session_compact" : "session_compact_failed", {
          type: compacted ? "session_compact" : "session_compact_failed",
          reason,
          aborted: this.compactionAbort?.signal.aborted === true,
        });
      }
      return compacted;
    } finally {
      this.compactionAbort = undefined;
      this.compactionInProgress = false;
      if (this.agentActivity?.phase === "compacting") {
        if (previous && previous.phase !== "compacting") {
          this.setAgentActivity(previous);
        } else {
          this.clearAgentActivity();
        }
      }
    }
  }

  private emitCompactionFailure(
    reason: ContextCompactionReason,
    tokensBefore: number | undefined,
    message: string,
  ): void {
    // A checkpoint cut short by the user's Stop is not a failed compaction;
    // it reports under the abort code so the turn reads as stopped.
    const aborted = this.compactionAborted;
    if (!aborted) this.lastCompactionFailure = message;
    this.emit({
      type: "compaction_end",
      reason,
      ok: false,
      ...(tokensBefore !== undefined ? { tokensBefore } : {}),
      willRetry: false,
      error: aborted
        ? { code: "TURN_ABORTED", message: "Context compaction was stopped" }
        : { code: "CONTEXT_COMPACTION_FAILED", message },
    });
  }

  private emitCompactionDiagnostic(
    kind: AgentRuntimeDiagnostic["kind"],
    requestId: string,
    data: Record<string, unknown>,
  ): void {
    this.onDiagnostic({
      kind,
      sessionId: this.sessionId,
      ...(this.turnId ? { turnId: this.turnId } : {}),
      requestId,
      data,
    });
  }

  private emitCompactionFailureDiagnostic(
    requestId: string,
    reason: CompactionFailureReason,
    tokensBefore: number | undefined,
    error: unknown,
    extra: Record<string, unknown> = {},
  ): void {
    if (!this.compactionShapeLogged) {
      this.emitCompactionDiagnostic("compaction_shape", requestId, {
        requestShape: extra.requestShape ?? "unobserved",
        ...(this.compactionRequestShape ?? {}),
      });
      this.compactionShapeLogged = true;
    }
    const candidate = error as {
      code?: unknown;
      details?: { providerStatus?: unknown; requestId?: unknown };
    };
    this.emitCompactionDiagnostic("compaction_failure", requestId, {
      provider: this.provider.id,
      model: this.provider.modelId,
      reason,
      ...(typeof candidate.code === "string" ? { errorCode: candidate.code } : {}),
      ...(typeof candidate.details?.providerStatus === "number"
        ? { httpStatus: candidate.details.providerStatus }
        : {}),
      ...(typeof candidate.details?.requestId === "string"
        ? { upstreamRequestId: candidate.details.requestId }
        : {}),
      ...(tokensBefore !== undefined ? { tokensBefore } : {}),
      ...(this.compactionDiagnosticBudget ?? {}),
      ...extra,
    });
  }


  private reasoningReplayIdentity(): ReasoningReplayIdentity {
    const requiresCompletionsReasoningReplay =
      this.model.api === "openai-completions" &&
      (
        this.model.compat as
          | { requiresReasoningContentOnAssistantMessages?: boolean }
          | undefined
      )?.requiresReasoningContentOnAssistantMessages === true;
    return {
      api: this.model.api,
      provider: this.model.provider,
      model: this.model.id,
      requiresCompletionsReasoningReplay,
    };
  }

  private liveSessionContext(
    checkpoint: ContextCompactionRecord | undefined = this.activeCompaction,
  ): { messages: AgentMessage[] } {
    return buildSessionContext(
      this.entriesWithCompaction(checkpoint),
      this.reasoningReplayIdentity(),
    );
  }

  /**
   * When the bound model requires DeepSeek-style reasoning replay, keep the
   * last few thinking turns inside opaque checkpoint details so post-compaction
   * context can echo real reasoning without restoring tool-call pairs (#296).
   */
  private retainedReasoningForCheckpoint(preparation: ShapedPreparation): {
    retainedReasoning?: ReturnType<typeof harvestRetainedReasoning>;
  } {
    const compat = this.model.compat as
      | { requiresReasoningContentOnAssistantMessages?: boolean }
      | undefined;
    if (!compat?.requiresReasoningContentOnAssistantMessages) return {};
    const retainedReasoning = harvestRetainedReasoning(
      preparation.messagesToSummarize,
    );
    return retainedReasoning.length > 0 ? { retainedReasoning } : {};
  }

  private checkpointDetails(preparation: ShapedPreparation) {
    return {
      readFiles: [...preparation.fileOps.read].sort(),
      modifiedFiles: [
        ...new Set([
          ...preparation.fileOps.written,
          ...preparation.fileOps.edited,
        ]),
      ].sort(),
    };
  }

  private createCheckpoint(
    preparation: ShapedPreparation,
    throughMessageId: string,
    summary: string,
    usage?: Usage,
    details?: unknown,
  ): ContextCompactionRecord {
    return {
      id: randomUUID(),
      summary,
      firstKeptMessageId: preparation.firstKeptEntryId,
      throughMessageId,
      tokensBefore: preparation.tokensBefore,
      ...(usage ? { usage } : {}),
      retainedTail: preparation.retainedTail,
      details: this.checkpointDetailsWithGeneration(details),
      providerId: this.provider.id,
      modelId: this.provider.modelId,
      createdAt: nowIso(),
    };
  }

  /**
   * Stamp the checkpoint with its generation so the context inspector can show
   * how many times a session has been compacted. A non-object `details` value
   * is nested rather than dropped: it belongs to whoever produced it.
   */
  private checkpointDetailsWithGeneration(details: unknown): unknown {
    const base =
      details && typeof details === "object" && !Array.isArray(details)
        ? (details as Record<string, unknown>)
        : details === undefined
          ? {}
          : { value: details };
    return {
      ...base,
      generation: this.activeCompaction
        ? checkpointGeneration(this.activeCompaction.details) + 1
        : 1,
    };
  }

  /**
   * Build the checkpoint a failed compaction installs: the summary it was
   * carrying forward, a recovery notice, and the real recent window of the range
   * it could not summarize (ADR 0049, issue #827).
   *
   * The window, not the notice, is what makes this checkpoint usable: with no
   * fresh summary it is the only thing carrying the range forward, so the
   * continuation text names it as the tail of the turn instead of presenting one
   * leftover user line as the whole job.
   */
  private createFallbackCheckpoint(
    preparation: ShapedPreparation,
    throughMessageId: string,
    maxSummaryChars: number,
    retentionMode: CompactionRetentionMode,
    budget: ContextBudget,
    failureReason: CompactionFailureReason,
    tailScale = 1,
  ): ContextCompactionRecord {
    const previousSummary = preparation.previousSummary
      ? boundedText(
          preparation.previousSummary,
          Math.min(COMPACTION_FALLBACK_MAX_SUMMARY_CHARS, maxSummaryChars),
        )
      : COMPACTION_FALLBACK_NO_SUMMARY;
    const continuation =
      retentionMode === "active_turn"
        ? "The provider is continuing the active turn: the recent messages carried below are the tail of that turn and the carried summary is the older history. Continue the work they describe."
        : "The previous turn is complete. Treat this summary and the recent messages below as historical context; the next user message is the only new task to execute.";
    const summary = [
      previousSummary,
      COMPACTION_FALLBACK_MARKER,
      "The automatic summary request did not complete. Older messages before this checkpoint are omitted from the next model request.",
      `The complete transcript remains available in the session. ${continuation}`,
    ].join("\n\n");
    const retainedTail = this.fallbackRetainedTail(
      preparation,
      budget,
      maxSummaryChars,
      retentionMode,
      tailScale,
    );
    return this.createCheckpoint(
      {
        ...preparation,
        retainedTail,
      },
      throughMessageId,
      summary,
      undefined,
      {
        ...this.checkpointDetails(preparation),
        fallback: "retained_tail" satisfies ContextCompactionFallback,
        failureCode: "CONTEXT_COMPACTION_FAILED",
        failureReason,
        retainedTailMode: retentionMode,
        // The shape tells a rebuild to replay the whole window. Without it a
        // restored checkpoint narrows the tail back to one user message, which
        // is the defect this window exists to fix (#827).
        retainedTailShape: COMPACTION_RETAINED_TAIL_SHAPE,
        retainedTailCount: retainedTail.length,
        ...this.retainedReasoningForCheckpoint(preparation),
      },
    );
  }

  /**
   * The recent window a fallback retains. Bounded by the keep-recent target so a
   * failure never carries more history than a successful checkpoint would, and
   * by what the safe budget leaves once the carried-forward summary and the
   * recovery notice are paid for — `persistCheckpoint` re-estimates the installed
   * context, and an oversized fallback would fail the run outright.
   */
  private fallbackRetainedTail(
    preparation: ShapedPreparation,
    budget: ContextBudget,
    maxSummaryChars: number,
    retentionMode: CompactionRetentionMode,
    tailScale: number,
  ): AgentMessage[] {
    const summaryTokens = Math.ceil(maxSummaryChars / 4);
    const available = Math.max(
      1,
      budget.hardLimit - summaryTokens - COMPACTION_FALLBACK_NOTICE_TOKENS,
    );
    const target = Math.max(
      1,
      Math.min(
        budget.keepRecentTokens,
        Math.floor(budget.hardLimit * COMPACTION_FALLBACK_KEEP_RECENT_RATIO),
      ),
    );
    return selectRecentTail(
      preparation.messagesToSummarize,
      Math.max(1, Math.floor(Math.min(target, available) * tailScale)),
      { latestUserGoal: retentionMode === "active_turn" },
    );
  }

  /**
   * The recovery path retains less than a normal checkpoint: its summary is a
   * carried-forward one rather than a fresh one, so the retained messages are
   * the only thing that has to fit.
   */
  private prepareFallbackCompactionInput(
    entries: Entry[],
    budget: ContextBudget,
    retentionMode: CompactionRetentionMode = "completed_turn",
  ) {
    return this.prepareCompactionInput(
      entries,
      budget,
      Math.max(
        1,
        Math.min(
          this.retainedUserMessageBudget(budget),
          Math.floor(budget.hardLimit * COMPACTION_FALLBACK_KEEP_RECENT_RATIO),
        ),
      ),
      retentionMode,
    );
  }

  /**
   * Tokens one summary prompt may carry for this model window. The preflight
   * guard and the chunk planner have to agree on it, so it is computed once here
   * from the shared formula.
   */
  private summaryInputLimit(budget: {
    hardLimit: number;
    requestHeadroom: number;
  }): number {
    return compactionSummaryInputLimit({
      hardLimit: budget.hardLimit,
      requestHeadroom: budget.requestHeadroom,
      modelMaxTokens: this.model.maxTokens,
    });
  }

  private compactionSummaryWouldExceedBudget(
    preparation: ShapedPreparation,
    budget: { hardLimit: number; requestHeadroom: number },
  ): boolean {
    // The summary covers the whole boundary range, so its input is the context
    // that tripped the hard limit. This sizes the prompt the way pi serializes
    // it — tool results already capped — rather than the raw messages, which
    // overstated tool-heavy sessions by several times and skipped summaries that
    // would have fit (#543). A prompt this large is now summarized in chunks
    // rather than skipped (#827); only the planner can still send the turn to
    // retained-tail recovery.
    return (
      estimateSummaryPromptTokens(preparation) >= this.summaryInputLimit(budget)
    );
  }

  /**
   * Fit the summary input under the provider budget. The full input is tried
   * first; when it is too large, one reduced pass (tool results cut to a short
   * prefix, thinking dropped) is tried before giving up. The reduced input still
   * covers every message the checkpoint files behind its boundary, so nothing is
   * silently dropped from the summary's scope (ADR 0282).
   */
  private fitSummaryInputToBudget(
    preparation: ShapedPreparation,
    budget: { hardLimit: number; requestHeadroom: number },
  ): ShapedPreparation | undefined {
    if (!this.compactionSummaryWouldExceedBudget(preparation, budget)) {
      return preparation;
    }
    const reduced = reduceSummaryInput(preparation);
    if (!reduced || this.compactionSummaryWouldExceedBudget(reduced, budget)) {
      return undefined;
    }
    return reduced;
  }

  /**
   * Plan the summary requests for a range no single prompt can carry: the
   * reduced input when one exists, split into contiguous chunks that each fit.
   * Returns undefined when the range cannot be planned, which is the only budget
   * failure that still routes a turn to retained-tail recovery (#827).
   */
  private planSummaryRequests(
    preparation: ShapedPreparation,
    budget: { hardLimit: number; requestHeadroom: number },
  ): AgentMessage[][] | undefined {
    const reduced = reduceSummaryInput(preparation) ?? preparation;
    const reserveTokens = compactionSummaryReserveTokens({
      previousSummary: preparation.previousSummary,
      outputBudget: compactionSummaryOutputBudget({
        requestHeadroom: budget.requestHeadroom,
        modelMaxTokens: this.model.maxTokens,
      }),
    });
    return planSummaryChunks(reduced, {
      summaryInputLimit: this.summaryInputLimit(budget),
      reserveTokens,
    });
  }

  private async persistCheckpoint(
    checkpoint: ContextCompactionRecord,
    reason: ContextCompactionReason,
    willRetry: boolean,
    mustFitSafeBudget: boolean,
    fallback?: ContextCompactionFallback,
  ): Promise<CheckpointPersistResult> {
    const systemMessage = systemTranscriptCheckpoint(this.agent.state.messages);
    checkpoint = {
      ...checkpoint,
      details: { ...(isRecord(checkpoint.details) ? checkpoint.details : {}), ...(systemMessage ? { systemMessageJson: JSON.stringify(systemMessage) } : {}) },
    };
    const compactedBudget = this.contextBudget(
      this.liveSessionContext(checkpoint).messages,
    );
    if (
      mustFitSafeBudget &&
      compactedBudget.tokens >= compactedBudget.hardLimit
    ) {
      return "oversized";
    }
    // The composer would otherwise keep showing the last pre-compaction
    // request's usage until another request reports one (#2015). The estimate
    // rides in the opaque details so it survives a reload like the generation.
    checkpoint = {
      ...checkpoint,
      details: {
        ...(isRecord(checkpoint.details) ? checkpoint.details : {}),
        contextTokens: compactedBudget.tokens,
      },
    };
    try {
      await this.host.call("session.appendCompaction", {
        sessionId: this.sessionId,
        compaction: checkpoint,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      this.emitCompactionFailure(reason, checkpoint.tokensBefore, message);
      return "failed";
    }

    this.activeCompaction = checkpoint;
    // A new window means both reminders are available again, matching Codex
    // resetting its `claim_*` flags when the context window turns over.
    this.contextReminderClaimed = false;
    this.contextFallbackReminderClaimed = false;
    this.agent.state.messages = this.liveSessionContext().messages;
    for (const message of this.agent.state.messages) {
      if (message.role === "system") this.systemJournal.remember(message, checkpoint.id);
    }
    this.emit({
      type: "compaction_end",
      reason,
      ok: true,
      tokensBefore: checkpoint.tokensBefore,
      firstKeptMessageId: checkpoint.firstKeptMessageId,
      willRetry,
      ...(fallback ? { fallback } : {}),
      mark: contextCompactionMark(checkpoint),
    });
    return "persisted";
  }

  private fallbackPreparation(
    entries: Entry[],
    budget: ContextBudget,
    preparation?: ShapedPreparation,
    retentionMode: CompactionRetentionMode = "completed_turn",
  ): ShapedPreparation | undefined {
    const fallbackInput = this.prepareFallbackCompactionInput(
      entries,
      budget,
      retentionMode,
    );
    if (fallbackInput.ok && fallbackInput.value) return fallbackInput.value;

    // A persisted checkpoint can be the last entry when a new prompt pushes
    // its retained tail over the hard limit. pi correctly reports that there
    // is no new history to summarize; rebuild a smaller tail from the full
    // transcript while carrying the existing summary forward.
    const terminal = entries.at(-1);
    if (terminal?.type !== "compaction") return preparation;
    const sourceInput = this.prepareFallbackCompactionInput(
      entries.slice(0, -1),
      budget,
      retentionMode,
    );
    if (!sourceInput.ok || !sourceInput.value) return preparation;
    return {
      ...sourceInput.value,
      // Same rule as `prepareCompactionInput`: strip a fallback notice but keep
      // the summary it carries forward, so a chained fallback cannot bake in
      // the notice or discard the real history along with it (#224).
      previousSummary:
        stripCompactionFallbackNotice(terminal.summary) ??
        sourceInput.value.previousSummary,
    };
  }

  private async recoverCompactionFailure(
    entries: Entry[],
    budget: ContextBudget,
    reason: ContextCompactionReason,
    willRetry: boolean,
    preparation: ShapedPreparation | undefined,
    failureMessage: string,
    retentionMode: CompactionRetentionMode,
    failureReason: CompactionFailureReason = "summary_provider",
  ): Promise<boolean> {
    if (reason === "manual") {
      this.emitCompactionFailure(
        reason,
        preparation?.tokensBefore,
        failureMessage,
      );
      return false;
    }

    const fallbackPreparation = this.fallbackPreparation(
      entries,
      budget,
      preparation,
      retentionMode,
    );
    if (!fallbackPreparation) {
      this.emitCompactionFailure(reason, undefined, failureMessage);
      return false;
    }
    const throughMessageId = this.fullEntries.at(-1)?.id;
    if (!throughMessageId) {
      this.emitCompactionFailure(
        reason,
        fallbackPreparation.tokensBefore,
        "Compaction has no durable transcript boundary",
      );
      return false;
    }

    // The tail is sized from the local estimate, but the install check below
    // measures the calibrated one. A provider whose tokenizer counts more than
    // the estimate (CJK text, for one) makes the first window too large, and
    // failing here leaves every later turn at the same hard limit (#2494).
    // Halve the window until it fits; the newest message is always kept.
    for (let tailScale = 1; ; tailScale /= 2) {
      const checkpoint = this.createFallbackCheckpoint(
        fallbackPreparation,
        throughMessageId,
        Math.max(
          256,
          Math.min(
            COMPACTION_FALLBACK_MAX_SUMMARY_CHARS,
            Math.floor(budget.hardLimit * 0.75),
          ),
        ),
        retentionMode,
        budget,
        failureReason,
        tailScale,
      );
      const persisted = await this.persistCheckpoint(
        checkpoint,
        reason,
        willRetry,
        true,
        "retained_tail",
      );
      if (persisted === "persisted") return true;
      if (persisted === "failed") return false;
      if (tailScale <= COMPACTION_FALLBACK_MIN_TAIL_SCALE) {
        this.emitCompactionFailure(
          reason,
          checkpoint.tokensBefore,
          "Automatic context recovery could not reduce the retained context below the safe model budget",
        );
        return false;
      }
    }
  }

  private async generateCompaction(
    preparation: ShapedPreparation,
    signal: AbortSignal,
  ): Promise<Awaited<ReturnType<typeof compact>>> {
    const usageTurnId = this.turnId;
    const requestId = randomUUID();
    this.compactionRequestShape = undefined;
    this.compactionShapeLogged = false;
    const models = withCompactionRequestHeaders(
      this.models,
      this.provider,
      this.sessionId,
      (usage) => this.emit({ type: "usage", usage }, usageTurnId),
      (shape) => {
        this.compactionRequestShape = shape;
        this.compactionShapeLogged = true;
        this.emitCompactionDiagnostic("compaction_shape", requestId, {
          requestShape: "observed",
          ...shape,
        });
      },
    );
    try {
      const result = await compact(
        preparation,
        // The summary is a provider request like any other turn. The desktop
        // compaction adapter calls `completeSimple` directly instead of
        // `streamFn`, so headers have to ride on the collection.
        models,
        this.model,
        undefined,
        agentThinkingLevel(this.thinkingLevel),
        // Without a policy pi-ai returns the first failed response as-is, which
        // made a single dropped stream or 503 discard the whole summary (#543).
        // pi's classifier decides what is transient; the waits honour `signal`.
        COMPACTION_SUMMARY_RETRY_POLICY,
        undefined,
        signal,
      );
      if (!result.ok) {
        this.emitCompactionFailureDiagnostic(
          requestId,
          "summary_provider",
          preparation.tokensBefore,
          result.error,
        );
      }
      return result;
    } catch (error) {
      this.emitCompactionFailureDiagnostic(requestId, "summary_provider", preparation.tokensBefore, error);
      throw error;
    }
  }

  /**
   * Summarize a range whose prompt does not fit the provider window, however far
   * it was reduced. Each chunk is one pi summary request — same prompt, retry
   * policy, and headers as the single-pass path — and each carries the summary of
   * the chunk before it, so the chain converges on one summary covering every
   * message the checkpoint files behind its boundary. Only the last chunk is given
   * the range's file operations, so the file list is appended to the summary
   * exactly once.
   */
  private async generateChunkedCompaction(
    preparation: ShapedPreparation,
    chunks: AgentMessage[][],
    signal: AbortSignal,
  ): Promise<Awaited<ReturnType<typeof compact>>> {
    let summary = preparation.previousSummary;
    let usage: Usage | undefined;
    let details: unknown;
    for (const [index, messages] of chunks.entries()) {
      const last = index === chunks.length - 1;
      const step = await this.generateCompaction(
        {
          ...preparation,
          messagesToSummarize: messages,
          turnPrefixMessages: [],
          isSplitTurn: false,
          previousSummary: summary,
          fileOps: last ? preparation.fileOps : emptyFileOps(),
        },
        signal,
      );
      if (!step.ok) return step;
      summary = step.value.summary;
      usage = addSummaryUsage(usage, step.value.usage);
      if (last) details = step.value.details;
    }
    return {
      ok: true,
      value: {
        summary: summary ?? "",
        tokensBefore: preparation.tokensBefore,
        usage,
        retainedTail: preparation.retainedTail,
        details: toJsonValue(details),
      },
    };
  }

  /**
   * Produce a checkpoint without touching the session: no persistence, no
   * `activeCompaction` mutation, no events. Keeping generation separate from
   * installation is what lets a failed build fall through to the retained-tail
   * recovery path without having already changed the session.
   */
  private async buildCheckpoint(
    signal: AbortSignal,
    retentionMode: CompactionRetentionMode,
  ): Promise<CheckpointBuild> {
    this.compactionDiagnosticBudget = undefined;
    const entries = this.entriesWithCompaction();
    const context = buildSessionContext(entries, this.reasoningReplayIdentity());
    const budget = this.contextBudget(context.messages);
    const preparation = this.prepareCompactionInput(
      entries,
      budget,
      this.retainedUserMessageBudget(budget),
      retentionMode,
    );
    if (!preparation.ok || !preparation.value) {
      this.emitCompactionFailureDiagnostic(
        randomUUID(),
        preparation.ok ? "no_new_history" : "summary_budget",
        undefined,
        preparation.ok ? "No new context is available to compact" : preparation.error,
        {
          requestShape: "not_sent",
          hardLimit: budget.hardLimit,
          outputBudget: compactionSummaryOutputBudget({
            requestHeadroom: budget.requestHeadroom,
            modelMaxTokens: this.model.maxTokens,
          }),
          plannedChunks: 0,
        },
      );
      return {
        ok: false,
        entries,
        budget,
        message: preparation.ok
          ? "No new context is available to compact"
          : preparation.error.message,
        failureReason: "no_new_history",
        recoverable: true,
      };
    }

    if (this.compactionStrategy === "fresh_window") {
      return this.buildRolloverCheckpoint(entries, budget, preparation.value);
    }

    const summaryInput = this.fitSummaryInputToBudget(preparation.value, budget);
    // No single prompt fits. The range is summarized in chunks instead of giving
    // up on the model: only a range that cannot be planned at all — empty, or
    // needing more requests than the planner allows — still falls back (#827).
    const chunks = summaryInput
      ? undefined
      : this.planSummaryRequests(preparation.value, budget);
    this.compactionDiagnosticBudget = {
      hardLimit: budget.hardLimit,
      outputBudget: compactionSummaryOutputBudget({
        requestHeadroom: budget.requestHeadroom,
        modelMaxTokens: this.model.maxTokens,
      }),
      plannedChunks: chunks?.length ?? 1,
    };
    if (!summaryInput && !chunks) {
      this.emitCompactionFailureDiagnostic(
        randomUUID(),
        "summary_budget",
        preparation.value.tokensBefore,
        "Compaction summary input exceeds the safe model budget",
        {
          requestShape: "not_sent",
          hardLimit: budget.hardLimit,
          outputBudget: compactionSummaryOutputBudget({
            requestHeadroom: budget.requestHeadroom,
            modelMaxTokens: this.model.maxTokens,
          }),
          plannedChunks: 0,
        },
      );
      return {
        ok: false,
        entries,
        budget,
        preparation: preparation.value,
        tokensBefore: preparation.value.tokensBefore,
        message: "Compaction summary input exceeds the safe model budget",
        failureReason: "summary_budget",
        recoverable: true,
      };
    }

    let result: Awaited<ReturnType<typeof compact>>;
    try {
      result = summaryInput
        ? await this.generateCompaction(summaryInput, signal)
        : await this.generateChunkedCompaction(
            preparation.value,
            chunks!,
            signal,
          );
    } catch (error) {
      return {
        ok: false,
        entries,
        budget,
        preparation: preparation.value,
        tokensBefore: preparation.value.tokensBefore,
        message: error instanceof Error ? error.message : String(error),
        failureReason: "summary_provider",
        recoverable: !signal.aborted,
      };
    }
    if (!result.ok) {
      return {
        ok: false,
        entries,
        budget,
        preparation: preparation.value,
        tokensBefore: preparation.value.tokensBefore,
        message: result.error.message,
        failureReason: "summary_provider",
        recoverable: result.error.code !== "aborted",
      };
    }

    const throughMessageId = this.fullEntries.at(-1)?.id;
    if (!throughMessageId) {
      return {
        ok: false,
        entries,
        budget,
        preparation: preparation.value,
        tokensBefore: result.value.tokensBefore,
        message: "Compaction has no durable transcript boundary",
        recoverable: false,
      };
    }
    return {
      ok: true,
      entries,
      budget,
      preparation: preparation.value,
      checkpoint: this.createCheckpoint(
        preparation.value,
        throughMessageId,
        result.value.summary,
        result.value.usage,
        {
          ...(isRecord(result.value.details) ? result.value.details : {}),
          strategy: "summary" satisfies CompactionStrategy,
          retainedTailMode: retentionMode,
          ...this.retainedReasoningForCheckpoint(preparation.value),
        },
      ),
    };
  }

  /**
   * Roll the context over without summarizing it, the way Codex's token-budget
   * compaction does. No model request, so nothing here can fail on the provider
   * and the ADR 0049 summary fallback has nothing to catch. The rest of the
   * lifecycle is shared with the summary family: this still produces a durable
   * checkpoint, a `compaction_end`, and everything the user sees.
   */
  private buildRolloverCheckpoint(
    entries: Entry[],
    budget: ContextBudget,
    preparation: ShapedPreparation,
  ): CheckpointBuild {
    const throughMessageId = this.fullEntries.at(-1)?.id;
    if (!throughMessageId) {
      return {
        ok: false,
        entries,
        budget,
        preparation,
        tokensBefore: preparation.tokensBefore,
        message: "Compaction has no durable transcript boundary",
        recoverable: false,
      };
    }
    // Codex clears history outright. Retaining nothing is the point of this
    // family: it buys the whole window back instead of a summary's worth.
    const rollover: ShapedPreparation = { ...preparation, retainedTail: [] };
    return {
      ok: true,
      entries,
      budget,
      preparation: rollover,
      checkpoint: this.createCheckpoint(
        rollover,
        throughMessageId,
        CONTEXT_ROLLOVER_SUMMARY,
        undefined,
        {
          ...this.checkpointDetails(rollover),
          strategy: "fresh_window" satisfies CompactionStrategy,
          retainedTailMode: "completed_turn" satisfies CompactionRetentionMode,
        },
      ),
    };
  }

  /**
   * Install an already-generated checkpoint on the blocking path. The budget
   * recheck inside `persistCheckpoint` runs against the current transcript, so
   * a checkpoint built earlier is still validated against what it would
   * actually produce now.
   */
  private async installCheckpoint(
    build: CheckpointBuildSuccess,
    reason: ContextCompactionReason,
    willRetry: boolean,
    retentionMode: CompactionRetentionMode,
  ): Promise<boolean> {
    const mustFitSafeBudget =
      reason === "overflow" || build.budget.tokens >= build.budget.hardLimit;
    const persisted = await this.persistCheckpoint(
      build.checkpoint,
      reason,
      willRetry,
      mustFitSafeBudget,
    );
    if (persisted === "persisted" || persisted === "failed") {
      return persisted === "persisted";
    }
    return await this.recoverCompactionFailure(
      build.entries,
      build.budget,
      reason,
      willRetry,
      build.preparation,
      "The checkpoint did not reduce context below the safe request budget",
      retentionMode,
      "checkpoint_oversized",
    );
  }

  private async performCompaction(
    reason: ContextCompactionReason,
    willRetry: boolean,
    retentionMode: CompactionRetentionMode,
  ): Promise<boolean> {
    this.emit({ type: "compaction_start", reason });
    this.compactionAbort = new AbortController();
    let build: CheckpointBuild;
    try {
      build = await this.buildCheckpoint(this.compactionAbort.signal, retentionMode);
    } finally {
      this.compactionAbort = undefined;
    }
    if (!build.ok) {
      if (!build.recoverable) {
        this.emitCompactionFailure(reason, build.tokensBefore, build.message);
        return false;
      }
      return await this.recoverCompactionFailure(
        build.entries,
        build.budget,
        reason,
        willRetry,
        build.preparation,
        build.message,
        retentionMode,
        build.failureReason ?? "summary_provider",
      );
    }
    return await this.installCheckpoint(build, reason, willRetry, retentionMode);
  }

  async compactManually(): Promise<void> {
    if (this.disposed) throw new Error("runtime disposed");
    if (this.agent.state.isStreaming || this.compactionInProgress) {
      throw Object.assign(new Error("session already has an active turn"), {
        errorCode: "AGENT_BUSY",
      });
    }
    try {
      const ok = await this.runCompaction("manual", false);
      if (!ok) {
        throw Object.assign(new Error("context compaction failed"), {
          errorCode: "CONTEXT_COMPACTION_FAILED",
        });
      }
    } finally {
      if (this.agentActivity?.phase === "compacting") this.clearAgentActivity();
    }
  }

  /**
   * Fold pi-ai hostedSearch content blocks and message citations into the
   * current assistant bubble as `UiMessage.hostedSearch`, emitting a
   * full-frame message_update when the normalized state actually changed.
   * Search state transitions are low frequency, so a full frame costs less
   * than teaching every delta path about the field.
   */
  private applyHostedSearch(message: AssistantMessage): void {
    if (!this.currentAssistant) return;
    const next = hostedSearchFromMessage({
      content: message.content,
      citations: message.hostedSearchCitations,
    });
    if (!next) return;
    const previous = this.currentAssistant.hostedSearch;
    if (previous && JSON.stringify(previous) === JSON.stringify(next)) return;
    this.currentAssistant = {
      ...this.currentAssistant,
      hostedSearch: next,
    };
    this.emit({ type: "message_update", message: this.currentAssistant });
  }

  private async handleAgentEvent(event: AgentEvent) {
    this.forwardAgentEventToExtensions(event);
    switch (event.type) {
      case "agent_start":
        if (this.steeringContinuation) break;
        if (
          this.providerRetryInProgress ||
          this.overflowRecoveryInProgress ||
          this.silentTurnRerunInProgress ||
          this.progressTurnRerunInProgress
        ) {
          break;
        }
        this.emit({ type: "agent_start" });
        break;
      case "turn_start":
        if (
          this.providerRetryInProgress ||
          this.overflowRecoveryInProgress ||
          this.silentTurnRerunInProgress ||
          this.progressTurnRerunInProgress
        ) {
          break;
        }
        this.emit({ type: "turn_start" });
        break;
      case "message_start": {
        if (event.message.role === "assistant") {
          this.clearAgentActivity();
          this.streamStartedAt = Date.now();
          const content = assistantContent(event.message.content);
          const retryingAssistant =
            this.providerRetryInProgress ||
            this.overflowRecoveryInProgress ||
            this.silentTurnRerunInProgress ||
            this.progressTurnRerunInProgress
              ? this.currentAssistant
              : undefined;
          const requestWaitMs =
            this.requestStartedAt !== undefined
              ? Math.max(0, Date.now() - this.requestStartedAt)
              : undefined;
          const cumulativeProviderWaitMs =
            requestWaitMs !== undefined ||
            retryingAssistant?.providerWaitMs !== undefined
              ? (retryingAssistant?.providerWaitMs ?? 0) + (requestWaitMs ?? 0)
              : undefined;
          const initialText =
            content.hasText && content.text.length > 0
              ? content.text
              : this.progressTurnRerunInProgress || this.overflowRecoveryInProgress
                ? retryingAssistant?.content ?? ""
                : content.text;
          this.liveCommentary = initialText === content.text ? content.transcript : undefined;
          this.currentAssistant = {
            id: retryingAssistant?.id ?? randomUUID(),
            role: "assistant",
            content: initialText,
            ...(content.hasThinking && content.thinking
              ? { thinking: content.thinking }
              : {}),
            createdAt: nowIso(),
            status: "streaming",
            modelId: this.provider.modelId,
            providerId: this.provider.id,
            ...(retryingAssistant?.modelStreamDurationMs !== undefined
              ? { modelStreamDurationMs: retryingAssistant.modelStreamDurationMs }
              : {}),
            ...(cumulativeProviderWaitMs !== undefined
              ? { providerWaitMs: cumulativeProviderWaitMs }
              : {}),
          };
          if (retryingAssistant) {
            // Keep one visible assistant bubble across the bounded retry. The
            // failed partial response is replaced instead of leaving a
            // duplicate error row when the second request succeeds. The same
            // applies to a silent-turn re-run: one bubble, no empty row.
            this.providerRetryInProgress = false;
            this.overflowRecoveryInProgress = false;
            this.silentTurnRerunInProgress = false;
            this.progressTurnRerunInProgress = false;
            this.emit({ type: "message_update", message: this.currentAssistant });
          } else {
            this.emit({ type: "message_start", message: this.currentAssistant });
          }
          this.applyHostedSearch(event.message);
        }
        // User messages are echoed and persisted by the desktop main process
        // (agentPrompt handler); re-emitting them here would duplicate the
        // bubble in the transcript since each emit mints a fresh id.
        break;
      }
      case "message_update": {
        if (this.currentAssistant && event.message.role === "assistant") {
          this.applyHostedSearch(event.message);
          const content = assistantContent(event.message.content);
          const previousCommentary = this.liveCommentary;
          if (content.hasText) this.liveCommentary = content.transcript;
          const previousText = this.currentAssistant.content;
          const previousThinking = this.currentAssistant.thinking ?? "";
          const nextText = content.hasText ? content.text : previousText;
          const nextThinking = content.hasThinking
            ? content.thinking
            : previousThinking;
          const textDelta = content.hasText
            ? cumulativeDelta(previousCommentary?.text ?? previousText, this.liveCommentary?.text ?? content.text)
            : { delta: "", reset: false };
          const thinkingDelta = content.hasThinking
            ? cumulativeDelta(previousThinking, content.thinking)
            : { delta: "", reset: false };
          this.currentAssistant = {
            ...this.currentAssistant,
            content: nextText,
            ...(nextThinking
              ? { thinking: nextThinking }
              : content.hasThinking
                ? { thinking: undefined }
                : {}),
            status: "streaming",
          };
          if (!sameCommentaryBoundaries(previousCommentary, this.liveCommentary) || (this.liveCommentary && textDelta.reset)) {
            this.emit({ type: "message_update", message: this.currentAssistant });
          } else if (
            textDelta.delta ||
            thinkingDelta.delta ||
            textDelta.reset ||
            thinkingDelta.reset
          ) {
            this.emit({
              type: "message_update",
              message: this.currentAssistant,
              ...(textDelta.delta ? { deltaText: textDelta.delta } : {}),
              ...(thinkingDelta.delta ? { deltaThinking: thinkingDelta.delta } : {}),
              ...(textDelta.reset ? { resetText: true } : {}),
              ...(thinkingDelta.reset ? { resetThinking: true } : {}),
            });
          }
        }
        break;
      }
      case "message_end": {
        if (event.message.role === "user") {
          const steering = this.pendingSteering.get(event.message);
          const id = steering?.id ?? this.pendingUserMessageId ?? randomUUID();
          if (steering) {
            // 后续回复必须位于已接收的用户补充之后,恢复重试也不能复用前一气泡。
            if (this.currentAssistant?.status === "streaming") {
              this.emit({ type: "message_end", message: {
                ...this.currentAssistant,
                status: this.currentAssistant.error ? "error" : "complete",
              } });
            }
            this.currentAssistant = undefined;
            this.liveCommentary = undefined;
            if (steering.toolNames.length) {
              this.activateDeferredTools(steering.toolNames);
              this.setAgentTools(this.activeTools());
            }
            this.pendingSteering.delete(event.message);
            const prompt = steering.delegationPrompt;
            this.delegationPrompt = prompt && (() => Promise.resolve(prompt));
            // User input is now part of the model context: whatever the model
            // says next answers the user, not a completion notice, so the
            // ordinary response contract applies again.
            this.allowSilentCompletion = false;
          } else {
            this.pendingUserMessageId = undefined;
          }
          this.appendLiveEntry(id, event.message);
          break;
        }
        if (event.message.role === "toolResult") {
          this.appendLiveEntry(event.message.toolCallId || randomUUID(), event.message);
          break;
        }
        if (this.currentAssistant && event.message.role === "assistant") {
          const assistantId = this.currentAssistant.id;
          const content = assistantContent(event.message.content);
          const visibleTranscript = content.hasText ? content.transcript?.text : this.liveCommentary?.text;
          this.liveCommentary = content.transcript;
          // pi-agent-core encodes stream failures in the final message
          // (stopReason "error"/"aborted" + errorMessage) and resolves the
          // prompt normally, so this is where provider/model errors surface.
          const stopReason = event.message.stopReason;
          const localError = readLocalRequestErrorDetails(event.message);
          const overflow = !localError && isContextOverflow(
            event.message,
            effectiveModelContextWindow(this.model) || DEFAULT_CONTEXT_WINDOW,
          );
          const aborted = stopReason === "aborted" || localError?.causeName === "AbortError";
          const failed = !aborted && (stopReason === "error" || overflow);
          const errorMessage =
            failed &&
            typeof (event.message as any).errorMessage === "string" &&
            (event.message as any).errorMessage
              ? ((event.message as any).errorMessage as string)
              : failed
                ? "provider stream failed"
                : undefined;
          let classifiedError = overflow
            ? errorMessage
              ? classifyAgentError(errorMessage)
              : {
                  code: "CONTEXT_TOO_LARGE",
                  message:
                    "The provider rejected or truncated an oversized model context",
                  retriable: false,
                }
            : errorMessage
              ? classifyProviderError(event.message, this.providerResponseStatus)
              : undefined;
          const nextText = content.hasText
            ? content.text
            : this.currentAssistant.content;
          const nextThinking = content.hasThinking
            ? content.thinking
            : this.currentAssistant.thinking ?? "";
          // `nextText` may include text retained in a reused assistant bubble
          // from an earlier recovery attempt. Recovery classification must
          // inspect only the response that just ended, or a silent retry after
          // progress text would look non-silent forever.
          const responseText = content.hasText ? content.text : "";
          // Annotate literal calls without aborting valid structured siblings.
          const textCallDiagnostic = !failed && !aborted
            ? textToolCallDiagnostic(responseText, this.toolCatalog)
            : undefined;
          if (looksLikePseudoToolCall(nextText)) {
            // The visible text is a lost tool batch, not an answer. Logging it
            // separates "the model went quiet" from "the model tried to act and
            // the call never reached the host" when a session is reviewed.
            process.stderr.write(
              `[agent-runtime] assistant emitted a tool call as text (session=${this.sessionId} turn=${this.turnId})\n`,
            );
          }
          const usage = usageFromPi((event.message as any).usage as Usage | undefined);
          // Measure the estimator against this request: the parked estimate
          // describes the same context, and only a settled, non-aborted
          // response actually carried the request. Consumed either way, so a
          // failed attempt cannot pair with a later usage report.
          this.recordContextCalibration(usage, failed || aborted);
          const hostedSearch = hostedSearchFromMessage({
            content: event.message.content,
            citations: event.message.hostedSearchCitations,
          });
          if (hostedSearch) {
            const terminal = failed || aborted ? "failed" : "completed";
            for (const round of hostedSearch.rounds) {
              if (round.status === "searching") round.status = terminal;
            }
            hostedSearch.status = hostedSearch.rounds.some(
              (round) => round.status === "failed",
            )
              ? "failed"
              : "completed";
          }
          const endedAt = Date.now();
          const providerWaitMs =
            this.requestStartedAt !== undefined &&
            this.streamStartedAt !== undefined
              ? this.streamStartedAt - this.requestStartedAt
              : undefined;
          const streamMs =
            this.streamStartedAt !== undefined
              ? Math.max(0, endedAt - this.streamStartedAt)
              : undefined;
          const modelStreamDurationMs =
            (this.currentAssistant.modelStreamDurationMs ?? 0) +
            (streamMs ?? 0);
          if (classifiedError) {
            classifiedError = this.providerErrorWithDiagnostics(
              classifiedError,
              "stream",
              providerWaitMs,
              streamMs,
            );
          }
          // Only a completed response replenishes both budgets. Headers and
          // partial output must not let a repeatedly broken stream retry forever.
          if (!failed && !aborted) {
            this.providerTransientRetryAttempt = 0;
            this.providerRateLimitRetryAttempt = 0;
          }
          // Re-run an invisible answer once before surfacing a finished turn.
          const silence =
            !failed &&
            !aborted &&
            responseText.trim().length === 0 &&
            !content.transcript?.text.trim() &&
            !messageRequestsTools(event.message);
          // A completion notice needs no acknowledgement, so its own reply may
          // stay silent (D446). The exception covers exactly that reply: the
          // first settled response spends it, whether silent, textual, or a
          // tool batch, so later replies in the same run answer tool results
          // or user input under the ordinary contract. A provider failure
          // keeps it for the retried attempt.
          const exemptSilence = silence && this.allowSilentCompletion;
          if (!failed && !aborted) this.allowSilentCompletion = false;
          const silentTurn = silence && !exemptSilence;
          if (silentTurn && !this.silentTurnRerunAttempted) {
            this.silentTurnRerunAttempted = true;
            this.pendingSilentTurnRerun = true;
            this.suppressSilentTurnRunEnd = true;
            // Hold the bubble open. The re-run streams into this same one, so
            // a recovered turn leaves no empty message behind in the
            // transcript and the user never learns it happened.
            this.currentAssistant = {
              ...this.currentAssistant,
              content: nextText,
              ...(nextThinking
                ? { thinking: nextThinking }
                : content.hasThinking
                  ? { thinking: undefined }
                  : {}),
              status: "streaming",
              modelId: this.provider.modelId,
              providerId: this.provider.id,
              ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
              ...(usage ? { usage } : {}),
            };
            this.emit({ type: "message_update", message: this.currentAssistant });
            this.streamStartedAt = undefined;
            break;
          }
          if (silentTurn) {
            // The re-run came back silent too. Stop guessing and say so: an
            // error row with a retriable code gives the UI its "continue"
            // affordance instead of leaving the user to invent one.
            classifiedError = this.providerErrorWithDiagnostics(
              {
                code: "EMPTY_MODEL_RESPONSE",
                message:
                  "The model ended its turn without producing any output",
                retriable: true,
              },
              "stream",
              providerWaitMs,
              streamMs,
            );
          }
          // Autonomous plan/goal: clearly forward-looking text without a tool
          // call is probably progress, not a final answer. Nudge once (#43).
          const progressOnlyTurn =
            !failed &&
            !aborted &&
            !silentTurn &&
            this.autonomousExecution &&
            !this.silentTurnRerunAttempted &&
            !this.progressTurnRerunAttempted &&
            isProgressOnlyAssistantTurn(event.message);
          if (progressOnlyTurn) {
            this.progressTurnRerunAttempted = true;
            this.pendingProgressTurnRerun = true;
            this.suppressProgressTurnRunEnd = true;
            this.currentAssistant = {
              ...this.currentAssistant,
              content: nextText,
              ...(nextThinking
                ? { thinking: nextThinking }
                : content.hasThinking
                  ? { thinking: undefined }
                  : {}),
              status: "streaming",
              modelId: this.provider.modelId,
              providerId: this.provider.id,
              ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
              ...(usage ? { usage } : {}),
            };
            this.emit({ type: "message_update", message: this.currentAssistant });
            this.streamStartedAt = undefined;
            break;
          }
          const canRecoverOverflow =
            this.compactionEnabled &&
            overflow &&
            !this.overflowRecoveryAttempted;
          if (canRecoverOverflow) {
            // Keep the failed response inside the same visible assistant bubble
            // while compaction prepares the retry. A provider overflow is an
            // internal recovery transition, not a terminal user-facing error.
            this.currentAssistant = {
              ...this.currentAssistant,
              content: nextText,
              ...(nextThinking
                ? { thinking: nextThinking }
                : content.hasThinking
                  ? { thinking: undefined }
                  : {}),
              status: "streaming",
              modelId: this.provider.modelId,
              providerId: this.provider.id,
              ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
              ...(usage ? { usage } : {}),
            };
            this.emit({ type: "message_update", message: this.currentAssistant });
            this.streamStartedAt = undefined;
            this.pendingOverflow = true;
            this.suppressOverflowRunEnd = true;
            break;
          }
          const emptyResponse = silentTurn;
          const diagnosticError = classifiedError;
          const retryProviderAttempt =
            !overflow &&
            diagnosticError !== undefined &&
            diagnosticError.details?.origin !== "local"
              ? this.claimProviderRetry(diagnosticError, "stream")
              : undefined;
          if (
            retryProviderAttempt !== undefined &&
            diagnosticError !== undefined
          ) {
            this.pendingProviderRetry = diagnosticError;
            this.suppressProviderRetryRunEnd = true;
            this.currentAssistant = {
              ...this.currentAssistant,
              content: nextText,
              ...(nextThinking
                ? { thinking: nextThinking }
                : content.hasThinking
                  ? { thinking: undefined }
                  : {}),
              status: "streaming",
              modelId: this.provider.modelId,
              providerId: this.provider.id,
              ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
              ...(usage ? { usage } : {}),
            };
            this.emit({ type: "message_update", message: this.currentAssistant });
            this.streamStartedAt = undefined;
            break;
          }
          // Pi 1.1.0 measures from request start with a monotonic clock. Keep the
          // sidecar stopwatch for stopped and older streams that have no final message.
          const piDurationMs = event.message.durationMs;
          const responseDurationMs =
            typeof piDurationMs === "number" &&
            Number.isFinite(piDurationMs) &&
            piDurationMs > 0
              ? piDurationMs
              : this.streamStartedAt !== undefined
                ? Math.max(0, endedAt - this.streamStartedAt)
                : undefined;
          const responseOutputTokens =
            aborted && (!usage || usage.outputTokens <= 0)
              ? estimateVisibleResponseOutputTokens({
                  content: visibleTranscript ?? nextText,
                  thinking: nextThinking,
                })
              : undefined;
          // This message annotation does not become a terminal run error.
          classifiedError ??= textCallDiagnostic;
          this.currentAssistant = {
            ...this.currentAssistant,
            content: nextText,
            ...(nextThinking
              ? { thinking: nextThinking }
              : content.hasThinking
                ? { thinking: undefined }
                : {}),
            status: failed || emptyResponse || textCallDiagnostic
              ? "error"
              : aborted
                ? "aborted"
                : "complete",
            modelId: this.provider.modelId,
            providerId: this.provider.id,
            responseModelId: concreteResponseModel(event.message, this.provider.modelId),
            // Tool-call truncation is recovered by Pi; annotate only a visible
            // text answer, without turning the settled run into an error.
            outputTruncated: !failed && !aborted && stopReason === "length" &&
              Boolean(responseText.trim()) && !messageRequestsTools(event.message) || undefined,
            ...(usage ? { usage } : {}),
            ...(responseDurationMs !== undefined ? { responseDurationMs } : {}),
            ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
            ...(responseOutputTokens !== undefined
              ? { responseOutputTokens }
              : {}),
            ...(classifiedError
              ? { error: classifiedError, isError: true }
              : {}),
            ...(hostedSearch ? { hostedSearch } : {}),
            // Signatures only describe this response's own blocks. A bubble
            // that kept text from an earlier recovery attempt no longer lines
            // up with them, so it keeps only the function-call signatures,
            // which are linked by call id rather than by text position.
            providerReplay: failed
              ? undefined
              : providerReplayForBubble(
                  captureAssistantProviderReplay(event.message.content),
                  nextText === content.text && nextThinking === content.thinking,
                ),
          };
          if (!this.currentAssistant.providerReplay) delete this.currentAssistant.providerReplay;
          if (!this.currentAssistant.responseModelId) delete this.currentAssistant.responseModelId;
          this.emit({ type: "message_end", message: this.currentAssistant });
          this.liveCommentary = undefined;
          this.activeProviderRetryAttempt = 0;
          this.streamStartedAt = undefined;
          this.currentAssistant = undefined;
          if (exemptSilence) {
            // Accepted silence is still nothing worth resending: keep it out
            // of the runtime entries, exactly as a restored transcript would,
            // and out of pi's transcript state so the next request carries no
            // empty assistant message. pi appends the message before it
            // notifies listeners; the identity check keeps this from touching
            // anything else should that order ever change.
            const messages = this.agent.state.messages;
            if (messages.at(-1) === event.message) {
              this.setAgentMessages(messages.slice(0, -1));
            }
          } else if (!failed && !aborted && !emptyResponse) {
            this.appendLiveEntry(assistantId, event.message);
          } else {
            this.turnHadError = true;
          }
          if (diagnosticError) {
            this.terminateParentTurn();
            this.emit({ type: "error", error: diagnosticError });
          }
        }
        break;
      }
      case "tool_execution_start": {
        const startedAt = Date.now();
        this.clearAgentActivity();
        this.activeToolCalls.set(event.toolCallId, {
          toolName: event.toolName,
          args: event.args,
          startedAt,
        });
        this.emit({
          type: "tool_start",
          toolCallId: event.toolCallId,
          toolName: event.toolName,
          args: event.args,
        }, undefined, startedAt);
        break;
      }
      case "tool_execution_update":
        this.emit({
          type: "tool_update",
          toolCallId: event.toolCallId,
          partialResult: event.partialResult,
        });
        break;
      case "tool_execution_end":
        // The agent issues the follow-up provider request as soon as the tool
        // results are in, so this is the anchor for the next providerWaitMs.
        {
          const endedAt = Date.now();
          const activeTool = this.activeToolCalls.get(event.toolCallId);
          this.activeToolCalls.delete(event.toolCallId);
          this.bashYieldCalls.delete(event.toolCallId);
          if (
            this.activeToolCalls.size === 0 &&
            !this.disposed &&
            !this.runCancelled &&
            this.agentActivity?.phase !== "waiting-subagents"
          ) {
            this.setAgentActivity({ phase: "preparing", since: Date.now() });
          }
          const toolUsage = activeTool
            ? estimateToolTokenUsage(
                this.model,
                event.toolCallId,
                activeTool.toolName,
                activeTool.args,
                event.result,
                event.isError,
                endedAt,
              )
            : undefined;
          this.requestStartedAt = endedAt;
          this.emit({
            type: "tool_end",
            toolCallId: event.toolCallId,
            result: event.result,
            isError: event.isError,
            ...(toolUsage ? { toolUsage } : {}),
          }, undefined, endedAt);
          if (activeTool?.toolName === SUBAGENT_TOOL_NAME && isRecord(event.result)) {
            const details = event.result.details;
            const record = isRecord(details) && typeof details.delegationId === "string"
              ? this.delegations.get(details.delegationId)
              : undefined;
            if (record) {
              record.taskMessage = taskMessageSnapshot({
                ...activeTool,
                toolCallId: event.toolCallId,
                result: event.result,
                endedAt,
                ...(toolUsage ? { toolUsage } : {}),
              });
              // A fast delegate may settle before its Task tool_end arrives.
              this.publishDelegationSettlement(record);
            }
          }
        }
        break;
      case "turn_end":
        this.batchPlanner.settleBatch(event.message);
        if (
          this.suppressOverflowRunEnd ||
          this.suppressProviderRetryRunEnd ||
          this.suppressSilentTurnRunEnd ||
          this.suppressProgressTurnRunEnd ||
          this.keepTurnOpenForDelegates()
        )
          break;
        const subagentUsage = this.turnSubagentUsage;
        this.turnSubagentUsage = undefined;
        this.emit({
          type: "turn_end",
          ...(subagentUsage ? { subagentUsage } : {}),
        });
        break;
      case "agent_end":
        // Input admitted after pi's last queue poll still belongs to this turn.
        // Continue after the current run settles; never wake the follow-up FIFO.
        if (this.pendingSteering.size && this.acceptingSteering && !this.runCancelled && !this.turnHadError) break;
        if (
          this.suppressOverflowRunEnd ||
          this.suppressProviderRetryRunEnd ||
          this.suppressSilentTurnRunEnd ||
          this.suppressProgressTurnRunEnd ||
          this.keepTurnOpenForDelegates()
        )
          break;
        this.acceptingSteering = false;
        this.retainPendingSteering();
        this.autonomousExecution = false;
        this.clearAgentActivity();
        this.reportMutationTermination();
        this.emit({
          type: "agent_end",
          messageIds: [],
        });
        break;
      default:
        break;
    }
  }

  /**
   * The recovery guard stops the agent loop by terminating the tool batch, so
   * the turn would otherwise end on a failed tool card with nothing said. Give
   * it the same visible, retriable error row an empty response gets: the user
   * learns the agent stopped on purpose, and the UI keeps its continue
   * affordance (spec 18-line-anchored-edit-contract §9.3).
   */
  private reportMutationTermination(): void {
    const termination = this.pendingMutationTermination;
    if (!termination) return;
    this.pendingMutationTermination = undefined;
    const recovery = mutationTerminationAdvice(
      termination.kind,
      termination.lastErrorCode,
    );
    const message = mutationTerminationMessage(
      termination.kind,
      termination.target,
      termination.lastErrorCode,
    );
    const error = {
      code: "MUTATION_RETRY_BUDGET_EXHAUSTED",
      message,
      retriable: true,
      details: {
        kind: termination.kind,
        ...(termination.lastErrorCode
          ? { lastErrorCode: termination.lastErrorCode }
          : {}),
        recovery,
      },
    };
    this.terminateParentTurn();
    this.finalizeCurrentAssistant("error", error);
    this.emit({ type: "error", error });
  }

  /** Resolve a bubble left in "streaming" when the run dies without a
   * message_end (rejected prompt), so the transcript never sticks mid-stream. */
  private finalizeCurrentAssistant(
    status: "error" | "aborted",
    error?: ReturnType<typeof classifyAgentError>,
  ) {
    if (!this.currentAssistant) {
      if (status !== "error" || !error) return;
      this.currentAssistant = {
        id: randomUUID(),
        role: "assistant",
        content: "",
        createdAt: nowIso(),
        status,
        modelId: this.provider.modelId,
        providerId: this.provider.id,
        error,
        isError: true,
      };
      this.emit({ type: "message_start", message: this.currentAssistant });
    } else {
      const responseDurationMs =
        this.streamStartedAt !== undefined
          ? Math.max(0, Date.now() - this.streamStartedAt)
          : undefined;
      const modelStreamDurationMs =
        (this.currentAssistant.modelStreamDurationMs ?? 0) +
        (responseDurationMs ?? 0);
      const responseOutputTokens =
        status === "aborted"
          ? estimateVisibleResponseOutputTokens({
              content: this.liveCommentary?.text ?? this.currentAssistant.content,
              thinking: this.currentAssistant.thinking,
            })
          : undefined;
      this.currentAssistant = {
        ...this.currentAssistant,
        status,
        ...(responseDurationMs !== undefined ? { responseDurationMs } : {}),
        ...(responseDurationMs !== undefined
          ? { modelStreamDurationMs }
          : {}),
        ...(responseOutputTokens !== undefined
          ? { responseOutputTokens }
          : {}),
        ...(error ? { error, isError: true } : {}),
      };
    }
    this.emit({ type: "message_end", message: this.currentAssistant });
    // The failure path is where a slow turn matters most: a provider that
    // burns its retries before giving up shows here as a large providerWaitMs.
    this.streamStartedAt = undefined;
    this.currentAssistant = undefined;
    this.liveCommentary = undefined;
  }

  /** Keep a pre-flight user message in context so a reused runtime and the
   * next turn both see it, even though no provider request was made. */
  private keepPreflightUserMessage(incomingUserMessage: AgentMessage): void {
    const userMessageId = this.pendingUserMessageId || randomUUID();
    this.pendingUserMessageId = undefined;
    this.appendLiveEntry(userMessageId, incomingUserMessage);
    this.setAgentMessages(this.liveSessionContext().messages);
  }
  private failCurrentPreflight(
    error: ReturnType<typeof classifyAgentError>,
  ): void {
    this.terminateParentTurn();
    this.finalizeCurrentAssistant("error", error);
    this.emit({ type: "error", error });
  }

  private failBeforeProviderRequest(
    incomingUserMessage: AgentMessage | undefined,
    error: ReturnType<typeof classifyAgentError>,
  ): void {
    if (incomingUserMessage) this.keepPreflightUserMessage(incomingUserMessage);
    this.failCurrentPreflight(error);
  }

  /**
   * Start execution for a host-approved plan without creating a visible user
   * turn. pi-agent-core needs a user message before `continue()`, so the
   * instruction is appended only to this runtime's in-memory context. Main
   * never receives a user event for it and therefore cannot persist or render
   * it as a transcript row.
   */
  async executeApprovedPlan(
    execution: PlanExecution,
    durableTurnId: string,
  ): Promise<{ turnId: string }> {
    if (this.disposed) throw new Error("runtime disposed");
    this.assertNotRunning();
    this.retainPendingSteering();
    if (execution.sessionId !== this.sessionId) {
      throw Object.assign(new Error("approved plan belongs to another session"), {
        errorCode: "PLAN_EXECUTION_NOT_FOUND",
      });
    }
    if (!durableTurnId.trim()) {
      throw Object.assign(new Error("execution turn id required"), {
        errorCode: "TURN_NOT_FOUND",
      });
    }
    return this.trackTurnOperation(durableTurnId, () =>
      this.executeApprovedPlanTurn(execution, durableTurnId),
    );
  }

  private async executeApprovedPlanTurn(
    execution: PlanExecution,
    durableTurnId: string,
  ): Promise<{ turnId: string }> {
    // Keep every new user turn small. A capability loaded for the preceding
    // turn can be searched again when the new task actually needs it.
    this.subagentOverrideProviders = {};
    this.resetDeferredToolsForPrompt();
    // Claims are message-scoped: a later prompt must observe edited or newly
    // created instruction files instead of reusing a previous chain.
    this.pathInstructionClaims.clear();
    this.turnId = durableTurnId;
    this.acceptingSteering = true;
    this.pendingUserMessageId = undefined;
    this.delegationPrompt = undefined;
    this.gracefulStopRequested = false;
    this.runCancelled = false;
    this.resetRunRecoveryState();
    this.turnEpoch += 1;
    this.abortDelegationsFromPreviousTurns();
    this.currentAssistant = undefined;
    this.liveCommentary = undefined;
    this.requestStartedAt = Date.now();
    // An approved plan runs as a plain Agent turn, never as a mode run turn.
    this.modeState.clearTurn();
    this.setMode("agent");
    this.autonomousExecution = true;

    const kind = execution.kind === "goal" ? "goal" : "plan";
    const instruction =
      kind === "goal"
        ? [
            "The user approved the goal contract below. Reach that goal now, autonomously.",
            `Use the host-created goal artifact at the workspace-relative path: ${execution.artifact.relativePath}`,
            `Approved goal title: ${execution.title}`,
            `Approval question: ${execution.question}`,
            "Treat the following Markdown as the exact approved contract. Do not renegotiate it, replace it with a new contract, or ask for approval again.",
            "<approved-goal-markdown>",
            execution.plan,
            "</approved-goal-markdown>",
            "Choose your own approach with the normal Agent tools. Then verify every acceptance criterion yourself, running the checks the contract names rather than assuming they pass.",
            "Keep working while a criterion is still unmet and you have an untried approach. Stop early only if a boundary in the contract blocks you or a criterion cannot be verified; say which one and why.",
            "Finish with a report that walks the acceptance criteria one by one, each marked met or unmet with the evidence you observed.",
          ].join("\n")
        : [
            "Execute the approved implementation plan now.",
            `Use the host-created plan artifact at the workspace-relative path: ${execution.artifact.relativePath}`,
            `Approved plan title: ${execution.title}`,
            `Approval question: ${execution.question}`,
            "Treat the following Markdown as the exact approved snapshot. Do not replace it with a new plan or ask for approval again.",
            "<approved-plan-markdown>",
            execution.plan,
            "</approved-plan-markdown>",
            "Implement the approved plan with the normal Agent tools, then report the result.",
          ].join("\n");
    const internalId = `approved-${kind}:${execution.id}`;
    const internalMessage: AgentMessage = {
      role: "user",
      content: instruction,
      timestamp: Date.now(),
    };
    this.appendLiveEntry(internalId, internalMessage);
    this.setAgentActivity({ phase: "starting", since: Date.now() });
    this.setAgentMessages(this.liveSessionContext().messages);
    if (this.automaticCompactionNeeded()) {
      const compacted = await this.runCompaction(
        "threshold",
        false,
        "active_turn",
      );
      if (!compacted) {
        if (this.compactionAborted) {
          this.terminateParentTurn();
          this.finalizeCurrentAssistant("aborted");
          return { turnId: this.turnId };
        }
        if (this.automaticCompactionWouldExceedHardLimit()) {
          this.failCurrentPreflight({
            code: "CONTEXT_COMPACTION_FAILED",
            message:
              "Automatic context compaction failed before approved plan execution",
            retriable: false,
          });
          return { turnId: this.turnId };
        }
      }
    }
    if (this.automaticCompactionWouldExceedHardLimit()) {
      this.failCurrentPreflight({
        code: "CONTEXT_TOO_LARGE",
        message:
          "The approved plan still exceeds the safe model context budget after compaction",
        retriable: false,
      });
      return { turnId: this.turnId };
    }
    await this.agent.continue();
    await this.waitForIdleAndSteering();
    // Same recovery contract as a user prompt: a plan execution that overflows,
    // hits a retriable stream failure, or comes back silent must not end as a
    // run with no end events at all.
    if (!(await this.runPendingRecoveries())) return { turnId: this.turnId };
    if (this.turnHadError) {
      this.terminateParentTurn();
      return { turnId: this.turnId };
    }
    await this.resumeAfterDelegations();
    return { turnId: this.turnId };
  }

  async prompt(
    input: string | RuntimePrompt,
    userMessageId?: string,
    durableTurnId?: string,
  ): Promise<{ turnId: string }> {
    if (this.disposed) throw new Error("runtime disposed");
    this.assertNotRunning();
    const turnId = durableTurnId?.trim() || randomUUID();
    return this.trackTurnOperation(turnId, async () => {
      try { return await this.promptTurn(input, userMessageId, turnId); }
      finally {
        // The run claim belongs to this turn only.
        this.modeState.endTurn();
        await this.batchPlanner.drain();
      }
    });
  }

  /** Execute the ordinary Host Read for explicit composer references before model input. */
  async resolveFileLineReferences(input: RuntimePrompt): Promise<RuntimePrompt> {
    if (!input.attachments?.some(attachment => attachment.lineRange !== undefined)) return input;
    const references = input.attachments.filter(attachment => attachment.lineRange !== undefined);
    if (references.length > MAX_FILE_LINE_REFERENCES) {
      throw Object.assign(new Error("Too many file line references"), { errorCode: "INVALID_ARGUMENT" });
    }
    if (references.some(attachment => attachment.kind !== "file" || attachment.localReference !== undefined || !parseFileLineRange(attachment.lineRange))) {
      throw Object.assign(new Error("Invalid file line reference"), { errorCode: "INVALID_ARGUMENT" });
    }
    const read = this.activeTools().find(tool => tool.name === "Read" && this.builtinTools.has(tool));
    const turnId = this.turnId;
    const attachments: RuntimePromptAttachment[] = [];
    const seen = new Set<string>();
    for (const attachment of input.attachments) {
      if (attachment.lineRange === undefined) {
        attachments.push(attachment);
        continue;
      }
      const range = parseFileLineRange(attachment.lineRange)!;
      const key = JSON.stringify([attachment.path, range.start, range.end]);
      if (seen.has(key)) continue;
      seen.add(key);
      if (this.runCancelled || this.disposed || turnId !== this.turnId) throw turnAbortedError("Turn ended during file reference reads");
      const args = {
        path: attachment.path,
        offset: range.start - 1,
        limit: range.end - range.start + 1,
      };
      const toolCall = { type: "toolCall" as const, id: randomUUID(), name: "Read", arguments: args };
      const timestamp = Date.now();
      const tools = read ? [read] : [];
      const prefetch = { blocked: !read };
      this.fileLineReadCalls.set(toolCall.id, prefetch);
      const { result, isError } = await runToolCall(toolCall, {
        tools,
        assistantMessage: {
          role: "assistant", content: [toolCall], api: this.model.api, provider: this.model.provider,
          model: this.model.id, usage: usageToPi(undefined), stopReason: "toolUse", timestamp,
        },
        context: { messages: this.agent.state.messages, tools },
        beforeToolCall: async context => {
          const decision = await this.beforeToolCall(context);
          if (decision?.block) prefetch.blocked = true;
          return decision;
        },
        afterToolCall: context => this.afterToolCall(context),
      }).finally(() => this.fileLineReadCalls.delete(toolCall.id));
      const text = result.content.flatMap(part => part.type === "text" ? [part.text] : []).join("\n");
      if (this.runCancelled || this.disposed || turnId !== this.turnId) throw turnAbortedError("Turn ended during file reference reads");
      attachments.push({
        ...attachment, lineRange: range, text,
        fileReferenceError: isError ? (prefetch.blocked ? "blocked" : "failed") : undefined,
      });
    }
    return { ...input, attachments };
  }

  private async promptTurn(
    input: string | RuntimePrompt,
    userMessageId: string | undefined,
    durableTurnId: string,
  ): Promise<{ turnId: string }> {
    const selectedTools = this.selectedMcpTools(input);
    let modelInput = typeof input !== "string" && input.sessionMessage
      ? { ...input, text: formatSessionMessage(input.text, input.sessionMessage), sessionMessage: undefined }
      : input;
    this.retainPendingSteering();
    const nextTurnId = durableTurnId;
    this.turnId = nextTurnId;
    this.acceptingSteering = true;
    this.gracefulStopRequested = false;
    this.runCancelled = false;
    this.turnSubagentUsage = undefined;
    // Capabilities and path-scoped instruction claims belong to one prompt.
    this.subagentOverrideProviders = {};
    this.pathInstructionClaims.clear();
    this.pendingUserMessageId = userMessageId;
    this.delegationPrompt = undefined;
    if (typeof input === "string") {
      const prompt = literalDelegationUserPrompt(input, this.subagents.map((role) => role.name));
      this.delegationPrompt = () => Promise.resolve(prompt);
    } else if (userMessageId && !input.sessionMessage) {
      let source: Promise<DelegationUserPrompt | undefined> | undefined;
      this.delegationPrompt = () => source ??= readDelegationUserPrompt(this.host, this.sessionId, userMessageId);
    }
    this.resetRunRecoveryState();
    this.autonomousExecution = false;
    const recovered = recoverMalformedToolCalls(this.agent.state.messages);
    if (recovered !== this.agent.state.messages) this.setAgentMessages(recovered);
    // Main resolves this provenance from the Host ledger. Never infer it from
    // prompt text, model output, extension content, or restored history.
    const origin = typeof input === "string" ? undefined : input.sessionMessage;
    this.allowSilentCompletion = origin?.kind === "completion" &&
      origin.targetSessionId === this.sessionId &&
      Boolean(origin.messageId?.trim() && origin.replyToMessageId?.trim());
    this.turnEpoch += 1;
    this.abortDelegationsFromPreviousTurns();
    this.requestStartedAt = Date.now();
    this.setAgentActivity({ phase: "starting", since: Date.now() });
    try {
      // Publish turn ownership before the first await. Status polling and Stop
      // must include capability negotiation, not observe a falsely idle turn.
      await this.batchPlanner.negotiate(Boolean(this.remoteWorkspace));
      if (this.runCancelled || this.disposed) throw turnAbortedError("Turn aborted during Host capability negotiation");
      // The run context decides this turn's policy level, CompleteStage and
      // the stage brief, so it is applied before the tools are rebuilt.
      const modeTurn = typeof input === "string" ? undefined : input.modeTurn;
      const modePromptChanged = await this.modeState.beginTurn(modeTurn, this.modeArtifactReader());
      if (this.runCancelled || this.disposed) throw turnAbortedError("Turn aborted while reading the mode run context");
      this.rebuildToolCatalog();
      this.resetDeferredToolsForPrompt();
      if (selectedTools.length) this.activateDeferredTools(selectedTools);
      this.setAgentTools(this.activeTools());
      if (modePromptChanged) this.setAgentSystemPrompt(this.composeSystemPrompt());
      const completion = typeof input === "string" ? undefined : input.backgroundCompletion;
      const completionEntries = completion ? this.historyToEntries([completion]) : [];
      if (typeof modelInput !== "string" && modelInput.attachments?.some(attachment => attachment.lineRange !== undefined)) {
        modelInput = await this.resolveFileLineReferences(modelInput);
      }
      const content = promptContent(modelInput);
      const incomingUserMessage: AgentMessage = {
        role: "user",
        content,
        timestamp: Date.now(),
      };
      const incomingMessages = completion ? completionEntries.map(entry => entry.message) : [incomingUserMessage];
      if (this.automaticCompactionNeeded(incomingMessages)) {
        const compacted = await this.runCompaction("threshold", false);
        if (!compacted) {
          if (this.compactionAborted) {
            // Stop landed during the pre-flight checkpoint. Keep the user's
            // message in context and end the turn as aborted, the same way a
            // stop during the provider request ends it (the catch below).
            if (!completion) this.keepPreflightUserMessage(incomingUserMessage);
            throw turnAbortedError("Turn aborted while compacting context");
          }
          // A soft-trigger summary failure is recoverable while the hard
          // provider budget still has room; retain the hard guard below.
          if (this.automaticCompactionWouldExceedHardLimit(incomingMessages)) {
            this.failBeforeProviderRequest(completion ? undefined : incomingUserMessage, {
              code: "CONTEXT_COMPACTION_FAILED",
              message: "Automatic context compaction failed before the model request",
              retriable: false,
            });
            return { turnId: this.turnId };
          }
        } else if (this.automaticCompactionWouldExceedHardLimit(incomingMessages)) {
          this.failBeforeProviderRequest(completion ? undefined : incomingUserMessage, {
            code: "CONTEXT_TOO_LARGE",
            message:
              "The pending prompt still exceeds the safe model context budget after compaction",
            retriable: false,
          });
          return { turnId: this.turnId };
        }
      }
      if (
        !this.compactionEnabled &&
        this.automaticCompactionWouldExceedHardLimit(incomingMessages)
      ) {
        this.failBeforeProviderRequest(completion ? undefined : incomingUserMessage, {
          code: "CONTEXT_TOO_LARGE",
          message:
            "The pending prompt exceeds the safe model context budget while automatic compaction is disabled",
          retriable: false,
        });
        return { turnId: this.turnId };
      }
      await this.extensionBeforeAgentStart(modelInput);
      if (this.runCancelled || this.disposed) {
        if (!completion) this.keepPreflightUserMessage(incomingUserMessage);
        throw turnAbortedError("Turn aborted during extension hooks");
      }
      if (completion) {
        for (const entry of completionEntries) this.appendLiveEntry(entry.id, entry.message);
        this.setAgentMessages([...this.agent.state.messages, ...incomingMessages]);
        await this.agent.continue();
      } else if (typeof modelInput === "string") {
        await this.agent.prompt(modelInput);
      } else {
        // pi's `(text, images)` form appends every image after the text; the
        // message form keeps an inline image block where the user placed it,
        // which is the same content `promptContent` already built above.
        await this.agent.prompt(incomingUserMessage);
      }
      await this.waitForIdleAndSteering();
      void this.extensionRunner?.emit("agent_settled", { type: "agent_settled" });

      if (!(await this.runPendingRecoveries())) return { turnId: this.turnId };
      if (this.turnHadError) {
        this.terminateParentTurn();
        return { turnId: this.turnId };
      }
      await this.resumeAfterDelegations();
    } catch (err) {
      const classifiedError = classifyAgentError(err);
      const diagnosticError =
        classifiedError.code === "TURN_ABORTED"
          ? classifiedError
          : this.providerErrorWithDiagnostics(
              classifiedError,
              "request",
              this.requestStartedAt !== undefined
                ? Math.max(0, Date.now() - this.requestStartedAt)
                : undefined,
            );
      this.terminateParentTurn();
      this.finalizeCurrentAssistant(
        classifiedError.code === "TURN_ABORTED" ? "aborted" : "error",
        classifiedError.code === "TURN_ABORTED" ? undefined : diagnosticError,
      );
      if (classifiedError.code === "TURN_ABORTED") throw err;
      throw Object.assign(new Error(diagnosticError.message), diagnosticError);
    }
    return { turnId: this.turnId };
  }

  private async extensionBeforeAgentStart(input: string | RuntimePrompt): Promise<void> {
    const runner = this.extensionRunner;
    if (!runner) return;
    this.extensionProviderHeaders = undefined;
    if (runner.hasHandlers("before_provider_headers")) {
      // Handlers edit the headers object in place, as they do in the pi CLI.
      const headers: Record<string, string> = { ...(this.provider.headers ?? {}) };
      await runner.emit("before_provider_headers", { type: "before_provider_headers", headers });
      if (this.runCancelled || this.disposed) return;
      this.extensionProviderHeaders = { ...headers };
    }
    if (!runner.hasHandlers("before_agent_start")) return;
    const base = this.composeSystemPrompt();
    const prompt = await runner.emitBeforeAgentStart(
      typeof input === "string" ? input : input.text,
      base,
    );
    this.setAgentSystemPrompt(prompt ?? base);
  }
  /**
   * `before_provider_request` rides pi-ai's `onPayload`, `after_provider_response`
   * its `onResponse`, and the per-turn `before_provider_headers` result merges
   * into the request headers (spec 16 §6).
   */
  private withExtensionProviderHooks(
    options: SimpleStreamOptions,
    model: Model<any>,
  ): SimpleStreamOptions {
    const runner = this.extensionRunner;
    if (!runner) return options;
    const next: SimpleStreamOptions = { ...options };
    // Notification handlers can finish out of order; this local id never leaves the process.
    const contextRequestId = ++this.extensionProviderRequestId;
    if (this.extensionProviderHeaders) {
      next.headers = mergeProviderHeaders(options.headers, this.extensionProviderHeaders);
    }
    if (runner.hasHandlers("before_provider_request")) {
      next.onPayload = async (payload, payloadModel) => {
        const base = await options.onPayload?.(payload, payloadModel);
        const current = base ?? payload;
        const replaced = await runner.emitBeforeProviderRequest(current, { contextRequestId });
        return replaced ?? base;
      };
    }
    if (runner.hasHandlers("after_provider_response")) {
      next.onResponse = async (response, responseModel) => {
        await options.onResponse?.(response, responseModel);
        void runner.emit("after_provider_response", {
          type: "after_provider_response",
          contextRequestId,
          response,
          model: model as unknown,
        });
      };
    }
    return next;
  }

  /**
   * Same rejection the sidecar gives a second `agent.prompt` while a turn is
   * active, raised before any turn state is touched. pi's own busy check
   * would throw later, after `turnId`/`turnEpoch` had already moved on, and
   * that throw finalized the running assistant message as an error.
   */
  private assertNotRunning(): void {
    if (!this.getStatus().isRunning) return;
    throw Object.assign(new Error("session already has an active turn"), {
      rpcCode: -32000,
      errorCode: "AGENT_BUSY",
    });
  }

  /** Resolve attachments against the configuration of the running turn. */
  steeringContext(expectedTurnId: string): { projectPath?: string; remoteWorkspace?: { hostKey: string; path: string }; supportsVision: boolean } {
    if (
      this.disposed || !this.acceptingSteering || this.runCancelled ||
      this.turnHadError || !this.getStatus().isRunning ||
      !expectedTurnId || expectedTurnId !== this.turnId ||
      this.planningState === "awaiting_approval"
    ) {
      throw Object.assign(new Error("The target turn is no longer accepting input"), {
        errorCode: "TURN_NOT_FOUND",
      });
    }
    return { projectPath: this.projectPath, ...(this.remoteWorkspace ? { remoteWorkspace: this.remoteWorkspace } : {}), supportsVision: this.model.input.includes("image") };
  }

  steer(input: RuntimePrompt, expectedTurnId: string, message: UiMessage): { accepted: boolean; turnId: string } {
    this.steeringContext(expectedTurnId);
    const queued: AgentMessage = { role: "user", content: promptContent(input), timestamp: Date.now() };
    const toolNames = this.selectedMcpTools(input);
    this.pendingSteering.set(queued, { id: message.id, toolNames, delegationPrompt: delegationUserPrompt(message) });
    this.agent.steer(queued);
    this.steeringWaitAbort?.abort();
    for (const abortTool of this.steeringToolAborts.values()) abortTool();
    if ([...this.activeToolCalls.values()].some((call) => call.toolName !== SUBAGENT_WAIT_TOOL_NAME)) {
      this.setAgentActivity({ phase: "waiting-tool-stop", since: Date.now() });
    }
    // Main persists this echo through the same outbox as assistant messages.
    this.emit({ type: "message_start", message });
    this.emit({
      type: "message_end", message,
      ...(this.currentAssistant?.status === "streaming"
        ? { precedingAssistant: { ...this.currentAssistant } } : {}),
    });
    return { accepted: true, turnId: this.turnId! };
  }

  private retainPendingSteering(): void {
    this.agent.clearSteeringQueue();
    for (const [message, pending] of this.pendingSteering) {
      if (!this.agent.state.messages.includes(message)) this.setAgentMessages([...this.agent.state.messages, message]);
      this.appendLiveEntry(pending.id, message);
    }
    this.pendingSteering.clear();

  }
  private async waitForIdleAndSteering(): Promise<void> {
    await this.agent.waitForIdle();
    if (!this.acceptingSteering || this.runCancelled || this.turnHadError) {
      this.retainPendingSteering();
      return;
    }
    // Recovery owns the next request when the previous response failed. Its
    // continuation will consume steering after repairing the context/backoff.
    if (this.suppressOverflowRunEnd || this.suppressProviderRetryRunEnd ||
        this.suppressSilentTurnRunEnd || this.suppressProgressTurnRunEnd) return;
    while (this.pendingSteering.size && this.acceptingSteering && !this.runCancelled && !this.turnHadError) {
      this.steeringContinuation = true;
      try {
        await this.agent.continue();
        await this.agent.waitForIdle();
        // The steering continuation may itself finish with a recoverable
        // provider/silent/overflow/progress failure. Let runPendingRecoveries
        // repair that assistant tail before another steering continuation.
        if (
          this.suppressOverflowRunEnd ||
          this.suppressProviderRetryRunEnd ||
          this.suppressSilentTurnRunEnd ||
          this.suppressProgressTurnRunEnd
        ) return;
      } finally {
        this.steeringContinuation = false;
      }
    }
  }

  abort(): Promise<void> {
    return this.aborting ??= this.abortTurn().finally(() => { this.aborting = undefined; });
  }

  private async abortTurn(): Promise<void> {
    const turnId = this.turnId;
    const settlement = turnId
      ? this.activeTurnSettlements.get(turnId)
      : undefined;
    const delegates = this.runningDelegations().map((record) => record.completion);
    this.acceptingSteering = false;
    this.gracefulStopRequested = false;
    this.runCancelled = true;
    this.steeringWaitAbort?.abort();
    this.extensionRunner?.cancelPending();
    this.resolvePendingAskTools();
    this.abortRunningDelegations();
    this.turnSubagentUsage = undefined;
    this.agent.abort();
    this.providerRetryAbort?.abort();
    if (this.compactionInProgress) this.compactionAborted = true;
    this.compactionAbort?.abort();
    // `agent.abort()` normally fires the signal each in-flight tool was handed,
    // and the tool executor reacts to that. When the signal does not reach a
    // tool, the executor keeps awaiting `tools.execute`, the turn never
    // settles, and this method never returns. The renderer awaits this RPC
    // before it clears the "processing" state, so one unyielding tool pinned
    // the whole session until it finished on its own (#1767). Drive the tools
    // from here as well, so a stop always releases them.
    for (const abortTool of [...this.activeToolAborts]) abortTool();
    await Promise.allSettled([...(settlement ? [settlement] : []), ...delegates]);
  }

  private trackTurnOperation<T>(
    turnId: string,
    operation: () => Promise<T>,
  ): Promise<T> {
    let settle!: () => void;
    const settlement = new Promise<void>((resolve) => {
      settle = resolve;
    });
    this.activeTurnSettlements.set(turnId, settlement);
    let result: Promise<T>;
    try {
      result = operation();
    } catch (error) {
      if (this.activeTurnSettlements.get(turnId) === settlement) {
        this.activeTurnSettlements.delete(turnId);
      }
      settle();
      throw error;
    }
    return result.finally(() => {
      if (this.activeTurnSettlements.get(turnId) === settlement) {
        this.activeTurnSettlements.delete(turnId);
      }
      settle();
    });
  }

  /**
   * Electron main reports that the run this turn works on changed (ADR
   * mode-definitions): `closeout` after the user paused it, `release` after
   * the user removed it. A notice for another turn or run is ignored.
   */
  modeTurnNotice(notice: ModeTurnNoticeParams): { applied: boolean } {
    if (this.disposed || !this.turnId || notice.turnId !== this.turnId) return { applied: false };
    if (this.modeState.activeTurn?.runId !== notice.runId) return { applied: false };
    if (notice.action === "closeout") {
      if (!this.modeState.beginCloseout(notice.runId)) return { applied: false };
      this.setAgentSystemPrompt(this.composeSystemPrompt());
      return { applied: true };
    }
    // The turn finishes as an ordinary turn of the mode the session returned
    // to; CompleteStage and the stage brief leave with the run context.
    this.modeState.clearTurn();
    this.setMode(notice.mode, notice.modeDefinition);
    this.rebuildToolCatalog();
    this.setAgentSystemPrompt(this.composeSystemPrompt());
    this.setAgentTools(this.activeTools());
    return { applied: true };
  }

  /** Ask pi-agent-core to stop after the current assistant/tool turn. */
  requestGracefulStop(): { requested: boolean } {
    if (this.disposed || !this.agent.state.isStreaming) {
      return { requested: false };
    }
    this.acceptingSteering = false;
    this.gracefulStopRequested = true;
    return { requested: true };
  }

  getStatus(): AgentStatus {
    return {
      sessionId: this.sessionId,
      isRunning:
        this.aborting !== undefined ||
        this.agent.state.isStreaming ||
        this.compactionInProgress ||
        this.agentActivity !== undefined ||
        (!this.turnHadError && !this.runCancelled && this.runningDelegations().length > 0),
      currentTurnId: this.turnId,
      modelId: this.provider.modelId,
      pendingToolConfirmations: 0,
      planningState: this.planningState,
      ...(this.pendingPlanId ? { pendingPlanId: this.pendingPlanId } : {}),
      ...(this.agentActivity ? { activity: this.agentActivity } : {}),
    };
  }

  async dispose(): Promise<void> {
    if (this.disposed) return;
    const runner = this.extensionRunner;
    this.extensionRunner = undefined;
    const closingExtensions = runner?.dispose();
    this.streamSink.dispose();
    this.disposed = true;
    this.acceptingSteering = false;
    this.runCancelled = true;
    this.steeringWaitAbort?.abort();
    this.resolvePendingAskTools();
    this.abortRunningDelegations();
    this.delegationWaitTargets = undefined;
    this.pathInstructionClaims.clear();
    this.failedHostToolCalls.clear();
    this.mutationFailureCounts.clear();
    this.mutationRecoveryGraces.clear();
    this.delegateMutationTerminations.clear();
    this.pendingMutationTermination = undefined;
    this.terminatingToolCalls.clear();
    this.delegateToolCalls.clear();
    this.bashYieldCalls.clear();
    this.appendedDelegationRowIds.clear();
    this.gracefulStopRequested = false;
    this.hostCloseUnsubscribe?.();
    this.hostCloseUnsubscribe = undefined;
    this.agent.abort();
    this.providerRetryAbort?.abort();
    this.cleanupActiveToolProgress();
    if (this.compactionInProgress) this.compactionAborted = true;
    this.compactionAbort?.abort();
    await closingExtensions;
    // Release pi-ai's per-session provider state (Anthropic message-thread
    // continuation, strict-tool downgrades) once nothing can send for it.
    cleanupSessionResources(this.sessionId);
  }
}