UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

2,746 lines • 139 kB
/**
 * AgentSession - Core abstraction for agent lifecycle and session management.
 *
 * This class is shared between all run modes (interactive, print, rpc).
 * It encapsulates:
 * - Agent state access
 * - Event subscription with automatic session persistence
 * - Model and thinking level management
 * - Compaction (manual and auto)
 * - Bash execution
 * - Session switching and branching
 *
 * Modes use this class and add their own I/O layer on top.
 */
import type { Agent, AgentEvent, AgentMessage, AgentState, AgentTool, AgentToolCall, AgentToolResult, InternalAgentChannel, ThinkingLevel } from "@earendil-works/pi-agent-core";
import { type ThinkingSelection } from "@earendil-works/pi-ai";
import type { Api, ImageContent, Model, TextContent } from "@earendil-works/pi-ai/compat";
import type { ToolRuntimeKind } from "../cli/tool-runtime.ts";
import { type SessionToolChildRow } from "../modes/rpc/tool-child/session-child.ts";
import { type AgentAbortSource } from "./agent-abort-provenance.ts";
import { DeferredTurnClaim } from "./agent-settled-delivery.ts";
import type { CredentialReplacement } from "./auth-storage.ts";
import { type BashResult } from "./bash-executor.ts";
import { type SessionClosedRecord } from "./session-closed.ts";
import type { BrowserEngine } from "./browser-engine.ts";
import { type ClientMessageIdentity, type PreparedClientInput } from "./client-message-identity.ts";
import { type CompactionResult } from "./compaction/index.ts";
import { type CompactionLifecycleState } from "./compaction/lifecycle.ts";
import { type PromptSurface } from "./dynamic-prompt/index.ts";
import { type SessionHoldEvent } from "./engine-turn-hold.ts";
import { type ModelUsabilityAdmission, type ModelUsabilityBudgetProjection } from "./extensions/builtin/compaction/model-usability-budget.ts";
import { type ResumeSlicePlan } from "./extensions/builtin/compaction/resume-slice.ts";
import { type PendingModelSwitch } from "./extensions/builtin/compaction/switch-admission.ts";
import { type ServiceTier } from "./extensions/builtin/service-tier.ts";
import { type ContextUsage, type ExecuteToolOptions, type ToolCallEventResult, type ExtensionCommandContextActions, type ExtensionContext, type ExtensionErrorListener, type ExtensionMode, type ExtensionRunner, type ExtensionToolHookLifecycleEvent, type ExtensionUIContext, type InputSource, type ReplacedSessionContext, type SessionStartEvent, type ShutdownHandler, type SystemPromptChangeEvent, type ToolDefinition, type ToolInfo } from "./extensions/index.ts";
import type { ApplyCompactionOptions, ApplyCompactionResult, CompactionReason, CompactionRejectionCause, ModelSelectSource } from "./extensions/types.ts";
import { type UserActivityKind } from "./extensions/user-activity.ts";
import { ExternalAdmission } from "./external-admission.ts";
import { type HoldInputResult } from "./held-inputs.ts";
import { type InputOrigin } from "./input-origin.ts";
import { type ConnectionOrigin } from "./turn-origin.ts";
import { type ItemizedAdmission } from "./itemized-send.ts";
import { type CustomMessage } from "./messages.ts";
import { type ModelChangeOrigin } from "./model-change-origin.ts";
import { ModelRegistry } from "./model-registry.ts";
import type { ModelRuntime } from "./model-runtime.ts";
import { type PendingInputSnapshot, type PendingInputUpdate } from "./pending-input-session.ts";
import type { PromptSizeInventory } from "./prompt-size-startup.ts";
import { type PromptTemplate } from "./prompt-templates.ts";
import { type ProviderFailure } from "./provider-failure.ts";
import type { ResourceLoader } from "./resource-loader.ts";
import { type FallbackRungRefusal } from "./retry-fallback/controller.ts";
import { type ModelConfigErrorEvent } from "./retry-fallback/model-config-error.ts";
import { type FallbackRungFailure } from "./retry-fallback/exhaustion.ts";
import { type RetryWait } from "./retry-wait.ts";
import { type RunBackgroundJob, type RunBackgroundStopOutcome } from "./run-background-jobs.ts";
import { type InheritResult, type ReleaseInheritedResult, type RunRef } from "./run-holds.ts";
import { SecurityNoticeSnapshot } from "./security-notices.ts";
import { type SessionActivitySnapshot } from "./session-activity.ts";
import { type ControlEndpointHost } from "./session-control-actions.ts";
import { type SessionFailureReport } from "./session-failure-report.ts";
import type { ChildLifecycleReport, LifecycleApi, SessionLifecycleEvent } from "./session-lifecycle-types.ts";
import type { BranchSummaryEntry, SessionEntry } from "./session-manager.ts";
import { SessionManager, type SessionRecoveryCause } from "./session-manager.ts";
import { type ThinkingLevelSource } from "./session-thinking-memory.ts";
import type { SessionRelocationHost } from "./session-relocation.ts";
import { type SettingsManager, type SettingsSourceSelection } from "./settings-manager.ts";
import { type SkillInvocationSyntax } from "./skill-invocation.ts";
import type { SourceInfo } from "./source-info.ts";
import { type AgentSessionStructuredRecord } from "./structured-session-lane.ts";
import { type ThinkingClampNotice } from "./thinking-levels.ts";
import { type ToolBarrierSpec } from "./tool-barrier.ts";
import { type SessionMessageUpdateEvent } from "./tool-call-display-name.ts";
import type { HostCallTarget, RegisteredHostCallKind } from "./tool-child-host-calls.ts";
import type { StuckModuleNotice } from "./tool-dispatch/in-process-module.ts";
import type { ToolDispatcher } from "./tool-dispatch/tool-dispatcher.ts";
import type { BashOperations } from "./tools/bash.ts";
import { type TurnDeadline, type TurnDeadlineWarning } from "./turn-deadline.ts";
/** The turn_end boundary report for a turn still unwinding after dispose() (senpi#2995). */
export declare const TURN_END_SKIPPED_AFTER_SHUTDOWN = "turn_end skipped: the session shut down during this turn, so its last response was not saved";
export { formatSkillInvocationPrompt, type ParsedSkillBlock, parseSkillBlock, parseSkillInvocationTokens, type SkillInvocationPromptSkill, type SkillInvocationSyntax, type SkillInvocationToken, } from "./skill-invocation.ts";
export interface CommandInvocation {
    name: string;
    source: "extension" | "prompt";
    sourceInfo: SourceInfo;
    syntax: "slash";
}
/** Tool execution events of calls a tool made through `ctx.executeTool()` carry `parentToolCallId`. */
type WithParentToolCallId<E> = E extends {
    type: "tool_execution_start" | "tool_execution_update" | "tool_execution_end";
} ? E & {
    parentToolCallId?: string;
} : E;
/** Why a session-level abort happened, when the caller knows: a session replacement, or the host process stopping. */
export type AgentAbortCause = {
    readonly kind: "session_replaced";
    /** What replaced the session: `new_session`, `fork` or a `switch_session`/resume. */
    readonly reason: "new" | "fork" | "resume";
    /** The replacement's transcript and durable session id, when they are known before the teardown. */
    readonly targetSessionFile?: string;
    readonly targetSessionId?: string;
} | {
    readonly kind: "host_shutdown";
};
type AgentSessionAgentEndEvent = Extract<AgentEvent, {
    type: "agent_end";
}> & {
    willRetry: boolean;
    aborted?: true;
    abortSource?: AgentAbortSource;
    /** Set when the turn's inactivity lease or hard max runtime ended it (see turn-deadline.ts). */
    deadline?: TurnDeadline;
    /** Present when the turn ended with a provider error; see provider-failure.ts. */
    failure?: ProviderFailure;
    /** Present when the run was aborted by an abort that named its cause (for example a session replacement). */
    abortCause?: AgentAbortCause;
};
/** Session-specific events that extend the core AgentEvent */
export type AgentSessionEvent = WithParentToolCallId<Exclude<AgentEvent, {
    type: "agent_start" | "agent_end" | "message_update";
}>>
/** The lifecycle run identity, bound before asynchronous event delivery; older engines omit it. */
 | {
    type: "agent_start";
    runId?: string;
} | AgentSessionAgentEndEvent | SessionMessageUpdateEvent | {
    type: "agent_settled";
} | {
    type: "agent_idle";
}
/** The session's tool child changed state (senpi#3566; the minimal record todo 14 extends). */
 | {
    type: "session_tool_child";
    state: "spawned" | "exited" | "respawned";
    generation: number;
    pid: number;
} | {
    type: "session_abort";
}
/** A workspace-writing tool call started waiting on the turn's tool barrier (senpi#3717). */
 | {
    type: "tool_barrier_waiting";
    id: string;
    toolCallId: string;
    toolName: string;
}
/** The tool barrier's ceiling passed before a release; it opened by itself (senpi#3717). */
 | {
    type: "tool_barrier_expired";
    id: string;
    deadlineMs: number;
} | SessionHoldEvent | SessionLifecycleEvent | {
    type: "resume_compaction_required";
    projection: ModelUsabilityBudgetProjection;
    notice: string;
} | {
    type: "resume_context_reduced";
    tokensBefore: number;
    tokensAfter: number;
    droppedEntries: number;
    notice: string;
}
/**
 * The session file's tail was torn by an interrupted write (a full disk) and was set aside in `backupPath`; every
 * complete record is kept (senpi#4295). Emitted live once, and replayed to each surface that attaches before the
 * next prompt, so the person is told once wherever they look.
 */
 | {
    type: "session_recovered";
    cause: SessionRecoveryCause;
    backupPath: string;
    droppedBytes: number;
    notice: string;
} | {
    type: "continuation_error";
    errorMessage: string;
}
/**
 * A background turn (an extension's `sendMessage` with `triggerTurn`, or `sendUserMessage`) could not start
 * because no provider is ready. Emitted once until a turn is admitted again, with the same guidance a typed
 * prompt gets, instead of an extension error.
 */
 | {
    type: "provider_required";
    notice: string;
}
/** The session file refused a message of the running turn; the message is not in the transcript. */
 | {
    type: "transcript_write_failed";
    role: AgentMessage["role"];
    errorMessage: string;
}
/**
 * An in-process `ctx.offload` module ran past its deadline and grace and cannot be stopped: it keeps its file locks,
 * every write waiting on them fails fast, and they are released when it finishes or the session is closed.
 */
 | ({
    type: "offload_module_stuck";
} & StuckModuleNotice) | {
    type: "skill_invocation";
    skills: readonly {
        name: string;
        path: string;
        syntax: SkillInvocationSyntax;
    }[];
} | {
    type: "command_invocation";
    command: CommandInvocation;
}
/** A pending input changed in durable custody (senpi#3549); `changes` are complete projections. */
 | ({
    type: "pending_input_update";
} & PendingInputUpdate) | {
    type: "queue_update";
    steering: readonly string[];
    followUp: readonly string[];
    ordered: readonly QueuedInput[];
} | {
    type: "compaction_start";
    reason: CompactionReason;
    requestId?: string;
} | {
    type: "compaction_progress";
    reason: CompactionReason;
    delta?: string;
    text?: string;
} | {
    type: "entry_appended";
    entry: SessionEntry;
} | {
    type: "session_info_changed";
    name: string | undefined;
} | ExtensionToolHookLifecycleEvent | SystemPromptChangeEvent | {
    type: "thinking_level_changed";
    level: ThinkingLevel;
} | {
    type: "high_reasoning_warning";
    modelId: string;
    provider: string;
    thinkingLevel: ThinkingLevel;
}
/** An explicit thinking request ran at a lower level than asked (senpi#2395); emitted once per model and level. */
 | ({
    type: "thinking_level_clamped";
} & ThinkingClampNotice) | ({
    type: "settings_source_selected";
} & SettingsSourceSelection)
/** Active model changed; `thinkingLevel` is the level in force AFTER the switch. */
 | {
    type: "model_changed";
    model: Model<any>;
    thinkingLevel: ThinkingLevel;
    source: ModelSelectSource;
    /** What made the switch and who issued it (senpi#2870). */
    origin: ModelChangeOrigin;
    /** The model active before the switch, when there was one. */
    previousModel?: Model<any>;
    /** The switch landed while a turn was streaming. */
    duringTurn: boolean;
}
/** A switch the session refused; recorded so the attempt survives (#1526). */
 | {
    type: "model_change_rejected";
    model: Model<any>;
    reason: "context-budget" | "auth";
    detail: string;
    contextWindow?: number;
    liveContextTokens?: number;
    requiredTokens?: number;
    shortfallTokens?: number;
    safetyMarginProfile?: string;
} | {
    type: "model_change_skipped";
    model: Model<any>;
    contextWindow: number;
    liveContextTokens: number;
    requiredTokens: number;
    shortfallTokens: number;
    safetyMarginProfile: string;
    direction: "forward" | "backward";
} | {
    type: "model_change_cancelled";
    origin: ModelChangeOrigin;
    reason: "superseded" | "context-budget" | "error";
    detail?: string;
}
/** A switch accepted but held until the next send can compact for it (#1873). */
 | {
    type: "model_change_pending";
    model: Model<any>;
    contextWindow: number;
    liveContextTokens: number;
    requiredTokens: number;
    shortfallTokens: number;
    notice: string;
}
/** Effective service tier or fast-mode state changed. */
 | {
    type: "service_tier_changed";
    tier?: ServiceTier;
    fastMode: boolean;
} | {
    type: "session_settings_changed";
    steeringMode: "all" | "one-at-a-time";
    followUpMode: "all" | "one-at-a-time";
    autoCompactionEnabled: boolean;
} | {
    type: "compaction_end";
    reason: CompactionReason;
    result: CompactionResult | undefined;
    aborted: boolean;
    willRetry: boolean;
    requestId?: string;
    accepted?: boolean;
    rejectionCause?: CompactionRejectionCause;
    errorMessage?: string;
} | {
    type: "auto_retry_start";
    attempt: number;
    maxAttempts: number;
    delayMs: number;
    errorMessage: string;
} | {
    type: "auto_retry_end";
    success: boolean;
    attempt: number;
    finalError?: string;
} | {
    type: "retry_fallback_applied";
    from: string;
    to: string;
    chainKey: string;
    reason: "transient" | "refusal" | "hard-error" | "billing";
    /** Set when a usage limit caused the switch: `model` binds one model, `account` the whole provider. */
    limit?: "model" | "account";
} | {
    type: "retry_fallback_succeeded";
    model: string;
    chainKey: string;
} | {
    /** A limit that named no model family was checked on another family once (senpi#5596). */
    type: "usage_limit_scope_probe";
    provider: string;
    heldFamily: string;
    probeFamily: string;
    outcome: "served" | "widened";
} | {
    type: "retry_fallback_reverted";
    from: string;
    to: string;
    /** `fallback-unusable`: the fallback could not serve (billing or an account limit), so the session returned early. */
    cause?: "fallback-unusable";
} | {
    type: "retry_fallback_exhausted";
    chainKey: string;
    /** The failure of the rung that ran last; kept for older clients. */
    lastError: string;
    /** The failure that started the fallback walk: the turn's first failed rung (senpi#4084). */
    primaryError?: FallbackRungFailure;
    /** Every rung that failed this turn, in the order it ran, the primary first. */
    failures?: FallbackRungFailure[];
    /** Rungs this turn's walk could not switch to (senpi#3447), each with the guard's reason and numbers. */
    refusals?: readonly FallbackRungRefusal[];
} | ModelConfigErrorEvent | {
    type: "server_fallback_aborted";
    from: string;
    to: string;
    chainConfigured: boolean;
} | {
    type: "auth_login_url";
    provider: string;
    url: string;
}
/**
 * A login progress line, such as a `provider_login_start` handler's download status (senpi#4436). The line is
 * `text`, not `message`: event consumers detect chat-message events with `"message" in event`.
 */
 | {
    type: "auth_login_progress";
    provider: string;
    text: string;
} | {
    type: "auth_login_end";
    provider: string;
    success: boolean;
    error?: string;
    /** A successful login that replaced a credential of the other kind names it (senpi#3486). */
    replaced?: CredentialReplacement["replaced"];
    /** Where the replaced credential was backed up, when it was. */
    backupPath?: string;
    /** The account a Claude CLI sign-in signed in (senpi#4436). */
    account?: {
        name: string;
    };
    /** That account's sign-in connection test. */
    check?: {
        model: string;
        outcome: "ok" | "failed";
        reason?: string;
        message?: string;
        status?: number;
        at: number;
    };
} | {
    type: "summarization_retry_scheduled";
    attempt: number;
    maxAttempts: number;
    delayMs: number;
    errorMessage: string;
} | {
    type: "summarization_retry_attempt_start";
    source: "branchSummary";
} | {
    type: "summarization_retry_attempt_start";
    source: "compaction";
    reason: CompactionReason;
} | {
    type: "summarization_retry_finished";
} | {
    type: "retry_probe_scheduled";
    selector: string;
    atMs: number;
    probeIndex: 1 | 2;
} | {
    type: "retry_probe_result";
    selector: string;
    ok: boolean;
    errorMessage?: string;
} | {
    type: "bash_execution_update";
    id?: string;
    delta: string;
};
/** Listener function for agent session events */
export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
export interface AgentSessionConfig {
    agent: Agent;
    /** @internal Construction channel for senpi's session layer only; absent for externally supplied Agents. */
    internalChannel?: InternalAgentChannel;
    /** Explicit service tier for the initial model. */
    serviceTier?: ServiceTier;
    sessionManager: SessionManager;
    settingsManager: SettingsManager;
    cwd: string;
    /** Directory containing runtime logs and global agent configuration. */
    agentDir?: string;
    /** Clock override for fallback selector cooldowns (tests only). */
    fallbackNow?: () => number;
    /** Wall clock used to translate provider reset timestamps into cooldown durations. */
    fallbackWallNow?: () => number;
    /** Random source for retry jitter (tests only). */
    retryRandom?: () => number;
    /**
     * Send cwd and date as an append-only environment-context message before a turn (senpi#2093).
     * Default true; test fixtures that pin exact transcripts pass false.
     */
    environmentContext?: boolean;
    /** Global model narrowing for selectors and startup model choice (from --models / enabledModels) */
    scopedModels?: Array<{
        model: Model<any>;
        thinkingLevel?: ThinkingLevel;
        thinkingSelection?: ThinkingSelection;
        serviceTier?: ServiceTier;
    }>;
    /** Favorite models to cycle through with Ctrl+P */
    favoriteModels?: Array<{
        model: Model<any>;
        thinkingLevel?: ThinkingLevel;
        thinkingSelection?: ThinkingSelection;
        serviceTier?: ServiceTier;
    }>;
    /** Resource loader for extensions, skills, prompts, themes, context files, and system prompt */
    resourceLoader: ResourceLoader;
    /** SDK custom tools registered outside extensions */
    customTools?: ToolDefinition[];
    /** Canonical model/auth runtime used by coding-agent internals. */
    modelRuntime?: ModelRuntime;
    /** Legacy model facade retained for extensions and SDK consumers. */
    modelRegistry?: ModelRegistry;
    /** Initial active built-in tool names. Default: [read, bash, edit, write] */
    initialActiveToolNames?: string[];
    /** Configured built-in defaults; fork-native builtin extension tools outside this set are omitted. */
    defaultToolNames?: string[];
    /**
     * Whether the initial tools come from the `defaultTools` setting. When true, reload activates
     * tools newly added to the setting. Tools removed from it stay active.
     */
    usesDefaultTools?: boolean;
    /** Tool names that remain executable only through the registered eval tool. */
    evalOnlyToolNames?: string[];
    /** Optional allowlist of tool names. When provided, only these tool names are exposed. */
    allowedToolNames?: string[];
    /** Optional denylist of tool names. When provided, these tool names are not exposed. */
    excludedToolNames?: string[];
    /**
     * Override base tools (useful for custom runtimes).
     *
     * These are synthesized into minimal ToolDefinitions internally so AgentSession can keep
     * a definition-first registry even when callers provide plain AgentTool instances.
     */
    baseToolsOverride?: Record<string, AgentTool>;
    /** Mutable ref used by Agent to access the current ExtensionRunner */
    extensionRunnerRef?: {
        current?: ExtensionRunner;
    };
    /** Session start event metadata emitted when extensions bind to this runtime. */
    sessionStartEvent?: SessionStartEvent;
    autoTitleSessions?: boolean;
    /** Where this session's replies render; omitted means `SENPI_PROMPT_SURFACE` decides. */
    promptSurface?: PromptSurface;
    /** Browser engine this session's skills drive; omitted means none was chosen. */
    browserEngine?: BrowserEngine;
    /** Caller env for this session's tool subprocesses (`open_session.env`, senpi#4381); omitted means none. */
    sessionEnv?: Readonly<Record<string, string>>;
    /** Tool runtime for this session (senpi#3566); absent means `in-process`. */
    toolRuntime?: ToolRuntimeKind;
    /** Where the startup thinking level came from (senpi#3819); absent means `default`. */
    initialThinkingLevelSource?: ThinkingLevelSource;
}
type SessionModelEntry = {
    model: Model<any>;
    thinkingLevel?: ThinkingLevel;
    thinkingSelection?: ThinkingSelection;
    serviceTier?: ServiceTier;
};
export interface ExtensionBindings {
    readonly sizesOnly?: boolean;
    /** Filesystem lookups for a sizes-only report; honoured only with `sizesOnly`. */
    readonly promptSizeInventory?: PromptSizeInventory;
    uiContext?: ExtensionUIContext;
    mode?: ExtensionMode;
    commandContextActions?: ExtensionCommandContextActions;
    abortHandler?: () => void;
    shutdownHandler?: ShutdownHandler;
    onError?: ExtensionErrorListener;
}
export interface TreeNavigationOptions {
    /** navigateTree only: resume the exact entry; select (default) puts user/custom text in the editor. */
    intent?: "select" | "resume";
    summarize?: boolean;
    customInstructions?: string;
    replaceInstructions?: boolean;
    label?: string;
    /** Leaf the caller last observed; the mutation is refused with `stale-leaf` when the session moved on. */
    expectedLeafId?: string;
}
export interface AssistantEditResult {
    editorText?: string;
    cancelled: boolean;
    aborted?: boolean;
    summaryEntry?: BranchSummaryEntry;
    /** The replacement text matched the original, so nothing was appended. */
    unchanged?: boolean;
    /** Id of the appended edited assistant entry. */
    entryId?: string;
}
/** Result of {@link AgentSession.editUserMessage}; the edited-assistant shape, field for field. */
export type UserEditResult = AssistantEditResult;
/** How a steer() or followUp() input was dispatched. */
export type QueuedInputDisposition = "handled" | "queued";
/** Options for AgentSession.prompt() */
export type PromptDisposition = QueuedInputDisposition | "started";
export type QueuedInput = ClientMessageIdentity & {
    readonly text: string;
    readonly mode: "steer" | "followUp";
    readonly enqueueOrder: number;
    /** Session-unique id of this queued input (`q_<n>`), stable until it is delivered or removed. */
    readonly queuedId: string;
    /** 1 when queued, +1 on every edit: a change can name the revision it was based on (senpi#3459). */
    readonly revision: number;
};
/**
 * What a dequeue or edit of one queued input did; `already_delivered` once the input reached a turn, `conflict`
 * when the caller's `expectedRevision` is not the input's current revision (nothing was changed).
 */
export type QueuedInputChange = "removed" | "edited" | "already_delivered" | "not_found" | "conflict";
/** A queued-input change applies only while the input is still at this revision. */
export interface QueuedInputChangeOptions {
    readonly expectedRevision?: number;
}
export type ClearedQueue = {
    steering: string[];
    followUp: string[];
    /** Global enqueue order, independent of native delivery priority. */
    readonly ordered: readonly QueuedInput[];
};
export declare const RESUME_EFFECT_ENTRY = "session-resume-effect";
export interface ResumeSessionRequest {
    readonly expectedSeq?: number;
    readonly mode?: "continue" | "release";
    readonly message?: string;
    readonly effectId?: string;
    /** Resume nothing while a person's Stop or a parent's run hold is live: a resume a peer asks for (senpi#7016). */
    readonly unlessStopped?: boolean;
}
export interface ResumeSessionAnswer {
    readonly resumed: boolean;
    readonly reason?: "stale" | "not_paused" | "resume_through_parent" | "stopped";
    readonly parentSessionId?: string;
    readonly pauseSeq: number;
    readonly turnStarted: boolean;
    readonly deliveredNotices: number;
    readonly deliveredHeldInputs: number;
    readonly replayed?: boolean;
}
/** A human input about to be queued or admitted (senpi#3811 design 4.4). */
export interface HumanInputAdmittedEvent {
    readonly kind: "prompt" | "steer" | "follow_up" | "answer" | "resume";
    readonly at: number;
}
/** Options accepted by the queued-input entry points `steer()` and `followUp()`. */
export interface QueuedInputOptions extends ClientMessageIdentity {
    /**
     * Recovery-ordered enqueue position. A reconnecting client replays its pending
     * messages with their original order so the queue is rebuilt as the user typed it.
     */
    enqueueOrder?: number;
    /** Input provenance reported to `input` extension handlers; defaults to "interactive". */
    source?: InputSource;
    /** Who the input came from; defaults from `source` (see `originOf`). */
    inputOrigin?: InputOrigin;
    /** RPC input: the connection declared `interactive_user`; without it the `input` event attributes it to an agent. */
    interactiveUser?: boolean;
    /** RPC input that arrived as a thread call from another session: its chain hop count, reported on the `input` event. */
    chainCount?: number;
    /** Internal, RPC input: whether its record arrived on a local or a delegated (remote device) connection. */
    connectionOrigin?: ConnectionOrigin;
    /** Persist the prepared queue record before publishing or enqueuing it. */
    onQueuedInput?: (input: PreparedClientInput) => void;
    /** A steer meant only for this turn (`currentTurnId`): checked where it enters the queue, else `TurnConflictError`. */
    expectedTurnId?: string;
}
export interface PromptOptions extends ClientMessageIdentity {
    /** Internal: this input was already reported to `onHumanInputAdmitted` by the caller, so it is not reported again. */
    humanInputReported?: boolean;
    /** Internal: the pause seq when `prompt()` accepted this input; a Stop after it holds the input (senpi#3811). */
    observedPauseSeq?: number;
    /** Internal: called when a newer Stop turned this input into held input instead of a turn. */
    onHeldByNewerStop?: () => void;
    /** Where the input sorts among queued inputs if it ends up queued (a replaying client keeps its order). */
    enqueueOrder?: number;
    /** Whether to dispatch extension commands and expand skill commands and prompt templates (default: true) */
    expandPromptTemplates?: boolean;
    /** Image attachments */
    images?: ImageContent[];
    /** Internal: the text blocks an extension sent `text` as; kept as separate blocks while they still spell it. */
    textBlocks?: readonly string[];
    /** Internal: who started this input when it differs from `source` (a person's answer sent through the extension API). */
    inputOrigin?: InputOrigin;
    /** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
    streamingBehavior?: "steer" | "followUp";
    /** With `streamingBehavior: "steer"`: the turn (`currentTurnId`) this steer is for; any other outcome is `TurnConflictError`. */
    expectedTurnId?: string;
    /** Session-only thinking level applied before starting this prompt. */
    thinkingLevel?: ThinkingLevel;
    /** Source of input for extension input event handlers. Defaults to "interactive". */
    source?: InputSource;
    /** RPC input: the connection declared `interactive_user`; without it the `input` event attributes it to an agent. */
    interactiveUser?: boolean;
    /** RPC input that arrived as a thread call from another session: its chain hop count, reported on the `input` event. */
    chainCount?: number;
    /** Internal, RPC input: whether its record arrived on a local or a delegated (remote device) connection. */
    connectionOrigin?: ConnectionOrigin;
    /**
     * Send command-shaped text that no command handles to the model as plain text. Without it, such
     * interactive or RPC input is rejected with `UnknownCommandError`.
     */
    unknownCommandAsText?: boolean;
    /** Internal hook used by RPC mode to observe prompt preflight acceptance or rejection. */
    preflightResult?: (success: boolean) => void;
    /** Internal hook used by the TUI to distinguish handled input from owned prompt work. */
    promptDisposition?: (disposition: PromptDisposition) => void;
    /** Internal cancellation signal for a prompt that has not acquired session-work ownership yet. */
    signal?: AbortSignal;
    /** Internal callback used by fire-and-forget extension input to retain session-work ownership after its barrier wait. */
    onSessionWorkReady?: () => void;
    sessionTitlePrompt?: string | false;
    onQueuedInput?: (input: PreparedClientInput) => void;
    /** Internal: the admitted native turn now owns the input, before agent_start. */
    onTurnAdmitted?: () => void;
    /** Arm the tool barrier for the turn this prompt starts; ignored when the prompt is queued instead (senpi#3717). */
    toolBarrier?: ToolBarrierSpec;
}
/** Result from cycleModel() */
export interface ModelCycleResult {
    model: Model<any>;
    thinkingLevel: ThinkingLevel;
    /** Whether cycling used the configured favorite model list */
    isScoped: boolean;
    /** Models skipped because their usability budget cannot admit the current context. */
    skippedModels: readonly Model<any>[];
    /** Present when the model switch also changed the active system prompt. */
    systemPromptChange?: SystemPromptChangeEvent;
}
/** Session statistics for /session command */
export interface SessionStats {
    sessionFile: string | undefined;
    sessionId: string;
    userMessages: number;
    assistantMessages: number;
    toolCalls: number;
    toolResults: number;
    totalMessages: number;
    tokens: {
        input: number;
        output: number;
        cacheRead: number;
        cacheWrite: number;
        total: number;
    };
    cost: number;
    /** Some turn had no known price, so `cost` is a lower bound (senpi#3844). */
    costUnknown?: true;
    contextUsage?: ContextUsage;
    /** Absent from hosts that predate the report. */
    failures?: SessionFailureReport;
}
/** Where a tool call learns that steering was queued (senpi#5236). */
export interface InvocationSteering {
    /** Whether steering is already queued when the call starts. */
    pending(): boolean;
    /** Call `onSteer` when steering is queued; returns the unsubscribe. */
    subscribe(onSteer: () => void): () => void;
}
/**
 * Bind a tool call's invocation signals onto `context`: `steeringSignal` fires when `steering` reports steering and is
 * never a cancellation. The subscription ends when the call's signal (else the context's) aborts or on `dispose`;
 * `track`, when given, holds the dispose while the binding is live.
 */
export declare function bindInvocationSignals(context: ExtensionContext, signal: AbortSignal | undefined, steering: InvocationSteering, track?: Set<() => void>): {
    context: ExtensionContext;
    dispose: () => void;
};
/**
 * Cursor admission lives in its own module; the names stay exported here so
 * existing importers keep resolving them.
 */
export { CURSOR_TOOL_RESULT_MAX_CHARS, truncateToolResultBodies } from "./cursor-history-admission.ts";
export declare function providerRetryWatchdogAbortMessage(retryTimeoutMs: number | undefined, streamStartTimeoutMs: number | undefined): string;
export declare class AgentSession {
    readonly agent: Agent;
    readonly sessionManager: SessionManager;
    readonly settingsManager: SettingsManager;
    private _scopedModels;
    private _favoriteModels;
    private _unsubscribeAgent?;
    /** The last repair of the session file, replayed to surfaces that attach before the next prompt (senpi#4295). */
    private _standingRecovery;
    private _unsubscribeRecovery;
    readonly securityNotices: SecurityNoticeSnapshot;
    private _unsubscribeSecurityNotices?;
    private readonly _unfollowProviderAccountChanges;
    private _unsubscribeSettingsSource?;
    private _unregisterMemoryReport;
    private _eventListeners;
    private readonly _structuredLane;
    private _agentEventQueue;
    /** What `_agentEventQueue` still holds, so a tool call stalled behind it can say what it waits on (senpi#6189). */
    private readonly _agentEventQueueLedger;
    private readonly _lifecycleEvents;
    /**
     * Exact message objects whose message_end persistence is still queued.
     * Agent core appends messages to agent.state.messages before emitting
     * message_end; until that event settles on _agentEventQueue, compaction must
     * treat these identities as pending persistence, never as stale or droppable.
     */
    private readonly _messageEndsAwaitingPersistence;
    /** Settles once the queued message_end processing (persistence included) of that exact message has run. */
    private readonly _messageEndPersistence;
    private _isAgentRunActive;
    /** senpi#3709: reset moments the failed requests of this run named, and whether its fallback ladder ran out. */
    private _runLimitResets;
    private _runLimitFailure;
    /** Back-offs spent waiting for a rate-limited or overloaded provider to take queued input (omo#14428). */
    private _queuedDrainBackoffAttempt;
    private _runFallbackExhausted;
    private _promptsInFlight;
    /** senpi#3650: the core may continue a run after agent_end; the settle must not wait on that continuation. */
    private readonly _runContinuations;
    /** senpi#3650: the turn that owns extension handler waits started now; the turn deadline releases only its own. */
    private _handlerTurnScope;
    private _toolExecutionDepth;
    private readonly _toolContextDisposers;
    private _promptStartPending;
    /** The pending start claim; `started` is set when it is released (true only for a turn about to start). */
    private _promptStartClaim;
    /** The next scheduled continuation runs queued input, not the transcript tail (a failed start's joiners). */
    private _continueWithQueuedInput;
    /** True while a reload's `session_start` handlers run; a nested reload would retire the runner they run on. */
    private _sessionStartDispatching;
    /** Waiters for the moment no prompt start is pending and no session start is dispatching (applyProjectTrustChange). */
    private _admissionIdleWaiters;
    /** User-abort generation at the start of an idle trigger turn's awaited admission hooks. */
    private _triggerTurnAdmissionAbortGeneration;
    private _pendingCustomTurnHeaders;
    private _engineTurnStarts;
    private _engineResumeWindow;
    /** The one continuation a host restart owes this session has been made (senpi#7020). */
    private _restartContinued;
    private readonly _engineTurnHold;
    private _lifecycleBinding;
    /** Itemized batches waiting for the entry their one message is written to (senpi#3811). */
    private readonly _persistWatchers;
    /**
     * The entry a ticket's queued message was written as, kept only while a re-send that joined that queued message is
     * still in flight, so a re-send that lost the race still gets its receipt. The last such re-send removes it, so the
     * map holds at most one entry per in-flight re-send (senpi#4125 review).
     */
    private readonly _writtenTicketEntries;
    /** How many sends that joined each ticket's queued message are still in flight. */
    private readonly _carrierJoiners;
    /** Call keys minted with a bridge-started call's execution start (RULING-127 (b), senpi#5374). */
    private readonly _bridgedCallKeys;
    private _resumeSettlement;
    private readonly _engineTurnRelease;
    private readonly _engineTurnInput;
    private readonly _humanInputListeners;
    private readonly _heldInputs;
    private readonly _runHolds;
    private readonly _runBackgroundJobs;
    private readonly _resumeEffects;
    private _stopInterrupt;
    private _deliveredHeldInputIds;
    private _heldCommandRun;
    /** Held person input is captured synchronously but its skills are read asynchronously, so it waits here as a promise. */
    private readonly _releaseExtras;
    private _releaseExtrasGeneration;
    private _engineTurnPauseRecorded;
    private _engineTurnPauseNotified;
    private _nextInputId;
    private _idleWaitPromise;
    private _resolveIdleWait;
    private _settlementEpoch;
    /** Set by the idle release; every runtime read re-hydrates before handing the array out. */
    private _runtimeMessagesTokenized;
    /** Tracks pending steering messages for UI display. Removed when delivered. */
    private _steeringMessages;
    /** Tracks pending follow-up messages for UI display. Removed when delivered. */
    private _followUpMessages;
    /** Queued-input ids a person enqueued (see `hasQueuedPersonInput`); stale ids are pruned on read. */
    private readonly _personQueuedIds;
    /** Recovery-only order across both native queue modes and TUI compaction ownership. */
    private _queuedInputOrder;
    /** The cause of the abort in flight, reported on the `agent_end` it produces. */
    private _abortCause;
    private _nextQueuedInputOrder;
    private _nextQueuedId;
    /** Identified queued input (with a client id) in durable custody; see pending-input-session.ts (senpi#3549). */
    private readonly _pendingInputs;
    private _queueClearRecorded;
    /** The exact message object queued for each `queuedId`, so removal and edits hit the native queue by identity. */
    private readonly _queuedMessages;
    /**
     * Input source of each user message this session admitted, written onto its session entry when the
     * message is persisted. Kept off the message itself so it can never reach a provider request.
     */
    private readonly _userInputSources;
    private readonly _queuedInputDispositions;
    private readonly _queuedInputAges;
    /** Recently delivered `queuedId`s (bounded), so a late dequeue answers `already_delivered`, not `not_found`. */
    private readonly _deliveredQueuedIds;
    private _sessionLogger;
    /**
     * A single notice slot for `compaction.model` fallbacks: a cause logs once, and logs again only
     * after a different cause or a successful use of the override clears the slot.
     */
    private _compactionModelFallbackNotice;
    private _activeCompactionLogAttempt;
    private readonly _supersededCompactionLogAttemptIds;
    /** Messages queued to be included with the next user prompt as context ("asides"). */
    private _pendingNextTurnMessages;
    private _pendingCustomMessages;
    /** Deliveries from other sessions: admitted once into the queues below, tracked until their entry is written. */
    readonly externalAdmission: ExternalAdmission;
    private _controlEndpointHost;
    /** The current extension generation's `pi.session`; a reload retires it with its runner. */
    private _sessionControl;
    private _relocationHost;
    private _postCompactionDeferredSteeringMessages;
    private _postCompactionDeferredFollowUpMessages;
    private _compactionAbortControllerValue;
    private _autoCompactionAbortControllerValue;
    private get _compactionAbortController();
    private set _compactionAbortController(value);
    private get _autoCompactionAbortController();
    private set _autoCompactionAbortController(value);
    private _pendingCompactionAdmission;
    private readonly _compactionLifecycle;
    private readonly _sessionWorkBarrier;
    /**
     * Extension-published activity that outlives a turn (background terminal
     * jobs, terminal monitors, loop-guard holds). Counts persist across extension
     * reloads on purpose: a stale "busy" only delays reclamation, while a lost
     * one would let the host evict a session still doing work.
     */
    private readonly _wakeSources;
    private _unsubscribeWakeSources;
    private _overflowRecoveryRungs;
    private _autoCompactionSessionOverride;
    private _compactionSkippedTooSmall;
    private _requiredCompactionAdmissionError;
    private readonly _transcriptWriteFailures;
    private readonly _recoveryIdentity;
    private _promptOwnsRun;
    private _requiredCompactionTurnError;
    private _resumeCompactionRequirement;
    private _pendingModelSwitch;
    private _pendingSwitchTokenScale;
    private _resumeSlice;
    private _skipNextPostRetryCompactionCheck;
    /**
     * Armed when an accepted compaction produced a summary that still leaves the
     * context over budget. It survives synthetic revision bumps (model or settings
     * changes, queue mutation, extension continuations, scheduled retries) because
     * none of those change the context that was rejected; only a real reduction, a
     * new user prompt, or a manual compaction releases it (#7921 case 6).
     */
    private _blockedPostCompactionAssistant;
    private _delegatedCompactionKey;
    private _skipNextPostCompactionAssistantCheck;
    private _scheduledContinuationRecompacted;
    private readonly _assistantsPendingAtCompaction;
    private readonly _postCompactionUsageExemptAssistants;
    private _messageRevision;
    private _branchSummaryAbortControllerValue;
    private get _branchSummaryAbortController();
    private set _branchSummaryAbortController(value);
    private _sessionTitleAbortController;
    private _sessionTitlePromise;
    /** The prompt text the running prompt's run titles the session with when it settles (senpi#5382). */
    private _pendingSessionTitlePrompt;
    private readonly _autoTitleSessions;
    private _retryAbortController;
    private _retryAttempt;
    private _retryWait;
    /**
     * A manual switch landed while a run was live and no request has been prepared on
     * the pick since (senpi#6893). A failure arriving now came from a request built
     * before the switch, so it is not charged to the pick. Request preparation clears
     * it, which holds for virtual picks too, whose responses name physical models.
     */
    private _manualSwitchAwaitingRequest;
    private readonly _requestShapeRecovery;
    /**
     * Failed response that the next request repeats, set by auto-retry and overflow recovery. The
     * retry is routed with it as `failed`, since the context no longer contains it.
     */
    private _failedResponse;
    /**
     * Resolve the effective retry profile for the current model's provider.
     * Falls back to the senpi-default profile when the provider declares none.
     */
    private _resolveRetryProfile;
    private _probePhase;
    private _hintDeadlineMs;
    private _cumulativeHintedWaitMs;
    private _retryPromise;
    private _retryResolve;
    private _userAbortPromise;
    private readonly _abortProvenance;
    private _deadlineTracker;
    private readonly _agentSettledDelivery;
    /** Resolved when a person's input moves on while this settle's agent_settled handlers still run (omo#11419). */
    private _settledHandlersYield;
    private _suppressQueuedContinuationAfterUserAbort;
    private _userAbortGeneration;
    /** Set when clearQueue({ abortWillFollow: true }) drains queues immediately before abort(). */
    private _hadClearedQueuedMessages;
    private _closedOnRequest;
    private _extensionEventSignal;
    private readonly _bashAbortControllers;
    private readonly _toolDispatcher;
    private _pendingBashMessages;
    private _extensionRunner;
    private _turnIndex;
    private readonly _entryIdsByMessage;
    private _prePromptProjection;
    private readonly _boundaryDispatchedMessages;
    /** Assistant turns whose `turn_end` boundary committed entries, so the next request must re-read agent state. */
    private readonly _boundaryRefreshedTurns;
    private _lastActivityOutcome;
    /** Set when dispose() starts; a turn still unwinding after it cannot resolve persisted entries (senpi#2995). */
    private _disposed;
    private _isBeforeSettle;
    private _abortDuringBeforeSettle;
    private _resourceLoader;
    private _customTools;
    private _baseToolDefinitions;
    private _cwd;
    private _agentDir;
    private readonly _toolChild;
    private readonly _toolChildHostTargets;
    /** The composed filesystem policy the built-in file tools enforce; a tool child's `authorize` asks the same one. */
    private _filesystemPolicy;
    /** Settles once dispose() has stopped the tool child, swept what it launched, closed its in-process offload jobs, and the fallback log's first-start removal has finished. */
    private _toolChildClosed;
    private _fallbackLogSettled;
    private _fallbackLog;
    private _extensionRunnerRef?;
    private _initialActiveToolNames?;
    private _defaultToolNames?;
    private _usesDefaultTools;
    private _evalOnlyToolNames?;
    /** Explicit config override; when supplied it wins over the fixed and declared policy across reloads. */
    private readonly _evalOnlyToolNamesOverride?;
    /** Policy tools withheld from the model, retained so disarming can restore direct access. */
    private readonly _withheldEvalOnlyToolNames;
    /** Eval-only hint names this session published, so a disarm can withdraw exactly those. */
    private readonly _publishedEvalOnlyHintNames;
    /** Active-tool selection as requested by callers, before eval-only filtering. */
    private _requestedActiveToolNames?;
    /** Every tool that has been active this session, in first-activation order (senpi#2095). */
    private readonly _declaredToolNames;
    /** Tool names the base system prompt was last built from. */
    private _promptToolNames;
    /** Whether the last tool declaration used the session-wide declared set. */
    private _promptDeclaresSessionTools;
    private _allowedToolNames?;
    private _excludedToolNames?;
    private _baseToolsOverride?;
    private _sessionStartEvent;
    private _sessionStartSettled;
    private readonly _promptCachePrefixBuilds;
    private readonly _userActivity;
    private _extensionUIContext?;
    private _extensionMode;
    private _extensionCommandContextActions?;
    private _extensionAbortHandler?;
    private _extensionShutdownHandler?;
    private _extensionErrorListener?;
    private _extensionErrorUnsubscriber?;
    private _extensionBindingPromptReadiness;
    private _modelRuntime;
    private _modelRegistry;
    private readonly _fallbackValidationWarnings;
    private _providerRequiredNoticed;
    private readonly _retryFallback;
    private _fallbackTurnFailures;
    private readonly _modelConfigErrors;
    private readonly _selectorCooldowns;
    private readonly _fallbackCircuits;
    private readonly _fallbackCircuitsLease;
    private _probeBackLaneSeq;
    private _circuitProbeWatchdog;
    private readonly _probeBackScheduler;
    private readonly _fallbackNow;
    private readonly _fallbackWallNow;
    private readonly _retryRandom;
    private readonly _environmentContextEnabled;
    private _toolRegistry;
    private _lazyToolActivation;
    /** Created on the first `ctx.executeTool()` call. */
    private _nestedToolCalls;
    /** The issuing assistant message of each model-issued call while it runs, for its nested calls (senpi#5234). */
    private readonly _toolCallIssuers;
    /** Calls a provider's exec channel (the Cursor bridge) runs for the model, from their preflight to their result. */
    private readonly _execBridgeToolCalls;
    private readonly _toolBarrier;
    private _toolDefinitions;
    private _toolPromptSnippets;
    private _toolPromptGuidelines;
    private _toolFullPromptGuidelines;
    private _baseSystemPrompt;
    private _currentServiceTier;
    private _sessionFastMode;
    private readonly _shownHighReasoningWarningKeys;
    private readonly _shownThinkingClampWarningKeys;
    private readonly _startupThinkingClamp;
    /** Last manual preference for unremembered models, kept in the session rather than startup config. */
    private _lastManualThinkingLevel;
    private _thinkingLevelSource;
    private readonly _sessionThinkingMemory;
    private _baseSystemPromptOptions;
    private _baseSystemPromptParts;
    private _sizesOnlyStartup;
    private _promptSizeInventory;
    private _systemPromptOverride?;
    private _promptSurface;
    private _browserEngine;
    private readonly _sessionEnv;
    constructor(config: AgentSessionConfig);
    get modelRuntime(): ModelRuntime;
    get modelRegistry(): ModelRegistry;
    private _getRequiredRequestAuth;
    /**
     * Resolve optional auth for a summarization stream. Native/custom stream
     * functions may provide ambient credentials, unlike streamSimple. A virtual
     * selection is routed first, so the summary is sized for the physical model.
     */
    private _getSummarizationRequestAuth;
    private _resolveSummarizationRequestAuth;
    /**
     * Resolve the model used for compaction summarization. When the user sets a
     * `compaction.model` override ("provider/model"), that model is used for the
     * summarization call instead of the session model — this is what lets an
     * SDK-owned lane (anthropic-subscription) compact on a cheaper/different model.
     * Unset, malformed, unknown, spent, or credential-less overrides keep a usable session model;
     * a set override that cannot serve logs why the session model was used.
     * A spent account instead uses the held target or another authenticated model.
     */
    private _resolveCompactionModel;
    private _logCompactionModelFallback;
    private _getCompactionRequestAuth;
    /**
     * The model whose limits apply to `message`, or undefined when the message came from another
     * model. Under a virtual selection, that is the physical model that produced it.
     */
    private _modelForMessage;
    /**
     * Record the selection on the current branch when the branch implies another one, so a resume
     * restores it. Tree navigation can leave the latest `model_change` on another branch; responses
     * cannot record a virtual selection because they name physical models. Responses do record a
     * physical selection unless the branch holds a virtual one; checking a physical selection against
     * responses would record it on every prompt while `prepareRequest` redirects to another model.
     */
    private _recordSelection;
    /** The model whose limits apply to the conversation. */
    private _limitsModel;
    /**
     * Install tool hooks once on the Agent instance.
     *
     * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
     * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
     * registered tool execution to the extension context. Tool call and tool result interception now
     * happens here instead of in wrappers.
     */
    /**
     * Surface a provider-level server-fallback abort before retry handling runs so
     * the UI can explain the switch. Emitted synchronously here because retry work
     * for the following agent_end starts before queued message_end processing
     * drains. `chainConfigured` is required because the no-chain refusal path
     * emits no retry_fallback_exhausted, leaving the UI no other signal.
     */
    private _emitServerFallbackAborted;
    /** The tool-search service of the current extension generation; undefined when the builtin is not loaded. */
    private _toolSearchService;
    /** Own the service the new extension load created and retire the previous generation's one. */
    private _adoptToolSearchService;
    private _releaseToolSearchService;
    /**
     * Let tool_search answer a query that names an eval-only or removed tool with that
     * tool's redirect hint. Idempotent: called at construction and again once the
     * extension runtime is bound and this session owns its service.
     */
    private _bindToolSearchRemovedHints;
    private _installAgentToolHooks;
    preflightToolCall(toolCall: AgentToolCall, args: unknown, options?: {
        waitForEventQueue?: boolean;
        parentToolCallId?: string;
        signal?: AbortSignal;
        execBridge?: boolean;
    }): Promise<ToolCallEventResult | undefined>;
    private _emitAfterToolCallHooks;
    /**
     * Tools callable through `ctx.executeTool()`: the active `direct` tools and every registered
     * `search` or `eval` tool (upstream `deferred`/`codemode`). `model-only` and `hidden` tools are
     * never callable from other tools.
     */
    private _getCallableTools;
    /**
     * Run a call that the tool call `parentToolCallId` made through `ctx.executeTool()`. It goes
     * through the agent's tool pipeline with the session's hooks, against the callable tools.
     */
    private _executeNestedToolCall;
    /**
     * Route a virtual model selection for each provider request (D-15). The request keeps the
     * context the fork loop built (resident materialization, transformContext, admission); only
     * the model and thinking level of a virtual selection are replaced by the routed physical
     * model for this request. The selection itself stays in agent state.
     */
    private _installAgentRequestProjection;
    private _dispatchTurnEndBoundary;
    /**
     * Consume the agent's `finishTurn` hook (D-16): `turn_end` extension boundaries run before the
     * agent emits `turn_end`, and a boundary `continue` forces one more request.
     */
    private _installAgentBoundaryHooks;
    /**
     * Cursor states a model's real context ceiling on every conversation
     * checkpoint. Once observed, it replaces the catalog guess on the live model
     * so context usage, compaction thresholds and admission all size against the
     * window the server will actually enforce.
     */
    private _applyObservedCursorContextWindow;
    private _installAgentNextTurnRefresh;
    /**
     * Rebuild agent messages from the canonical session projection, keeping the exact messages still
     * awaiting persistence (the fork restore path), and map projected messages to their entries.
     */
    private _refreshFinalizedContext;
    private _applyBoundaryDrafts;
    private _createBoundaryPreviewManager;
    private _getPendingBoundaryMessages;
    private _buildBoundaryContext;
    private _commitBoundaryDrafts;
    /**
     * Run `agent_before_settle` handlers where the run would otherwise settle. Returns whether the
     * session continues: a handler asked for it (and the context can continue) or input is queued.
     */
    private _runBeforeSettleBoundary;
    private _reportInvalidBoundaryContinuation;
    /** Emit an event to all listeners */
    private _emitEntryAppended;
    /** Append a transport-provided entry and publish it on the RPC event stream. */
    appendSessionEntry(entry: SessionEntry): void;
    private _emitFallbackExhausted;
    private _emit;
    private _emitSessionCompactFailed;
    /** Mirror stuck-prone lifecycle transitions into logs/session.log (content-free). */
    private _logSessionEvent;
    private _estimateCompactionLogTokens;
    private _createToolContext;
    private _emitQueueUpdate;
    private _incrementMessageRevision;
    /**
     * `agent.state.messages` with resident tokens hydrated, same array identity.
     * The idle release tokenizes the runtime messages in place to let the resident
     * store drop its hydrated copies; every reader that can run between two turns
     * goes through here so a sentinel never reaches a consumer.
     */
    private _runtimeMessages;
    /** Byte-derived size of the context an admission decision would carry. */
    private _blockedAdmissionContentTokens;
    /** A compaction that genuinely reduced the context clears the blocked state. */
    private _releaseBlockedPostCompactionAdmissionIfReduced;
    /**
     * An explicit user retry releases the automatic-loop latch, not the context
     * admission requirement. The pre-prompt gate must still compact successfully
     * before sending an oversized request.
     */
    private _releaseBlockedPostCompactionAdmission;
    getMessageRevision(): number;
    /** Resolved agent state directory for this session. */
    get agentDir(): string;
    /** Resolves after dispose() once the tool child has exited, its launched groups are swept and the fallback log has stopped writing; awaited by disposers. */
    whenToolChildClosed(): Promise<void>;
    /** The `list_sessions` row of this session's tool child (senpi#3566); `none` under the in-process runtime. */
    toolChildRow(): SessionToolChildRow;
    /**
     * Working directory this session resolves settings against — the same value extensions
     * receive as `ctx.cwd`, so a host surface (RPC) reads project settings identically.
     */
    get cwd(): string;
    private _waitForSettledSessionWork;
    waitForSettledSessionWork(): Promise<void>;
    private _modelSelectionChangesContext;
    private _invalidateCompactionForModelSelection;
    /**
     * #1873 narrows #1378: a cycle silently passes over a candidate only when no
     * reduction could ever make it serve. A candidate that one compaction would fix
     * is landed on and held as a pending switch instead, because skipping it throws
     * away the model the user was cycling towards.
     */
    private _modelChangeWouldExhaustContext;
    private _getIdleWaitPromise;
    private _resolveIdleWaitIfIdle;
    /**
     * senpi#3709: a run whose fallback ladder ran out reports the soonest reset its failed requests
     * named after a limit failure. Outages retain ordinary provider recovery; a known reset that
     * passed during later rungs remains known so a resumer can retry now. Consumed once per settle.
     */
    private _takeRunFallbackExhaustion;
    private _emitAgentSettled;
    /**
     * Drops the session manager's materialized views while nothing runs, when a full-history view of a trimmed
     * mirror is among them (senpi#3519). Unlike `releaseSettledSessionMemory`, nothing is tokenized in place, so a
     * history read can call it while its answer, which may share message objects, is still unwritten.
     */
    releaseFullHistoryView(): void;
    /**
     * Release the memoized session views and tokenize the runtime messages while nothing runs.
     * Called when a run settles idle and after a resumed session's first render, which builds the
     * views without any run settling afterwards.
     */
    releaseSettledSessionMemory(): void;
    private _emitAgentIdleAfterDeferredTurns;
    private _promptAgent;
    private _lastAssistantMessage;
    private _requestSelectedModel;
    private readonly _endSelectedModels;
    /** Internal handler for agent events - shared by subscribe and reconnect */
    private _handleAgentEvent;
    private _createRetryPromiseForAgentEnd;
    private _findLastAssistantInMessages;
    /**
     * Synchronously mirror the auto-compaction decision that _checkCompaction()
     * will make after agent_end. Agent core drains queues before that async work
     * runs, so only this preflight can transfer required admissions safely.
     */
    private _getRequiredAutoCompactionReason;
    /**
     * Threshold checks measure the larger of the provider-reported context and
     * the plain local-transcript estimate. Providers whose usage tracks a
     * server-side summarized conversation (native Cursor checkpoints) can report
     * a context far smaller than the transcript this client replays every turn,
     * and that small figure must not hide a transcript already past the window.
     */
    private _resolveThresholdContextTokens;
    /**
     * `compaction.enabled=false` disables proactive (threshold) compaction only.
     * A provider-confirmed overflow is an error the session cannot progress past
     * by any other route, so overflow recovery stays armed regardless (#1422).
     */
    private _getAutoCompactionReason;
    /**
     * Content measured by bytes, ignoring every provider usage number. The
     * stale-usage exemptions below only claim that a usage figure measured before
     * the accepted compaction boundary is not evidence of current pressure; they
     * must not exempt the messages themselves, because fresh post-boundary content
     * (a large tool result, late steering) is measurable without any usage report
     * (#7921 case 5).
     */
    private _exceedsPolicyByContentEstimate;
    private _hasPendingPostCompactionUsageExemption;
    private _isPostCompactionUsageExempt;
    private _consumePostCompactionUsageExemption;
    /**
     * Disarm the post-compaction usage exemption and hand the input parked behind it back to the ordinary queues.
     * Every path that spends the exemption goes through here, so none can leave that input parked (#4036).
     */
    private _releasePostCompactionDeferral;
    /** The first response after a compaction spends the exemption however it ended; true when it was released here. */
    private _releaseSpentPostCompactionExemption;
    private _agentEndAllowsQueuedContinuation;
    private _willRetryAfterAgentEnd;
    private _isRequiredCompactionError;
    private _processAgentEvent;
    /** Resolve the pending retry promise */
    private _resolveRetry;
    private _resetHintTierState;
    private _isCircuitProbeOnCurrentModel;
    /** The first streamed content from the probed entry proves it serves again. */
    private _acceptCircuitProbeOnProgress;
    /**
     * A probe holds the circuit's only admission until it settles, so it must never
     * hang: with the stream-start guard disabled, the probe still gets that guard's
     * default bound and is aborted as a provider failure when it expires.
     */
    private _armCircuitProbeWatchdog;
    private _clearCircuitProbeWatchdog;
    private _emitSessionAbort;
    /**
     * Arm the probe-back scheduler for a tier-2 demoted selector. The scheduler
     * will fire at most two probes (half-hint, then deadline) and clear the
     * selector cooldown on success so maybeRestorePrimary reverts at the next
     * turn boundary.
     */
    private _armProbeBackForDemotedSelector;
    private _findPersistedMessageEntryId;
    /** Find the last assistant message in agent state (including aborted ones) */
    private _findLastAssistantMessage;
    /**
     * Retry failures stay in append-only history but must not be retained in the
     * active context branch. Otherwise split-turn compaction keeps the failed
     * assistant response verbatim and cannot make progress before a retry.
     */
    private _retireFailedRetryAssistant;
    private _isAssistantFromBeforeLatestCompaction;
    private _replaceMessageInPlace;
    /** Emit extension events based on agent events */
    private _emitExtensionEvent;
    /**
     * Subscribe to agent events.
     * Session persistence is handled internally (saves messages on message_end).
     * Multiple listeners can be added. Returns unsubscribe function for this listener.
     */
    subscribe(listener: AgentSessionEventListener): () => void;
    /**
     * The internal structured lane (senpi#4272): every session event in `_emit` order with its provider capture, plus
     * block controls at their position. Attach before a turn's first provider push; a stream already pushing keeps
     * its decision and yields no capture.
     */
    subscribeStructured(listener: (record: AgentSessionStructuredRecord) => void, failed?: (cause: unknown) => void): () => void;
    /** Whether `subscribeStructured` can attach: false for an Agent constructed outside the session layer. */
    get hasStructuredLane(): boolean;
    /** Disconnect from agent events during disposal. */
    private _disconnectFromAgent;
    /**
     * Remove all listeners and disconnect from agent.
     * Call this when completely done with the session.
     */
    dispose(): void;
    /** Extension-published wake sources that currently report live work, by `source` name. */
    get activeWakeSources(): readonly string[];
    /** Live in-session activity signals; see `session-activity.ts` for the contract. */
    get activitySnapshot(): SessionActivitySnapshot;
    /**
     * Whether this session owns work that must outlive a teardown decision: an
     * agent run, bash, compaction, barrier-held session work, or an
     * extension-published wake source. Occupancy sweeps (the shared RPC host's
     * idle eviction) MUST consult this rather than individual flags, so a new
     * activity source is picked up by every call site at once.
     */
    get isSessionBusy(): boolean;
    /** Refresh the public finalized transcript from the canonical session projection. */
    refreshContext(): void;
    /** Full agent state */
    get state(): AgentState;
    /** Current model (may be undefined if not yet selected) */
    get model(): Model<any> | undefined;
    /** Current thinking level */
    get thinkingLevel(): ThinkingLevel;
    /** Explicit selector provenance, absent for SDK-defaulted effective levels. */
    get thinkingSelection(): ThinkingSelection | undefined;
    /** Where the thinking level in force came from (senpi#3819). */
    get thinkingLevelSource(): ThinkingLevelSource;
    /** This session's last thinking level per model, keyed `provider/id` (senpi#3819). */
    getSessionModelThinkingLevels(): Record<string, ThinkingLevel>;
    /**
     * The level `model` runs at in this session: the current one for the active model, otherwise the
     * level a switch to it would restore. Nothing is applied (senpi#3819).
     */
    getThinkingLevelForModel(model: Model<Api>): {
        level: ThinkingLevel;
        source: ThinkingLevelSource;
        availableLevels: ThinkingLevel[];
    };
    /** An explicit thinking request clamped while this session was created (senpi#2395). */
    get startupThinkingClamp(): ThinkingClampNotice | undefined;
    get serviceTier(): ServiceTier | undefined;
    /**
     * True when the active model is served at the priority ("fast") tier: either the model
     * itself is configured for it (an `openai` `-fast` catalog variant, a scoped
     * `provider/id:priority`) or an extension turned fast mode on for this session.
     *
     * Display-only: it never feeds request composition, so an extension toggling fast mode
     * for one provider cannot leak `service_tier` into another provider's payload.
     * `serviceTier` stays the single request-side source.
     */
    isFastModeActive(): boolean;
    /**
     * The tier a request would carry right now: `serviceTier`, promoted to `"priority"` while
     * session fast mode is on (which is exactly what the service-tier extension puts on the
     * wire). Reported to clients so `serviceTier` and `fastMode` can never disagree.
     */
    get effectiveServiceTier(): ServiceTier | undefined;
    /**
     * Session-scoped fast-mode indicator; never persisted, reset on session start.
     *
     * Turning fast OFF also clears the cached priority tier: `/fast off` writes a remembered
     * `"auto"` that must override an inherited catalog-priority tier immediately (display and
     * request side), not only on the next session. Only codex-response models are touched, and
     * never when an explicit scoped/favorite `:priority` pin is in force — those are pinned by
     * the user's model selection, not by `/fast`.
     */
    setSessionFastMode(enabled: boolean): void;
    /**
     * Emit `service_tier_changed` when the effective tier or the fast-mode indicator actually
     * moved. Both are observable state for RPC clients (`get_state.serviceTier` / `.fastMode`),
     * and they can move independently: a session fast-mode toggle need not change the resolved
     * tier, and a model switch can change the tier with fast mode untouched.
     */
    private _emitServiceTierChangeIfNeeded;
    /**
     * Explicit scoped/favorite tiers win; otherwise fall back to the model's
     * configured serviceTier from models.json/extension compatibility config. The per-model
     * `/fast` memory is honored by the service-tier extension (`liveMemoryTier` + the session
     * flag in `before_provider_request`), not cached here: caching it would survive a same-session
     * `/fast off` (no model switch to re-resolve) and leak an inherited priority onto the wire.
     */
    private _resolveServiceTier;
    /** Under a virtual selection, the physical model and thinking level of the latest successful response. */
    get routedModel(): {
        model: Model<any>;
        thinkingLevel?: ThinkingLevel;
    } | undefined;
    /** Whether the session is currently processing an agent run or post-run continuation. */
    get isStreaming(): boolean;
    /** The running turn's id (its admission epoch); undefined while no turn runs. A steer names it as `expectedTurnId`. */
    get currentTurnId(): string | undefined;
    /** Record a background job under the running turn; outside a turn nothing is recorded. */
    registerRunBackgroundJob(job: RunBackgroundJob): () => void;
    /** Stop the background jobs `turnId` started (`interrupt { background: "stop" }`). */
    stopRunBackgroundJobs(turnId: string): Promise<RunBackgroundStopOutcome>;
    /** True while a provider retry is in flight; the deadline lease treats it as turn progress. */
    get isRetryInFlight(): boolean;
    /** Whether the session has no active agent run, retry, or queued continuation. */
    get isIdle(): boolean;
    /** The surface this session's prompt is built for; what its host does with a result follows from it. */
    get promptSurface(): PromptSurface;
    /**
     * Rebuilds the prompt for another surface (a later `open_session.promptSurface`). The next
     * turn's `before_agent_start` hands presets the new surface through `systemPromptOptions`.
     */
    setPromptSurface(surface: PromptSurface): void;
    /** Moves this session to another browser engine (a later `open_session.browserEngine`); the next tool call sees it. */
    setBrowserEngine(engine: BrowserEngine): void;
    get browserEngine(): BrowserEngine | undefined;
    get sessionEnv(): Readonly<Record<string, string>> | undefined;
    /** Current effective system prompt (includes any per-turn extension modifications) */
    get systemPrompt(): string;
    /** The stable prefix the turn request splits `systemPrompt` at, while the prompt still starts with it (senpi#4447). */
    get systemPromptStablePrefix(): string | undefined;
    /** Current retry attempt (0 if not retrying) */
    get retryAttempt(): number;
    get retryWait(): RetryWait | undefined;
    /** Abort owner for the current turn boundary, used by internal renderers. */
    get currentAbortSource(): AgentAbortSource | undefined;
    /** The deadline that stopped the current turn, when the lease fired (senpi#3227). */
    get currentDeadline(): TurnDeadline | undefined;
    /** Adapter for the deadline owner interface: a deadline stop that could not complete. */
    _warnDeadline(event: TurnDeadlineWarning, detail: string): void;
    /**
     * End the running turn because the process hosting this session is stopping (an RPC host shutting down or
     * restarting): a system abort whose `agent_end` carries `abortCause: { kind: "host_shutdown" }`, never a user abort.
     */
    abortForHostShutdown(): Promise<void>;
    /** Adapter for the deadline owner interface: end the turn through the normal system abort. */
    abortTurnForDeadline(): Promise<void>;
    /**
     * An abort (Esc, or the turn deadline) that the run does not honour within the grace is held by an extension handler
     * no abort signal reaches: release the turn's held handler waits so it settles (senpi#3650).
     */
    private _waitForIdleAfterAbort;
    /**
     * A person's input arrived while the settled run's notification-only agent_settled handlers still run: stop waiting on
     * every one of them (omo#11419). The held one is released quietly (session.log stage "released", no extension error);
     * the rest of the walk runs detached. A prompt sent from inside an agent_settled subscriber, before any handler is
     * held, marks the yield so the settle releases the first handler as soon as it starts.
     */
    private _yieldSettledHandlers;
    private _yieldHeldSettledHandlers;
    /** Adapter for the deadline owner interface: stop waiting on extension handlers that hold the turn (senpi#3650). */
    releaseHeldExtensionHandlers(): number;
    /** Record a deadline stop durably so the goal engine holds off until admitted user input. */
    _recordDeadlineStop(deadline: TurnDeadline): void;
    /**
     * Get the names of currently active tools.
     * Returns the names of tools currently set on the agent. Tools with `search` or `eval` exposure
     * are callable from other tools through `ctx.executeTool()` without being active.
     */
    getActiveToolNames(): string[];
    /** Get the names of the tools that tools can call through `ctx.executeTool()`. */
    getCallableToolNames(): string[];
    /**
     * Get all configured tools with normalized exposure metadata and source metadata.
     */
    getAllTools(): ToolInfo[];
    getToolDefinition(name: string): ToolDefinition | undefined;
    /**
     * The tool a call named `requested` runs, by the same rule the agent loop
     * applies (exact name, else the unique alias among callable tools), without
     * activating anything. Returns `requested` when nothing resolves.
     */
    resolveToolCallName(requested: string): string;
    /**
     * Serves the tool child's `completion` or `reserved` calls on the server (codemode registers its completion handler and
     * `runReservedTool`, which hold `evalHandleHost`). Returns the unregister function; a later registration replaces it.
     */
    registerToolChildHostTarget(kind: RegisteredHostCallKind, target: HostCallTarget): () => void;
    executeTool<TDetails = unknown>(toolName: string, params: unknown, options?: ExecuteToolOptions<TDetails>): Promise<AgentToolResult<TDetails>>;
    /**
     * Lazily activate a registered inactive tool.
     *
     * Resolution order is deliberate: resolve the winning definition and enforce its
     * `allowLazyActivation` hard stop, then invoke activators in registration order.
     * The caller re-resolves the tool from the active registry before execution.
     */
    /** The child jobs the registered tools declare (`ToolDefinition.childJob`): who a child's wake or exit concerns. */
    private _childJobs;
    private _callableToolNames;
    private _toolSearchCatalogNames;
    private _activateLazyTool;
    private _isEvalOnlyPolicyArmed;
    /** Resolve fixed and declared eval-only tools, unless an SDK embedder supplied an override. */
    private _resolveEvalOnlyToolNames;
    /**
     * Publish per-tool eval-only redirect hints so a direct call names its own eval helper.
     *
     * Hints published here are tracked so a disarm - or a shrinking armed set, e.g. bash+workflow
     * down to workflow only - withdraws the stale ones. Only tracked names are ever deleted, so
     * hints owned by other publishers survive.
     */
    private _publishEvalOnlyToolHints;
    /**
     * Set active tools by name.
     * Only tools in the registry can be enabled. Unknown and hidden tool names are ignored.
     * Also rebuilds the system prompt to reflect the new tool set.
     * Changes take effect on the next agent turn.
     */
    /**
     * Resolve an executable tool from the full registry (builtin + extension
     * tools), independent of the active set. The Cursor exec bridge uses this:
     * Cursor drives its native tools (read/bash/grep/ls/write) over the exec
     * channel regardless of which tools the request advertised.
     */
    getRegisteredTool(name: string): AgentTool | undefined;
    /** The exec-frame call `toolCallId` ended, whether it ran, was blocked or was aborted: it is no longer model-issued. */
    releaseExecBridgeToolCall(toolCallId: string): void;
    /** Cursor exec already ran the tool; still emit tool_result so plan-touch trackers see .omo/plans writes. */
    emitExecBridgeToolResult(toolName: string, toolCallId: string, args: unknown, result: AgentToolResult<unknown>, isError: boolean): Promise<void>;
    setActiveToolsByName(toolNames: string[]): void;
    /**
     * senpi#2095: a model that accepts `allowed_tools` is declared every tool this session has
     * activated, and the prompt's tool section lists that same set, so the active set shrinking or
     * re-growing restricts callability through `tool_choice` instead of rewriting the cached prefix.
     * Any other model is declared exactly the active tools.
     */
    private _declaresSessionTools;
    private _toolDeclarationNames;
    private _applyToolDeclarations;
    /**
     * Re-derive the declaration after a model change. Only a switch into or out of a model that declares
     * the session set can move it, and the prompt is rebuilt only when its tool list actually moves.
     */
    private _refreshToolDeclarationsForModel;
    /** Whether compaction or branch summarization is currently running */
    get isCompacting(): boolean;
    get compactionState(): Readonly<CompactionLifecycleState>;
    /** All messages including custom types like BashExecutionMessage */
    get messages(): AgentMessage[];
    /** Current steering mode */
    get steeringMode(): "all" | "one-at-a-time";
    /** Current follow-up mode */
    get followUpMode(): "all" | "one-at-a-time";
    /** Current session file path, or undefined if sessions are disabled */
    get sessionFile(): string | undefined;
    /** Current session ID */
    get sessionId(): string;
    /** Subscribe to the internal event bus shared by this session's extensions. */
    onExtensionEvent(channel: string, handler: (data: unknown) => void): () => void;
    /** Host input entry point; not exposed by the extension API or its event bus. */
    recordUserActivity(kind: UserActivityKind): void;
    /** Publish on the internal event bus shared by this session's extensions. */
    emitExtensionEvent(channel: string, data: unknown): void;
    /** Installed by the interactive mode before it binds extensions; `pi.session.registerControlEndpoint` needs one. */
    setControlEndpointHost(host: ControlEndpointHost | undefined): void;
    /** Installed by a host that can continue this session on another computer (`pi.session.requestRelocation`). */
    setRelocationHost(host: SessionRelocationHost | undefined): void;
    /** Current session display name, if set */
    get sessionName(): string | undefined;
    /** Globally narrowed models (from --models / enabledModels) */
    get scopedModels(): ReadonlyArray<SessionModelEntry>;
    /** Update global model narrowing */
    setScopedModels(scopedModels: SessionModelEntry[]): void;
    /** Favorite models for Ctrl+P cycling */
    get favoriteModels(): ReadonlyArray<SessionModelEntry>;
    /** Update favorite models for Ctrl+P cycling */
    setFavoriteModels(favoriteModels: SessionModelEntry[]): void;
    private _getCurrentFavoriteModels;
    /** File-based prompt templates */
    get promptTemplates(): ReadonlyArray<PromptTemplate>;
    private _normalizePromptSnippet;
    private _normalizePromptGuidelines;
    private _rebuildSystemPrompt;
    /**
     * Run `input` extension handlers for queued (steer / follow-up) input.
     *
     * Queued input reaches the model exactly like a prompt does, so it passes the same
     * extension surface: a handler may consume it or rewrite it. The input keeps the
     * session-scoped `inputId` identity, so the `input_disposition` event a handler
     * observes correlates with the input it saw.
     *
     * @returns the (possibly transformed) input, or `undefined` when a handler consumed it.
     */
    private _runInputHandlers;
    private _emitInputDisposition;
    /**
     * Send a prompt to the agent.
     * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
     * - Expands file-based prompt templates by default
     * - During streaming, queues via steer() or followUp() based on streamingBehavior option
     * - Validates model and API key before sending (when not streaming)
     * @throws Error if streaming and no streamingBehavior specified
     * @throws Error if no model selected or no API key available (when not streaming)
     */
    /**
     * A provider whose stored credential pools two or more accounts: whether any of them can serve `modelId` now
     * (no live block, and no live block on that model), and the accounts with why each is out. A cooling account is
     * not usable until its cooldown ends, so an automated loop never probes a spent pool turn after turn (senpi#3131).
     * Undefined for a single-credential provider, or when pool health cannot be read (the hold then stays).
     * Reads pool health only, never key material.
     */
    private _pooledAccountHealth;
    /**
     * The reported usage of this provider's accounts, without the ones only the user can bring back (a re-login, a
     * disabled, signed-out, billing- or organization-blocked account): the pool skips those whatever their usage reads,
     * so their usage must not release the provider's hold (senpi#6536). An account out only on a usage limit keeps it.
     * Accounts the summary does not name keep their usage, so a provider holding one credential still releases on its
     * own reading.
     */
    private _usageOfSelectableAccounts;
    prompt(text: string, options?: PromptOptions): Promise<void>;
    /** A person's input (prompt, steer, follow-up, answer) attends the session and releases what it holds. */
    private _beginPersonInput;
    /**
     * Every input release settles here, once nothing could still admit it: no prompt in flight (a
     * command's follow-on reaches `prompt()` synchronously) and no run active. Called from every
     * prompt's `finally`, from run settlement, and after an answer is dispatched.
     */
    private _settleInputRelease;
    /**
     * Hold a person's raw input for the parent's run Resume under its client id, so a replay is held once; its
     * commands, skills and templates run when it is delivered. The child's own Stop goes only once the input is held.
     */
    private _holdForRun;
    /** Hold a person's prepared input (expanded text and images) under its client id, so a replay is held once. */
    private _holdPreparedInput;
    private _isExtensionCommandText;
    private _prompt;
    /** Apply before_agent_start additions and reset any prior turn's system-prompt override. */
    private _applyBeforeAgentStartResult;
    /**
     * Try to execute an extension command. Returns true if command was found and executed.
     */
    private _tryExecuteExtensionCommand;
    /**
     * Throw `UnknownCommandError` when `text` is command-shaped and no extension command, prompt
     * template, or loaded skill resolves it. Runs after input transforms and expansion, so extension
     * rewrites and expanded commands never reach here as unknown.
     */
    private _rejectUnknownCommand;
    /**
     * Expand explicit skill invocations to their full content.
     * Leading runs accept slash and dollar syntax; inline `$name` expands only when
     * it names a loaded skill, so ordinary dollar prose such as `$HOME` stays literal.
     */
    private _expandSkillCommand;
    private _expandSkillTokens;
    /**
     * Shared queueing path for `steer()` and `followUp()`: extension-command guard,
     * `input` handlers, skill/template expansion, then the recovery-ordered enqueue.
     */
    private _queueUserInput;
    private _promptHeldQueuedInput;
    private _admitQueuedInput;
    /**
     * An input that names a turn is refused before any admission side effect (human-input record, person input, input
     * handlers) when that turn is not running, or when a hold would deliver the input into a later turn (senpi#5776).
     */
    private _refuseStaleNamedTurn;
    /**
     * Queue a steering message while the agent is running.
     * Delivered after the current assistant turn finishes executing its tool calls,
     * before the next LLM call.
     * Runs `input` extension handlers, then expands skill commands and prompt templates.
     * Errors on extension commands.
     * @param images Optional image attachments to include with the message
     * @param options Recovery enqueue order and input source; source defaults to interactive
     * @throws Error if text is an extension command
     */
    steer(text: string, images?: ImageContent[], options?: QueuedInputOptions): Promise<QueuedInputDisposition>;
    /**
     * Queue a follow-up message to be processed after the agent finishes.
     * Delivered only when agent has no more tool calls or steering messages.
     * Runs `input` extension handlers, then expands skill commands and prompt templates.
     * Errors on extension commands.
     * @param images Optional image attachments to include with the message
     * @param options Recovery enqueue order and input source; source defaults to interactive
     * @throws Error if text is an extension command
     */
    followUp(text: string, images?: ImageContent[], options?: QueuedInputOptions): Promise<QueuedInputDisposition>;
    private _startSessionTitleGeneration;
    private _generateSessionTitle;
    /**
     * The auto-title is part of the `agent_end` of the run that asked for it: requested after that run's last model
     * response and awaited before `agent_settled` and `agent_idle`. Its `session_info_changed` therefore has one place in
     * the stream (after `agent_end`, before the settle), ahead of anything a host or background job does once the session
     * is idle. Started at network-reply time it raced those inputs (senpi#5382). An abort drops it (`_abortWithProvenance`).
     */
    private _settleSessionTitle;
    private abortSessionTitleGeneration;
    private _buildSessionTitleBaseOptions;
    /**
     * Internal: Queue a steering message (already expanded, no extension command check).
     */
    private _queueSteer;
    /**
     * Internal: Queue a follow-up message (already expanded, no extension command check).
     */
    private _queueFollowUp;
    /** Identified input is admitted into durable custody and enqueued in one gated step; other input as before. */
    private _enqueueQueuedInput;
    /** Restore accepted input without re-running input transforms or changing its enqueue order. */
    restoreQueuedInput(input: PreparedClientInput): Promise<void>;
    private _enqueuePreparedInput;
    private _flushPostCompactionDeferredMessages;
    /**
     * Hand parked input back to the agent queue at the place it was sent: newer input of the same mode that was
     * queued meanwhile is moved behind it, so delivery keeps the order the input was sent in (#4036).
     */
    private _requeueAtOriginalPlace;
    /**
     * Throw an error if the text is an extension command.
     */
    private _throwIfExtensionCommand;
    /** Whether a triggered automatic wake reaches the hold gate at all (senpi#3811). */
    private _wakeGateApplies;
    /** An itemized batch, admitted where a plain `sendMessage` is, answering one receipt per item (design 4.5). */
    private _sendItemizedMessage;
    /**
     * The atomic admission of an itemized batch: if a live hold applies to the batch or to any item (by that item's
     * producer and run), every item becomes its own notice, all in one entry; otherwise the batch is delivered as one
     * message and every item's receipt names the entry that message was written to. Async so a failed write rejects
     * the receipts even on a deferred path; the held branch still decides custody before its first await.
     */
    private _admitItemized;
    /** A re-send of a queued ticket shares the queued message's outcome instead of waiting on a message never written. */
    private _joinPersistWatcher;
    /** The queued message that already carries this ticket, if any. */
    private _queuedTicketCarrier;
    private _recordWrittenTicket;
    private _takePersistWatcher;
    /**
     * Send a custom message to the session. Creates a CustomMessageEntry.
     *
     * Handles three cases:
     * - Streaming: queues message, processed when loop pulls from queue
     * - Not streaming + triggerTurn: appends to state/session, starts new turn
     * - Not streaming + no trigger: appends to state/session, no turn
     *
     * @param message Custom message with customType, content, display, details
     * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
     * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
     */
    sendCustomMessage<T = unknown>(message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">, options?: {
        triggerTurn?: boolean;
        deliverAs?: "steer" | "followUp" | "nextTurn";
        ticket?: string;
    }, deferredTurnClaim?: DeferredTurnClaim, releasedWake?: () => boolean, itemized?: ItemizedAdmission, onQueued?: () => void): Promise<void>;
    private _leaveCarrier;
    private _queuedDeliveryTickets;
    /** Read from the durable custody key, so a delivery re-sent from custody after a restart is still the engine's. */
    private _isEngineDelivery;
    /**
     * senpi#3864: a queued delivery that leaves the queue unconsumed is no longer work the engine owes. A cleared
     * one is cancelled (a producer keeps its own ticket open without the payload); one an abort left queued waits
     * for a person's turn, so its engine ticket turns passive.
     */
    private _releaseQueuedDeliveries;
    /** A removed itemized message is never written: every send waiting on it settles now (senpi#4106). */
    private _settleRemovedCarriers;
    private _retireLifecycleDelivery;
    private _deliverCustomMessage;
    /** The holds a peer delivery cannot release (senpi#6490); `externalAdmission` answers `held` with them. */
    private _peerDeliveryHolds;
    /**
     * A peer delivery the wake gate would hold, with no hold a peer cannot release, continues the session as a person's
     * input does (senpi#6490): an `unattended` hold, or the release barrier of an unattended Resume. `_engineTurnInput.begin()`
     * attends the session and releases what it holds, after which `holdsSource` is false; so the admission's `started`
     * (no `_peerDeliveryHolds()`) and this gate always agree, and anything else is answered `held`.
     */
    private _peerDeliveryReleasesHold;
    /**
     * Subscribe to human input as it enters the session: called synchronously for every input whose origin is a
     * person (TUI input, RPC prompt/steer/follow_up, human question answers, `resumeSession`). Origin comes from
     * the entry point, never from the connection's `interactive_user` role, which only decides authority. Never
     * called for automatic deliveries (extension messages, wakes, continuations). A throwing listener does not block
     * the input. Timing: a call means a person sent it, not that it took effect: `prompt` reports before checks that
     * can still throw, `resumeSession` reports even when nothing is paused, and TUI messages queued during
     * compaction report when they are delivered.
     */
    onHumanInputAdmitted(listener: (event: HumanInputAdmittedEvent) => void): () => void;
    /** Internal adapter boundary for a validated reply that resumes the current turn. */
    admitHumanAnswer(): void;
    private _humanInputAdmitted;
    /** Explicit user Resume; attachment alone must never call this. */
    resumeSession(): Promise<void>;
    /** Resume and wait until the resumed work has settled (TUI, tests). */
    resumeSessionRequest(request: ResumeSessionRequest): Promise<ResumeSessionAnswer>;
    /**
     * Resume after a Stop or an unattended hold (senpi#3811 design 4.9). The answer is ready once the release is
     * admitted; `settled` resolves when the resumed work has settled. Every request field is optional.
     */
    beginResume(request: ResumeSessionRequest): Promise<{
        answer: ResumeSessionAnswer;
        settled: Promise<void>;
    }>;
    private _resumeOnce;
    /**
     * One turn after a Stop: held human input, then notices, then the directive. Resolves once that turn started (or
     * once its send settled without one) and returns its settlement, which finishes the release only if the shared
     * resume settlement delivered the turn.
     */
    private _resumeAfterStop;
    /**
     * Settles once the latest resume turn's held input and notices were consumed, or the turn was not delivered
     * (senpi#3811/#3864). Published when that resume turn begins, so a caller waits for consumption deterministically
     * instead of counting ticks.
     * @internal Not part of the RPC surface.
     */
    resumeSettled(): Promise<void>;
    /** The resume turn both resume paths start; held input and notices are consumed only if no newer Stop aborted it. */
    private _startResumeTurn;
    private _startResumeTurnWith;
    /** Human input kept while a run-owned hold blocks turns; idempotent by input id (senpi#3811). */
    holdInput(input: {
        inputId: string;
        revision: number;
        text: string;
        images?: ImageContent[];
    }): HoldInputResult;
    withdrawHeldInput(inputId: string): boolean;
    get pausedHeldInputCount(): number;
    /** Before a human input releases a Stop: the hidden directive and held human input ride ahead of the wakes. */
    private _captureReleaseExtras;
    /** The held-command run the last release started, for the person input it releases to await (senpi#3811). */
    private _takeHeldCommandRun;
    /**
     * Held input is prepared when delivered, not when held (senpi#3811). The held extension commands leave custody
     * now and run in the order typed: a command that ran is delivered, so no later release runs it twice; the run
     * reports a failure instead of rejecting. A manual-continue "." stays in custody: the delivering turn continues
     * the work itself, so it is settled with that turn and stays held if the turn is not delivered.
     */
    private _takeHeldCommands;
    /** A held person input's text as the model receives it: skills and prompt templates expanded. */
    private _preparedHeldText;
    private _takeHeldInputs;
    /**
     * A superseded host generation draining a session nobody is attached to (senpi#3114): automatic turns wait as
     * notices from here on, exactly as on an unattended reopen, so the running turn is the session's last on this
     * host and it parks when that turn settles. A person's input or resume_session releases the hold.
     */
    holdAutomaticTurns(): void;
    /**
     * A session reopened because it was live when its previous host ended continues as that host left it (senpi#7020):
     * it releases the holds the restart caused, through the ordinary Resume when they are the only ones, so the wakes
     * held during a drain are delivered, a goal resumes and an engine-started run the restart cut continues once.
     */
    private _continueAfterHostRestart;
    /**
     * A graceful close drains the running turn (oh-my-openagent#14313): automatic turns (monitor, goal, loop wakes) wait
     * as notices meanwhile, so the running turn is the session's last. The close releases the hold again whether it
     * ends the session or gives up, so a reopen never replays it as a pause.
     */
    holdForClose(): void;
    releaseCloseHold(): void;
    /** Set by `recordClosedOnRequest`: the teardown's `session_shutdown` then carries `closed: true`. */
    get closedOnRequest(): boolean;
    /**
     * A graceful close ended this session on request (oh-my-openagent#14313): its `session-closed` entry is the clean-stop
     * record, and the teardown tells extensions to stop the work they would otherwise restore on a reopen.
     */
    recordClosedOnRequest(record: SessionClosedRecord): void;
    /** A parent's Stop reaching this child (senpi#3811): hold every automatic turn until the parent's run Resume. */
    pauseForRun(owner: {
        parentSessionId: string;
        parentPauseSeq: number;
        runRef: RunRef;
    }): Promise<InheritResult>;
    resumeForRun(request: {
        parentSessionId: string;
        parentPauseSeq: number;
        childSeqCutoff: number;
    }): Promise<ReleaseInheritedResult & {
        turnId?: string;
    }>;
    private _pauseState;
    private _emitHoldChanged;
    private _nextTurnStart;
    /** Whether the user's Stop or a parent's run hold is live: automatic connection input is then kept as a notice. */
    automaticInputHoldLive(): boolean;
    noteAutomaticInput(text: string): boolean;
    private _stopAddedSince;
    private _stopHoldLive;
    private _resumeCause;
    get pauseView(): {
        pauseSeq: number;
        records: {
            kind: string;
            key: string;
            runRef?: {
                kind: string;
                id: string;
            };
            parentSessionId?: string;
        }[];
    };
    get runPaused(): boolean;
    get paused(): boolean;
    private _createLifecycleBinding;
    /** Reads the lifecycle; every fact that feeds it raises its own change edge, so a read never writes (senpi#3980). */
    get lifecycle(): import("./session-lifecycle-types.ts").SessionLifecycle;
    get workObligations(): import("./work-obligations.ts").SessionWorkObligations;
    get lifecycleApi(): LifecycleApi;
    reportChildLifecycle(report: ChildLifecycleReport): void;
    requestSelfSettle(): import("./session-lifecycle-types.ts").SelfSettleResult;
    refreshLifecycle(): void;
    get pausedNoticeCount(): number;
    get holds(): import("./engine-turn-hold.ts").SessionHold[];
    /** The interrupted-run hold; on a reopen after a restart it names why a cut continuation stays held (senpi#7079). */
    private _addInterruptedRunHold;
    /**
     * An automatic send that would start a turn while the previous run is interrupted waits for a person (senpi#4683):
     * it joins the interrupted-run hold as a notice that Resume or the next message delivers. Refused as a turn it was
     * lost, and each refusal counted as an engine turn until the no-work limit paused the session.
     */
    private _holdForInterruptedRun;
    private _noteHeldWake;
    /**
     * The engine-turn bound's bookkeeping must never stop a turn: a session file that refuses the write (read-only,
     * full disk) only loses the count, as the turn's own persistence reports the failure (senpi#2967).
     */
    private _recordEngineTurnStart;
    /**
     * A refused engine turn still records its message and settles a cross-session delivery it carries. A message
     * whose entry the file refuses leaves the context too: its sender redelivers it, and it must not appear twice.
     */
    private _recordRefusedEngineTurnMessage;
    /** Keeps this process's engine-turn record: a user message clears it, a tool call marks the running engine turn. */
    private _observeEngineTurnMessage;
    /**
     * An engine-originated turn (an extension's `sendMessage` with `triggerTurn`, from any source) that would
     * exceed the engine-wide bound is not started: the message is still recorded, and the stop is recorded (best
     * effort), emitted and shown, so a session file that refuses writes still pauses visibly (senpi#2967).
     */
    private _stopEngineTurn;
    /** Environment context a new turn must carry: set when cwd or date differs from the latest one visible (senpi#2093). */
    private _pendingEnvironmentContextMessage;
    private _appendCustomMessage;
    private _flushPendingCustomMessages;
    /**
     * Send a user message to the agent. Always triggers a turn.
     * When the agent is streaming, use deliverAs to specify how to queue the message.
     * If the prompt path rejects before the message reaches a queue or a turn
     * (e.g. a required compaction that cannot complete), the message is retained
     * in the steering/followUp queue for later delivery and the error still propagates.
     *
     * @param content User message content (string or content array)
     * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
     * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.
     */
    sendUserMessage(content: string | (TextContent | ImageContent)[], options?: {
        deliverAs?: "steer" | "followUp";
        expandPromptTemplates?: boolean;
    }, deferredTurnClaim?: DeferredTurnClaim, inputOrigin?: InputOrigin): Promise<void>;
    /** Reserve a global order for input temporarily owned outside the native queues. */
    reserveQueuedInputOrder(): number;
    private _recordQueuedInput;
    /** Queued input that a whole turn started after and settled without delivering is overdue: say so (#4036). */
    private _warnQueuedInputOutlivingRun;
    private _mintQueuedId;
    /** A queued input reached a turn: forget its record and remember its id as delivered. */
    private _removeQueuedInput;
    /**
     * Removes one queued input before it reaches a turn, from the visible lists and the native queue alike.
     * An input already drained into a turn answers `already_delivered`.
     */
    dequeueQueuedInput(queuedId: string, options?: QueuedInputChangeOptions): QueuedInputChange;
    /** Replaces the text of one queued input in place, keeping its order and identity, and bumps its revision. */
    editQueuedInput(queuedId: string, text: string, options?: QueuedInputChangeOptions): QueuedInputChange;
    /**
     * Removes (`text` undefined) or edits one queued input. An input in durable custody (admitted with a client id)
     * changes in its record first and in the native queue in the same gated step; any other input changes as
     * `dequeueQueuedInput` / `editQueuedInput` do.
     */
    changeQueuedInput(queuedId: string, text: string | undefined, options?: QueuedInputChangeOptions & {
        readonly effectId?: string;
    }): Promise<QueuedInputChange>;
    private _changeQueuedInput;
    /**
     * Takes every queued cross-session delivery out of the queues unwritten and settles it as `clearQueue` does (its
     * engine custody cancelled, a send waiting on it failed, its admission dropped), leaving user input queued. An
     * interrupt does this once the aborted work settled, so a delivery the aborted run left queued never pins the
     * session; its sender redelivers it (oh-my-openagent#14169).
     */
    takeQueuedDeliveries(): void;
    /**
     * Clear all queued messages and return them. The non-enumerable `ordered`
     * view preserves legacy object equality and native queue semantics.
     * @param options.abortWillFollow Mark a non-empty drain so an immediately following abort can emit session_abort.
     */
    clearQueue(options?: {
        abortWillFollow: boolean;
    }): ClearedQueue;
    /**
     * Settles once the last `clearQueue` is recorded in the pending-input journal. `clearQueue` stays synchronous;
     * a caller that acknowledges the clear (RPC `clear_queue`) awaits this first so its answer is durable.
     */
    whenQueueClearRecorded(): Promise<void>;
    /**
     * Whether a person's input is waiting in the queue: a TUI submit, an RPC client prompt/steer/follow_up or an
     * answered question, tagged when it was enqueued. Decided from the entries actually queued now, so an input
     * that was delivered, dequeued or cleared no longer counts. Extension and engine sends are never a person's.
     */
    get hasQueuedPersonInput(): boolean;
    /** Number of pending messages (includes both steering and follow-up) */
    get pendingMessageCount(): number;
    /** Get pending steering messages (read-only) */
    getSteeringMessages(): readonly string[];
    /** Get pending follow-up messages (read-only) */
    getFollowUpMessages(): readonly string[];
    /** The pending inputs in durable custody, and an explicit outcome for each id the caller already knows. */
    getPendingInputs(knownClientMessageIds?: readonly string[]): Promise<PendingInputSnapshot>;
    getQueuedInputs(): readonly QueuedInput[];
    get resourceLoader(): ResourceLoader;
    /** A user Stop: hold automatic turns until human input or resume_session, then stop the running turn (senpi#3811). */
    stop(): Promise<void>;
    /**
     * Abort current operation and wait for agent to become idle.
     */
    abort(options?: {
        readonly cause?: AgentAbortCause;
    }): Promise<void>;
    private _abortWithProvenance;
    waitForIdle(): Promise<void>;
    private _emitModelSelect;
    /**
     * Set model directly.
     * Validates that auth is configured, saves to session and settings.
     * @throws Error if no auth is configured for the model
     */
    setModel(model: Model<any>, origin?: ModelChangeOrigin): Promise<SystemPromptChangeEvent | undefined>;
    assertModelUsable(model?: Model<Api> | undefined, liveContextTokens?: number, options?: {
        includeSpeculationLead?: boolean;
        admission?: ModelUsabilityAdmission;
    }): void;
    /** Admit an oversized restored transcript so the normal pre-provider compaction can run. */
    /** The switch waiting for the next send to compact for it, if any (#1873). */
    get pendingModelSwitch(): PendingModelSwitch | undefined;
    /**
     * A switch the target cannot hold yet but one compaction would fix. Refusing it
     * discards what the user asked for; committing it strands the session on a model
     * that cannot answer. Holding it does neither: nothing durable is written until
     * the next send has reduced the transcript and the switch actually applies.
     */
    private _projectSwitchDeferral;
    private _admitSwitchCompactionRequired;
    private _clearPendingModelSwitch;
    /**
     * Fit a fallback rung by reducing the transcript without a provider request
     * (#1873). Summarizing is not available here: the model being fallen back from
     * has usually just failed, and the rung itself cannot hold the transcript, so
     * the deterministic slice is the only reduction that can run. The recorded
     * transcript stays intact in the session file.
     */
    private _reduceForSwitchTarget;
    /**
     * Reported tokens per estimated token, never below 1 (senpi#3447): the reported
     * live context when it is above the per-message estimate, the estimate otherwise.
     * A reported figure implausibly above a large estimate (a Cursor cacheRead spike)
     * is ignored, as the compaction threshold already does.
     */
    private _switchTokenScale;
    private _switchContextMessages;
    private _projectSwitchFit;
    /**
     * Repair and apply a held switch, in the one order that works: the model that
     * can still hold the transcript writes the summary, the reduction aims at the
     * window the transcript must end up inside, and only a transcript that actually
     * fits is allowed to carry the switch. The deterministic slice is the floor when
     * summarization did not get there, so a repairable switch cannot strand itself.
     */
    private _applyPendingModelSwitch;
    /** Whether a recorded resume requirement still blocks: the current context does not fit the current model. */
    private _resumeRequirementStillBlocks;
    /** Any committed compaction, manual /compact included, retires a resume requirement the context now satisfies. */
    private _clearResumeCompactionRequirementIfFits;
    admitResumeCompactionRequired(projection: ModelUsabilityBudgetProjection): void;
    /** Reduce an over-window restored context deterministically while the recorded transcript stays intact. */
    applyResumeSlice(plan: ResumeSlicePlan): void;
    private _resumeSliceEvent;
    private _getDownswitchLiveContextTokens;
    /**
     * Set the model for this session without changing the global model defaults.
     * The selection is still persisted in this session's history.
     */
    setSessionModel(model: Model<Api>, origin?: ModelChangeOrigin): Promise<SystemPromptChangeEvent | undefined>;
    /**
     * #1526: every switch guard rejects before `_switchActiveModel` appends its
     * `model_change`, so a refused switch used to leave no entry, no event, and
     * no log line - indistinguishable from a switch the user never attempted.
     * Record the refusal, then rethrow the original error unchanged.
     */
    private _recordRejectedModelChange;
    /**
     * The admission only selects wording, and the switch wording's remedy
     * ("Compact the session, ...") is executable only when there is context to
     * compact. `_setModel` is also reachable from `session_start` (the
     * `recommended-models` builtin switches the model there), so derive the
     * admission from the branch instead of hardcoding a switch: with conversation
     * context this is a switch, on an empty session it is still a cold start.
     */
    private _modelSwitchAdmission;
    /**
     * The single guard seam for a model switch (#1526): every site that can
     * refuse a switch - the `_setModel` pre-flight, the post-`model_select`
     * revalidation in `_switchActiveModel`, and both cycle guards - records the
     * refusal and rethrows the original error unchanged, so no refusal is
     * observable on one path and invisible on its sibling.
     */
    private _assertModelUsableForSwitch;
    private _setModel;
    /**
     * A manual model change takes over a live retry loop (senpi#6893): a pending
     * backoff is cut so the turn continues at once on the picked model with a fresh
     * budget, and a failure still to come from a request already in flight is not
     * charged to the picked model. An explicit abort still cancels the retry.
     */
    private _handOffRetryToManualModel;
    private _maybeRestoreFallbackPrimary;
    /**
     * A senpi-owned compaction just rewrote the conversation context: release any
     * refusal-caused fallback pin (the "same context refuses again" assumption no
     * longer holds) and, while no run is active, eagerly re-attempt the original
     * model through the existing revert gate. Billing-caused pins never release.
     */
    private _onCompactionContextChanged;
    private _switchActiveModel;
    private _applyEphemeralThinkingLevel;
    /**
     * Cycle to next/previous model.
     * Uses favorite models, constrained by any global model narrowing.
     * @param direction - "forward" (default) or "backward"
     * @returns The new model info, or undefined if only one model available
     */
    cycleModel(direction?: "forward" | "backward", options?: {
        readonly persistDefault?: boolean;
        readonly origin?: ModelChangeOrigin;
    }): Promise<ModelCycleResult | undefined>;
    private _cycleFavoriteModel;
    /**
     * Set thinking level.
     * Clamps to model capabilities based on available thinking levels.
     * Refreshes per-model memory, never the startup default; explicit save controls own that setting.
     */
    setThinkingLevel(level: ThinkingLevel, origin?: ModelChangeOrigin): void;
    /**
     * Set the thinking level for this session without changing the global default.
     * The effective level is still persisted in this session's history.
     */
    setSessionThinkingLevel(level: ThinkingLevel, origin?: ModelChangeOrigin): void;
    private _setThinkingLevel;
    private _emitHighReasoningWarningIfNeeded;
    private _emitThinkingClampWarningIfNeeded;
    private _thinkingClampWarningKey;
    /**
     * Cycle to next thinking level.
     * @returns New level, or undefined if model doesn't support thinking
     */
    cycleThinkingLevel(): ThinkingLevel | undefined;
    /**
     * Get available thinking levels for current model.
     * The provider will clamp to what the specific model supports internally.
     */
    getAvailableThinkingLevels(): ThinkingLevel[];
    /**
     * Check if current model supports xhigh thinking level.
     */
    supportsXhighThinking(): boolean;
    /**
     * Check if current model exposes the native "max" adaptive thinking tier
     * (currently Anthropic Opus 4.6 legacy and Opus 4.7 native).
     */
    supportsMaxThinking(): boolean;
    /**
     * Check if current model supports thinking/reasoning.
     */
    supportsThinking(): boolean;
    /**
     * The level a model switch lands on (senpi#3819): a fallback's ephemeral level, else this session's
     * last level for the model, else a favorite's `:level`, else the model's global last-used level,
     * else the model's own default, else the configured default - clamped to what the model supports.
     */
    private _getThinkingForModelSwitch;
    private _clampThinkingLevel;
    private syncQueueModesFromSettings;
    /**
     * Set steering message mode.
     * Saves to settings.
     */
    setSteeringMode(mode: "all" | "one-at-a-time"): void;
    /**
     * Set follow-up message mode.
     * Saves to settings.
     */
    setFollowUpMode(mode: "all" | "one-at-a-time"): void;
    private _claimCompactionController;
    private _ownsCompactionController;
    private _releaseCompactionController;
    private _claimPendingCompactionAdmission;
    private _releasePendingCompactionAdmission;
    private _recordUserAbort;
    private _abortActiveAgentAndRetry;
    /** Generate the built-in summary while preserving fork routing identity and transforms. */
    private _runDefaultCompaction;
    /**
     * Manually compact the session context.
     *
     * This is the manual entry point used by `/compact`, RPC, and extensions. It is
     * separate from automatic threshold/overflow compaction, which enters through
     * `_checkCompaction()` and `_runAutoCompaction()`. After preparation and the
     * `session_before_compact` hook, both paths call the lower-level `compact()`
     * function imported from `./compaction/index.ts`, unless the hook cancels or
     * supplies a custom result.
     *
     * Aborts the current agent operation first. Manual compaction never retries or
     * continues the interrupted agent turn.
     *
     * @param customInstructions Optional instructions for the compaction summary
     */
    compact(customInstructions?: string): Promise<CompactionResult>;
    applyCompaction(precomputed: CompactionResult, options: ApplyCompactionOptions): Promise<ApplyCompactionResult>;
    private _beginExtensionCompactionFeedback;
    private _updateExtensionCompactionFeedback;
    private _endExtensionCompactionFeedback;
    private _executeCompaction;
    private _wouldCompactionOverflow;
    /**
     * Replaces agent state with the canonical session context while keeping exact
     * message objects whose message_end persistence is still queued. Identities
     * already present in the session context are kept from the context only, so
     * nothing is duplicated; the queued message_end still owns exactly-once
     * persistence for the rest.
     */
    private _stripTrailingFailedAssistants;
    private _restoreAgentMessagesFromSession;
    private _rejectCompaction;
    /**
     * Cancel in-progress compaction (manual or auto).
     */
    abortCompaction(): void;
    /**
     * Cancel in-progress branch summarization.
     */
    abortBranchSummary(): void;
    /**
     * A turn needs a selected model whose provider has credentials. Every path that starts a turn checks
     * this before admission, so a first run with no provider reports how to log in instead of failing
     * deeper in compaction or the provider request.
     */
    private _assertModelReadyForTurn;
    /** Shows the provider guidance for a refused background turn once until a turn is admitted again. */
    private _noticeProviderRequired;
    /**
     * Dispatch automatic compaction after `agent_end` or before prompt submission.
     * Manual compaction does not call this method; it enters through `compact()`.
     *
     * Two cases:
     * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
     * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
     *
     * @param assistantMessage The assistant message to check
     * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
     * @returns Whether the post-run loop should call `agent.continue()` for overflow recovery or queued messages
     */
    private _enforceCompactionBeforeProvider;
    /** Share resume's branch provenance rule without projecting trusted usage on every request. */
    private _estimatePrePromptContextTokens;
    /**
     * Pending queued input the provider will also carry on this turn. Steering and
     * follow-up text enqueued after the admission projection was assembled - by a
     * `before_agent_start` handler, an extension action, or the user racing the
     * gate - is drained into the same run, so the final gate must measure it
     * (#7921 case 5).
     */
    private _pendingQueuedInputMessages;
    /**
     * The normal pre-prompt check only estimates persisted session context. This
     * final gate also includes turn-local messages which the provider will see:
     * the current prompt, next-turn custom messages, before_agent_start additions,
     * and steering or follow-up input queued after that projection was assembled.
     * Compaction rewrites only session context, so callers retain and reapply
     * their already-assembled one-shot additions after it succeeds.
     */
    private _enforceFinalProviderAdmission;
    private _checkCompaction;
    /**
     * Whether the automatic compaction that just failed proves the unchanged context cannot be
     * compacted, so the automatic loop must stop re-sending it (#7921 case 6). An external owner
     * and a transient provider failure (senpi#6760) say nothing about the context: latching on
     * them refused every automated send for good, while a later attempt can succeed. Neither does
     * a breaker cooldown rejection, which made no attempt at all. Three consecutive owned failures trip
     * the breaker, deterministic ones included, so this can leave a deterministic failure
     * unlatched for one cooldown (60 s, with #531 cooldown admission). The next real attempt
     * that fails deterministically latches again, and a latch already armed stays armed.
     */
    private _failedCompactionLatchesAdmission;
    private _isCompactionOnCooldown;
    /**
     * Compaction claims are last-writer-wins: a newer admission aborts the
     * incumbent controller (_claimCompactionController). When the failed attempt
     * lost that race, a live claimant now owns the route and re-gates admission
     * itself, so the loser must not surface RequiredCompactionError (issue #886).
     * A user abort leaves no live claimant behind and keeps throwing.
     */
    private _hasSupersedingCompactionClaim;
    private _isCompactionDelegated;
    private _runPrePromptCompaction;
    private _revalidateScheduledContinuationAdmission;
    private _continueAgentAfterCurrentRun;
    /**
     * Mirror _runAutoCompaction's post-success recovery for non-auto compaction
     * owners (manual, extension action, extension apply): a custom triggerTurn
     * message sent while the compaction was running is parked in the agent-level
     * queues without starting a turn, so a settled compaction must deliver it or
     * hidden continuations (e.g. goal) wedge until manual user input.
     */
    private _resumeQueuedMessagesAfterCompaction;
    /** A continuation run has no prompt to reject, so a message write it lost is reported like a failed continuation. */
    private _reportContinuationTranscriptFailure;
    /** Runs input that joined a start which never ran: the transcript tail may be anything, even empty. */
    private _drainJoinedInput;
    private _scheduleContinuationAfterCurrentEvent;
    /**
     * Execute threshold or overflow compaction. Manual compaction uses
     * `AgentSession.compact()` instead. Both paths call the lower-level `compact()`
     * function imported from `./compaction/index.ts` after preparation and extension
     * interception.
     *
     * @param reason Automatic trigger selected by `_checkCompaction()`
     * @param willRetry Whether to continue the interrupted turn after overflow compaction
     * @returns Whether the post-run loop should call `agent.continue()`
     */
    private _runAutoCompaction;
    /**
     * Toggle auto-compaction for this session only. Persisting the flag is a
     * settings-editor concern; a session-level command (RPC `set_auto_compaction`,
     * one thread of a multi-session host) must never rewrite the global setting
     * for every other session on the machine (#1422).
     */
    setAutoCompactionEnabled(enabled: boolean): void;
    /**
     * Compaction settings for a model, defaulting to the session model so per-model
     * token budgets (`compaction.modelOverrides`) apply to every compaction read here.
     * Callers that captured a model before an await pass it explicitly, so a model
     * switch during that await cannot change the budget the operation started with.
     */
    private _getCompactionSettings;
    private _emitSessionSettingsChanged;
    /** Whether auto-compaction is enabled for this session */
    get autoCompactionEnabled(): boolean;
    bindExtensions(bindings: ExtensionBindings): Promise<void>;
    private _beginSessionStartSettlement;
    private extendResourcesFromExtensions;
    private _applyExtensionBindings;
    private _refreshCurrentModelFromRegistry;
    private _bindExtensionCore;
    /** Fallback-chain configuration warnings calculated when this session started. */
    get fallbackValidationWarnings(): readonly string[];
    /** The dispatcher every wrapped tool call and user-bash operation goes through (senpi#3566). */
    get toolDispatcher(): ToolDispatcher;
    private _isBuiltinExtensionPath;
    private _enforceConfiguredDefaultTools;
    private _refreshToolRegistry;
    /**
     * Arm the tool barrier (senpi#3717): until `releaseToolBarrier(id)`, the end of the turn it was armed for,
     * or `deadlineMs`, every tool not declared `workspaceEffect: "read"` waits before it runs.
     */
    armToolBarrier(spec: ToolBarrierSpec): void;
    /** Open the barrier armed under `id`; false (a no-op) when no barrier with that id is armed. */
    releaseToolBarrier(id: string): boolean;
    /** Hold a workspace-changing call while a tool barrier is armed; true when it waited. */
    private _waitForToolBarrier;
    private _buildRuntime;
    reload(options?: {
        beforeSessionStart?: () => void | Promise<void>;
    }): Promise<{
        cancelled: boolean;
        reason?: string;
    }>;
    /**
     * Loads or unloads the project's code after the session's project trust changed (Full access left or
     * re-entered, senpi#3420): rebuilds the runtime exactly like reload(), but nothing can cancel it. No
     * `session_before_reload` handler runs (a project extension must not keep itself loaded); a prompt
     * that is being admitted, or a session start in dispatch, is waited out instead of cancelling, and
     * prompts admitted after that wait for the rebuilt runtime. A reload already in flight sees the trust
     * epoch move and loads again before it installs anything.
     */
    applyProjectTrustChange(): Promise<void>;
    private _notifyAdmissionIdle;
    private _rebuildRuntimeForReload;
    /**
     * Ask extensions whether a full session reload may proceed by emitting the
     * cancellable `session_before_reload` event. `reload()` always consults this
     * gate itself, so a cancelling extension prevents the teardown on every
     * reload path; interactive hosts may additionally pre-check it to warn
     * without starting their reload UI.
     */
    checkReloadVeto(): Promise<{
        cancelled: boolean;
        reason?: string;
    }>;
    /**
     * Check if an error is retryable (overloaded, rate limit, server errors).
     * Context overflow errors are NOT retryable (handled by compaction instead).
     */
    private _isRetryableError;
    /**
     * A failure the agent marked local (the session's journal or file, senpi#3866). The mark is typed and set by
     * where the error came from, never read from its text: the text carries the OS error, which can read like a
     * provider quota (EDQUOT). No model produced it, so it never retries, walks the fallback chain, or marks a
     * model unhealthy.
     */
    private _isLocalFailure;
    private _isCursorPayloadOverflow;
    private _truncateAgentMessagesToLastUserTurn;
    private _isClaudeSdkSessionLockError;
    private _isClaudeSdkInvalidRequestError;
    /**
     * Claude-SDK-only quirks that a provider hop cannot fix: the session.json
     * lock is held by this session's own subprocess, and a bare `invalid_request`
     * from the SDK boundary carries no provider-neutral meaning. Both are scoped
     * to the Claude SDK lane, because the SAME wording from another provider is
     * an ordinary failure whose classification (transient retry, or hard-error
     * fallback) must not change. Provider-agnostic classes - the stream-stall
     * watchdog above all - stay out of this predicate: they already consume the
     * shared same-model budget through `isRetryableAssistantError` and must still
     * escalate to the fallback chain when that budget runs out.
     */
    private _isClaudeSdkSameModelRemintError;
    /**
     * The Claude SDK lane owns its own account pool: an auth miss there is
     * repaired or failed over inside the pool, so hopping to another provider
     * would abandon the user's Claude subscription on a recoverable miss. Every
     * other provider keeps the configured fallback-chain hop. The sign-in-again
     * prompt (senpi#4436) is the same kind of miss: every model on the lane fails
     * it until the user signs in, so it neither retries nor hops.
     */
    private _isClaudeSdkAuthMissError;
    private _isHardErrorFallbackEligible;
    /** Same-model recovery for a request-shape 400: never a model switch (senpi#3727). */
    private _handleRequestShapeRejection;
    private _takeNativeToolSearchInjectionFailure;
    private _getProviderRetryDelayMs;
    /**
     * Retry policy + callbacks shared by compaction and branch-summary summarization calls.
     * Uses the same `settings.retry` budget/backoff as agent-turn retries so a single transient
     * stream drop no longer fails the whole operation. `source` carries the context
     * the TUI needs to render the retry and recreate the underlying indicator.
     */
    private _summarizationRetryCallbacks;
    private _compactionFailureModel;
    /**
     * User-facing text for a turn that is really over. A provider-stream stall
     * or a transport drop carries the classifier's own wording (`Provider stream
     * start timed out after 180000ms ...`, `WebSocket closed 1006 ...`), which
     * the retry engine needs on the message but which explains nothing to the
     * person reading the transcript and names no next step (senpi#1740,
     * senpi#1628). Anything else keeps its error verbatim, minus the internal
     * replay marker.
     */
    private _terminalFailureText;
    /**
     * A 429-class failure with no usable fallback candidate must not fail the
     * turn with zero attempts: a provider answering 429 is asking for a retry.
     * No-hint and tier2 waits degrade to same-model in-turn retries under the
     * normal retry budget (tier2 clamps the hinted wait to the in-turn cap);
     * only tier3 hour-plus waits stay terminal, with the requested wait named
     * in the final error. Returns the in-turn retry delay, or undefined after
     * emitting the terminal auto_retry_end.
     */
    private _degradeRateLimitedWithoutFallback;
    /**
     * Handle retryable errors with exponential backoff.
     * @returns whether retry continuation started, was blocked by compaction, or was not handled
     */
    private _handleRetryableError;
    /**
     * omo#14428: the retry owner gave up on a rate-limited or overloaded provider while input was still queued. The
     * session waits the provider out (the provider's stated delay, else a backoff that grows with each wait and
     * restarts after a run that ends without an error) and then runs the queue, whose own failures retry again. An
     * abort cancels the wait like a retry backoff.
     */
    private _drainQueueAfterProviderBackoff;
    /**
     * The ceiling on one agent-level wait: an explicitly configured `retry.maxAgentDelayMs` wins, then a profile's own
     * override-mode turn ceiling (`null` is explicitly uncapped, as kimi-code declares), then the settings default.
     */
    private _agentDelayCeilingMs;
    /**
     * Cancel in-progress retry.
     */
    abortRetry(): void;
    /**
     * Wait for any in-progress retry to complete.
     * Returns immediately if no retry is in progress.
     */
    private waitForRetry;
    /** Whether auto-retry is currently in progress */
    get isRetrying(): boolean;
    /** Whether auto-retry is enabled */
    get autoRetryEnabled(): boolean;
    /**
     * Toggle auto-retry setting.
     */
    setAutoRetryEnabled(enabled: boolean): void;
    /**
     * Execute a bash command.
     * Adds result to agent context and session.
     * @param command The bash command to execute
     * @param onChunk Optional streaming callback for output
     * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
     * @param options.id Optional identifier included in bash execution update events
     * @param options.operations Custom BashOperations for remote execution
     */
    executeBash(command: string, onChunk?: (chunk: string) => void, options?: {
        excludeFromContext?: boolean;
        id?: string;
        operations?: BashOperations;
    }): Promise<BashResult>;
    /**
     * Record a bash execution result in session history.
     * Used by executeBash and by extensions that handle bash execution themselves.
     */
    recordBashResult(command: string, result: BashResult, options?: {
        excludeFromContext?: boolean;
    }): void;
    /**
     * Cancel running bash command.
     */
    abortBash(): void;
    /** Remove a host-owned full-output spill after a remote observer failed. */
    cleanupBashOutput(path: string): Promise<void>;
    /** Whether a bash command is currently running */
    get isBashRunning(): boolean;
    /** Whether there are pending bash messages waiting to be flushed */
    get hasPendingBashMessages(): boolean;
    /**
     * Flush pending bash messages to agent state and session.
     * Called after agent turn completes to maintain proper message ordering.
     */
    private _flushPendingBashMessages;
    /**
     * Set a display name for the current session.
     */
    setSessionName(name: string): void;
    /**
     * Navigate to a different node in the session tree.
     * Unlike fork() which creates a new session file, this stays in the same file.
     *
     * @param targetId The entry ID to navigate to
     * @param options.intent Select for retry (default), or resume the exact entry without editor text
     * @param options.summarize Whether user wants to summarize abandoned branch
     * @param options.customInstructions Custom instructions for summarizer
     * @param options.replaceInstructions If true, customInstructions replaces the default prompt
     * @param options.label Label to attach to the branch summary entry
     * @returns Result with editorText (if user message) and cancelled status
     */
    navigateTree(targetId: string, options?: TreeNavigationOptions): Promise<{
        editorText?: string;
        cancelled: boolean;
        aborted?: boolean;
        summaryEntry?: BranchSummaryEntry;
    }>;
    /**
     * Start a turn from the current leaf with no new user prompt (senpi #1930): after an edited
     * assistant response becomes the leaf, the model continues from its edited text, delivered as a
     * hidden custom message, never as a trailing assistant message (see continue-from-leaf.ts).
     * Resolves once the runtime took the continuation (its `agent_start`, or a delegated queue into
     * a running turn), like a prompt - NOT after the whole continued turn. Before this it awaited
     * the whole turn, so a desktop continuation longer than the RPC control deadline always timed
     * out (#848 / senpi #2708). Refuses while streaming and on a session with no messages. The turn
     * keeps running in the background after this resolves; a later failure reaches the client as its
     * normal turn error event, not as a reply here.
     */
    continueFromLeaf(): Promise<void>;
    /**
     * Replace an assistant response with an edited copy. The leaf moves to the target's parent and
     * the edited message is appended there as the new leaf, so the original and everything after it
     * are abandoned exactly like a tree navigation (branch summary optional, `session_before_tree`
     * and `session_tree` fire). Unchanged text appends nothing.
     */
    editAssistantMessage(entryId: string, text: string, options?: TreeNavigationOptions): Promise<AssistantEditResult>;
    /**
     * Replace a prompt with an edited copy. The leaf moves to the target's parent and the edited
     * prompt is appended there as the new leaf, so the original and everything after it are
     * abandoned exactly like a tree navigation - this is the `/tree` selection rule of
     * `docs/sessions.md`, with the edited text written into the session instead of into an editor.
     * No turn starts: the new leaf is a prompt with no reply until a caller runs one. Unchanged
     * text appends nothing.
     */
    editUserMessage(entryId: string, text: string, options?: TreeNavigationOptions): Promise<UserEditResult>;
    private _navigateTree;
    /**
     * Get all user messages from session for fork selector.
     */
    getUserMessagesForForking(): Array<{
        entryId: string;
        text: string;
    }>;
    /**
     * Get session statistics. Aggregates over ALL session entries (including
     * history that was compacted away), so token/cost totals reflect what was
     * actually billed across the session.
     */
    getSessionStats(): SessionStats;
    /**
     * Cache-safe foreground wait budget for the LIVE current model. Recomputed on
     * every call so a model switch takes effect immediately.
     */
    resolvePromptCacheSafeWaitSeconds(): number | undefined;
    /**
     * Mirror the budget into the advisory env var read by out-of-process tools.
     * Last writer wins across in-process sessions; consumers treat it as a hint.
     */
    syncPromptCacheSafeWaitEnv(): void;
    /**
     * Context usage is shown on every frame (footer), but it only changes when a message is appended or
     * replaced, the branch moves, or the model changes. Messages are appended in place, so the key is the
     * array, its length and last message (with a fingerprint of its content and usage, in case it grows
     * in place), plus the leaf and the model's window.
     */
    getContextUsage(): ContextUsage | undefined;
    private _contextUsageCache;
    private _computeContextUsage;
    /** The live context in tokens, and whether a provider reported it (otherwise it is a per-message estimate). */
    private _measureContextTokens;
    /**
     * Whether the latest reported usage predates the latest model switch: no
     * assistant message after the switch reported usage, so the last reported
     * figure belongs to the previous model's tokenizer. Assistant messages are
     * appended to the branch only once they stop streaming (a pending assistant
     * message is rejected), so a switch that lands mid-turn still precedes the
     * message entry carrying the new model's usage.
     */
    private _isUsageStaleAfterModelChange;
    /**
     * Export session to HTML.
     * @param outputPath Optional output path (defaults to session directory)
     * @param options Optional export presentation settings
     * @returns Path to exported file
     */
    exportToHtml(outputPath?: string, options?: {
        themeName?: string;
    }): Promise<string>;
    /** Render the session to HTML in memory, passing every value through `sanitize` (used by `/share`). */
    renderToHtml(options: {
        themeName?: string;
        sanitize: <T>(value: T) => T;
    }): string;
    private htmlExportOptions;
    /**
     * Export the current session branch to a JSONL file.
     * Writes the session header followed by all entries on the current branch path.
     * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
     * @returns The resolved output file path.
     */
    exportToJsonl(outputPath?: string): string;
    /**
     * Get text content of last assistant message.
     * Useful for /copy command.
     * @returns Text content, or undefined if no assistant message exists
     */
    getLastAssistantText(): string | undefined;
    createReplacedSessionContext(): ReplacedSessionContext;
    /**
     * Check if extensions have handlers for a specific event type.
     */
    hasExtensionHandlers(eventType: string): boolean;
    /**
     * Get the extension runner (for setting UI context and error handlers).
     */
    get extensionRunner(): ExtensionRunner;
}
//# sourceMappingURL=agent-session.d.ts.map