import type { ContentExclusionServiceHandle } from '../core/sharedApi/runtime-generated';
import type { ContentExclusionServiceHandle as ContentExclusionServiceHandle_2 } from './sharedApi/runtime-generated';
import type { CreateMessageResultWithTools as CreateMessageResultWithTools_2 } from '@modelcontextprotocol/sdk/types.js';
import type { GitHandlerContract } from '../core/sharedApi/runtime-generated';
import type { GitRootResult } from './sharedApi/runtime-generated';
import type { GitWorkingDirectoryContext } from './runtime-generated';
import type { HookSessionLoadResult } from './sharedApi/runtime-generated';
import type { ModelWireChatCompletionMessageCustomToolCall } from './runtime-generated';
import type { ModelWireChatCompletionMessageFunctionToolCall } from './runtime-generated';
import type { ModelWireCustomToolCall } from './runtime-generated';
import type { ModelWireFunctionCall } from './runtime-generated';
import type * as Native from './sharedApi/runtime-generated';
import { NativeHookResourceRow } from './sharedApi/runtime-generated';
import type { NativePathManager } from '../sharedApi/runtime-generated';
import type { NativePermissionService } from '../sharedApi/runtime-generated';
import { NativeProcessorPostToolUseFailureResult } from './sharedApi/runtime-generated';
import type { NativeProcessorProgressMessage } from './sharedApi/runtime-generated';
import type { NativeShellConfig } from '../core/sharedApi/runtime-generated';
import type { NativeToolConfig } from '../core/sharedApi/runtime-generated';
import type { NativeToolMetadata } from '../core/sharedApi/runtime-generated';
import type { NativeUrlManager } from '../sharedApi/runtime-generated';
import { PermissionRequestHooksRunResult } from './sharedApi/runtime-generated';
import type { RepoInstructionSource } from './sharedApi/runtime-generated';
import type { ResponseLimitsStatusResult } from './sharedApi/runtime-generated';
import type { RunnerFileRange } from '../core/sharedApi/runtime-generated';
import type { RunnerLoggerContract } from '../sharedApi/runtime-generated';
import type { RunnerLoggerContract as RunnerLoggerContract_2 } from './sharedApi/runtime-generated';
import type { RunnerLoggerContract as RunnerLoggerContract_3 } from '../core/sharedApi/runtime-generated';
import type { RunnerLogLevel } from './core/sharedApi/runtime-generated';
import type * as RuntimeNative from './runtime-generated';
import type * as RuntimeNative_2 from '../core/sharedApi/runtime-generated';
import type { SandboxConfig as SandboxConfig_2 } from '../core/sharedApi/runtime-generated';
import type { SandboxConfig as SandboxConfig_3 } from './sharedApi/runtime-generated';
import type { SandboxConfig as SandboxConfig_4 } from './runtime-generated';
import type { SandboxRemoteMcpEgress } from '../core/sharedApi/runtime-generated';
import { SandboxRemoteMcpEgress as SandboxRemoteMcpEgress_2 } from './runtime-generated';
import type { SessionFsReverseCall } from '../sharedApi/runtime-generated';
import { ShellContextHandle } from '../core/sharedApi/runtime-generated';
import type { ShellDriverContextHandle } from '../core/sharedApi/runtime-generated';
import { ShellManagerTaskProgress } from '../core/sharedApi/runtime-generated';
import { ShellManagerTrackedTask } from '../core/sharedApi/runtime-generated';
import type { SkillInvocationRecord } from '../core/sharedApi/runtime-generated';
import type { StoredInboxEntryDto } from './sharedApi/runtime-generated';
import type { ToolExecutionResult } from '../core/sharedApi/runtime-generated';

/** Turn abort information including the reason for termination */
export declare interface AbortData {
    /** Finite reason code describing why the current turn was aborted */
    reason: AbortReason;
}

/** Session event "abort". Turn abort information including the reason for termination */
export declare interface AbortEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Turn abort information including the reason for termination */
    data: AbortData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "abort". */
    type: "abort";
}

/** Finite reason code describing why the current turn was aborted */
export declare type AbortReason = "user_initiated" | "remote_command" | "user_abort" | "autopilot_credit_limit";

/** Finite reason code describing why the current turn was aborted */
declare type AbortReason_2 = "user_initiated" | "remote_command" | "user_abort" | "autopilot_credit_limit";

/** Parameters for aborting the current turn */
declare interface AbortRequest {
    /** Finite reason code describing why the current turn was aborted */
    reason?: AbortReason_2;
}

/** Result of aborting the current turn */
declare interface AbortResult {
    /** Error message if the abort failed */
    error?: string;
    /** Whether the abort completed successfully */
    success: boolean;
}

/** Authenticated account entry returned by `account.getAllUsers`, with auth info and an optional associated token. */
declare interface AccountAllUsers {
    /** Authentication information for this user */
    authInfo: AuthInfo_2;
    /** Associated token, if available */
    token?: string;
}

/** Current authentication state */
declare interface AccountGetCurrentAuthResult {
    /** Authentication errors from the last auth attempt, if any */
    authErrors?: string[];
    /** Current authentication information, if authenticated */
    authInfo?: AuthInfo_2;
}

/** Optional GitHub token used to look up quota for a specific user instead of the global auth context. */
declare type AccountGetQuotaRequest = {
    gitHubToken?: string;
};

/** Quota usage snapshots for the resolved user, keyed by quota type. */
declare interface AccountGetQuotaResult {
    /** Quota snapshots keyed by type (e.g., chat, completions, premium_interactions) */
    quotaSnapshots: Record<string, AccountQuotaSnapshot>;
}

/** Credentials to store after successful authentication */
declare interface AccountLoginRequest {
    /** GitHub host URL */
    host: string;
    /** User login/username */
    login: string;
    /** GitHub authentication token */
    token: string;
}

/** Result of a successful login; throws on failure */
declare interface AccountLoginResult {
    /** Whether the credential was persisted to a secure store (system keychain, or the config file when plaintext storage is enabled). False when no secure store was available and the token was not saved, so the consumer can decide how to proceed. */
    storedInVault: boolean;
}

/** User to log out */
declare interface AccountLogoutRequest {
    /** Authentication information for the user to log out */
    authInfo: AuthInfo_2;
}

/** Logout result indicating if more users remain */
declare interface AccountLogoutResult {
    /** Whether other authenticated users remain after logout */
    hasMoreUsers: boolean;
}

/** Quota usage snapshot for a Copilot quota type, including entitlement, used requests, overage, reset date, and remaining percentage. */
declare interface AccountQuotaSnapshot {
    /** Number of requests included in the entitlement, or -1 for unlimited entitlements */
    entitlementRequests: number;
    /** Whether the user has an unlimited usage entitlement */
    isUnlimitedEntitlement: boolean;
    /** Number of additional usage requests made this period */
    overage: number;
    /** Whether additional usage is allowed when quota is exhausted */
    overageAllowedWithExhaustedQuota: boolean;
    /** Percentage of entitlement remaining */
    remainingPercentage: number;
    /** Date when the quota resets (ISO 8601 string) */
    resetDate?: string;
    /** Whether usage is still permitted after quota exhaustion */
    usageAllowedWithExhaustedQuota: boolean;
    /** Number of requests used so far this period */
    usedRequests: number;
}

declare type AcquireArgs = {
    authInfo: AuthInfo;
    integrationId: string;
    sessionId: string;
    logger: RunnerLoggerContract_2;
};

/** Perform an initial `POST /models/session` acquire for auto-mode. */
export declare function acquireAutoModeSession(args: AcquireArgs): Promise<AutoModeSessionResult>;

declare type ActiveToolCall = {
    toolCallId: string;
    name: string;
    arguments?: unknown;
    type?: CopilotChatCompletionMessageToolCall["type"];
};

/**
 * Resolved Anthropic adaptive-thinking capability for a model. This is the
 * runtime's own abstraction over CAPI's single boolean wire field plus the
 * programmatic capability-default switch.
 */
declare type AdaptiveThinkingSupport = "unsupported" | "optional" | "required";

/** Resolved Anthropic adaptive-thinking capability for a model. */
declare type AdaptiveThinkingSupport_2 = "unsupported" | "optional" | "required";

declare type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise<void>;

/**
 * CAPI-delivered flag name that gates agent factories (`run_factory` /
 * `author_factory`). Availability additionally requires a non-PRU (usage-/
 * token-based) billing model — see `nativeRuntime.githubIsAgentFactoriesEnabled`.
 */
export declare const AGENT_FACTORIES_FEATURE_FLAG = "agent_factories";

declare type AgentCallbackCheckQuotaEvent = Record<string, never>;

declare type AgentCallbackCheckQuotaResponse = {
    has_enough_quota: boolean;
};

declare type AgentCallbackCommentReplyEvent = {
    comment_id: number;
    message: string;
};

declare type AgentCallbackErrorEvent = {
    text: string;
    name?: string;
    message?: string;
    stack?: string;
    stdout?: string;
    stderr?: string;
    blockedRequests?: BlockedRequest[];
    request_id?: string;
    ghRequestId?: string;
    serviceRequestId?: string;
    cmd?: string;
    /** Service that originated the error (e.g., "capi", "git") */
    service?: string;
    /** Error code - either from the service (e.g., "429", "hook") or a process exit code */
    code?: number | string;
    signal?: string;
    skipReport?: boolean;
    isVisionFlow?: boolean;
};

declare type AgentCallbackPartialResultEvent = {
    branchName: string;
    message: string;
};

declare type AgentCallbackProgressEvent = (({
    kind: "log";
    message: string;
} | Event_2) & {
    /**
     * Progress events may have telemetry associated with them.
     */
    telemetry?: EventTelemetry;
}) | SubagentSessionBoundary | SessionLoggingDisabledEvent | TelemetryEvent | StreamingDeltaEvent;

declare type AgentCallbackProgressOptions = {
    accepts_user_messages: boolean;
};

declare type AgentCallbackProgressResponse = {
    user_messages: UserMessage[];
};

declare type AgentCallbackResultEvent = {
    diff: string;
    branchName: string;
    prTitle: string;
    prDescription: string;
    blockedRequests?: BlockedRequest[];
};

declare type AgentContext = "cli" | "cca" | "sdk";

declare type AgentDefinition = {
    /** Unique identifier for the agent. Used as the tool name. */
    name: string;
    /** Human-readable display name for UI. */
    displayName: string;
    /** Description of what the agent does. Used in tool description. */
    description: string;
    /** Git commit SHA or version identifier for this agent. */
    version?: string;
    /**
     * Absolute local path to the source agent definition. Present only for
     * file-backed custom agents and used to resolve relative instruction paths.
     */
    sourcePath?: string;
    /**
     * Model to use for this agent. When unset, inherits the outer agent's model.
     * Accepts a single model string or a prioritized list of models. When a list
     * is provided, the first available model that passes all guards (availability,
     * cost tier) is selected. If no model in the list is usable, the agent
     * inherits the outer agent's model.
     *
     * Each entry is a model **selection id**: a bare id (e.g. `claude-sonnet-4.6`)
     * names a Copilot (CAPI) model, while a provider-qualified id (`provider/id`,
     * e.g. `acme/claude-sonnet`) targets a BYOK model from the session's provider
     * registry. A bare id never resolves to a BYOK provider.
     */
    model?: string | string[];
    /**
     * Reasoning effort for this agent (e.g. `"low"`, `"medium"`, `"high"`, `"xhigh"`).
     * When unset, the agent inherits the outer/main agent's reasoning effort.
     * A per-call or `/subagents` override still takes precedence.
     */
    reasoningEffort?: string;
    /**
     * List of tools this agent has access to. Use `["*"]` for all tools. Each entry is an
     * exact tool name (or alias, e.g. `edit`), a bare MCP server name (expands to all of that
     * server's tools), `<server>/*`, or `<server>/<tool>`. The `github` alias resolves to the
     * `github-mcp-server` server.
     */
    tools: string[];
    /**
     * When true, the agent receives only the tools it explicitly lists in `tools`,
     * without the implicit required tools (e.g. `view`) that are otherwise force-added
     * to every custom-agent-as-tool. Use for agents with a deliberately constrained
     * toolset (e.g. the search subagent). Defaults to false. Ignored when `tools` is ["*"].
     */
    strictToolsList?: boolean;
    /** Configuration for which prompt layers to include. */
    promptParts: PromptParts;
    /**
     * The system prompt for this agent.
     * Supports placeholders like {{cwd}}, {{grepToolName}}, {{globToolName}}, and {{shellToolName}}.
     */
    prompt: string;
    /** Optional MCP servers this agent needs. */
    mcpServers?: Record<string, MCPServerConfig>;
    /** List of skill names to preload into this agent's context. When omitted, no skills are preloaded. */
    skills?: string[];
    /**
     * Opt-in to lazy/deferred tool loading even when the agent explicitly lists tools.
     * By default, tools explicitly named in `tools` are eagerly visible to the model.
     * When true, MCP tools the agent lists stay deferred and are discovered via
     * `tool_search_tool` — useful for agents that enumerate many tools but use only a few per turn.
     */
    deferredToolLoading?: boolean;
    /** Runtime contexts where this agent is available. Defaults to all contexts. */
    contexts?: AgentContext[];
    /**
     * Optional sidekick agent configuration. When present, this agent can run as a
     * sidekick agent — launching automatically in the background and publishing
     * context to the session inbox.
     */
    sidekick?: {
        /**
         * Session event types that launch this agent. Each entry is either a
         * bare event-name string (unlimited firing) or an object
         * `{ event, limit? }` giving a per-event fire limit per session.
         *
         * Common events include "user.message" and "session.context_changed".
         * Future trigger types: "session.start", "tool.execution_complete", "assistant.turn_end"
         */
        triggers: SidekickTrigger[];
        /**
         * Session event types to collect as context for the next trigger launch.
         *
         * Important: trigger events are NOT implicitly treated as context. If you
         * want prior trigger occurrences (for example prior user.message turns)
         * to be included as context for later launches, you must explicitly list
         * those event names here.
         *
         * Context events are queued but do not launch the sidekick by themselves.
         */
        contextEvents?: string[];
        /**
         * @deprecated Superseded by {@link behavior}. Accepted purely for parse compatibility
         * with existing/legacy agent definitions; it has **no effect at runtime** — only
         * `behavior` is read. Because `behavior` defaults to "restart", a definition that sets
         * `cancelOnNewTurn: false` without an explicit `behavior` still resolves to "restart".
         * Set `behavior: "persistent"` for long-lived behavior.
         */
        cancelOnNewTurn?: boolean;
        /**
         * How the agent reacts when a new eligible trigger fires while a prior run exists.
         * - "restart" (default): cancel any prior in-flight run and start a fresh single-shot run.
         * - "persistent": keep the same long-lived run alive across triggers; deliver the new
         *   user message into the existing agent loop (waking it if idle, queuing it if mid-turn)
         *   instead of cancelling and relaunching.
         *
         * The sole field consulted at runtime; the deprecated `cancelOnNewTurn` is ignored.
         */
        behavior: "restart" | "persistent";
        /**
         * Maximum inbox entries this agent may send per trigger.
         * In "persistent" mode this is a per-processed-message allowance: each delivered user
         * message the agent begins processing gets a fresh budget of this many sends.
         */
        maxSendsPerTurn: number;
        /** Feature flag that must be enabled for this sidekick agent to run. */
        featureFlag?: string;
        /**
         * Opt-in inline-forwarding threshold, in characters. When set, inbox entries
         * from this agent whose `content` length is at or below this value are forwarded
         * inline in the system notification — the full content is embedded directly and
         * the separate summary + `read_inbox` round-trip is skipped. Entries longer than
         * this value fall back to the summary notification. When omitted, inline
         * forwarding is disabled for this agent (all entries use the summary path).
         *
         * Controls delivery only; the agent still produces a `summary` on `send_inbox`
         * (it is simply unused for inlined entries).
         */
        inlineForwardMaxChars?: number;
        /** Named launch condition functions — agent launches if ANY condition passes (OR semantics).
         *  Conditions run before cancellation — if all fail, the previous run is not cancelled. */
        launchConditions?: string[];
    };
};

/** Canonical directory where custom agents can be discovered or created, with scope, preference, and optional project path. */
declare interface AgentDiscoveryPath {
    /** Absolute path of the search/create directory (may not exist on disk yet) */
    path: string;
    /** Whether this is the canonical directory to create a new agent in its tier. At most one entry per tier is preferred. */
    preferredForCreation: boolean;
    /** The input project path this directory was derived from (only for project scope) */
    projectPath?: string;
    /** Which tier this directory belongs to */
    scope: AgentDiscoveryPathScope;
}

/** Canonical locations where custom agents can be created so the runtime will recognize them. */
declare interface AgentDiscoveryPathList {
    /** Canonical agent create/discovery directories, in priority order */
    paths: AgentDiscoveryPath[];
}

/** Which tier this directory belongs to */
declare type AgentDiscoveryPathScope = "user" | "project";

/**
 * Execution modes for agents.
 * - sync: Run agent synchronously and wait for completion (default)
 * - background: Run agent asynchronously in background, return agent_id immediately
 */
declare type AgentExecutionMode = "sync" | "background";

/**
 * Agent executor dependencies for the task tool.
 * Hides the routing between general-purpose, YAML-based, and user agents
 * behind a single `executeAgent` call.
 *
 * Production code uses {@link createSessionAgentExecutors} to get the real implementation.
 * Tests can provide a lightweight fake.
 */
declare interface AgentExecutors {
    /**
     * Executes an agent of the given type with the provided input.
     * Handles tool filtering and model overrides internally.
     */
    executeAgent: (agentType: string, input: {
        description: string;
        prompt: string;
    }, modelOverride: string | undefined, options: ToolCallbackOptions | undefined, clientOptionOverrides?: ResolvedModel["clientOptionOverrides"], executionOptions?: {
        contextTier?: ContextTier_3;
        autoModeSession?: AutoModeSession;
    }) => Promise<ToolResult | string>;
    /** Executes an internal agent definition without registering a user-invocable agent type. */
    executeDefinition?: (definition: AgentDefinition, input: {
        prompt: string;
    }, modelOverride: string | undefined, options: ToolCallbackOptions | undefined, executionOptions?: {
        contextTier?: ContextTier_3;
        maxAgentTurns?: number;
        lastTurnWarning?: string;
        /**
         * Suppresses the caller's subagent lifecycle hooks
         * (`onSubagentStart` / `onSubagentStop`) for this execution. Internal
         * agents such as the autopilot completion reviewer set this so the
         * session being judged cannot inject context into, block, or rewrite
         * the reviewer's output (which carries its parsed `VERDICT:` line).
         */
        suppressSubagentHooks?: boolean;
    }) => Promise<ToolResult | string>;
    /**
     * Releases any long-lived resources the implementation owns (e.g. cached
     * sessions or handles) and is called once when the task tool tears down.
     * Implementations that only create ephemeral per-invocation state — such as
     * {@link createSessionAgentExecutors} — may leave this a no-op.
     */
    shutdown: () => Promise<void>;
}

/** The currently selected custom agent, or null when using the default agent. */
declare interface AgentGetCurrentResult {
    /** Currently selected custom agent, or null if using the default agent */
    agent: AgentInfo;
}

/** Agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. */
declare interface AgentInfo {
    /** Description of the agent's purpose */
    description: string;
    /** Human-readable display name */
    displayName: string;
    /** Stable identifier for selection. For most agents this is the same as `name`; for plugin/builtin agents it may differ. Always populated; defaults to `name` when no distinct id was assigned. */
    id: string;
    /** MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. */
    mcpServers?: Record<string, unknown>;
    /** Authored preferred model id for this agent. Runtime model selection may choose a different model; omitted means no authored preference. */
    model?: string;
    /** Name of the agent. Use `id` as the stable selection identifier. */
    name: string;
    /** Absolute local file path of the agent definition. Only set for file-based agents loaded from disk; remote agents do not have a path. */
    path?: string;
    /** Authored base prompt for the agent. Runtime prompt assembly may add dynamic context at invocation time. Omitted from `session.agent.list` unless `includePrompt` is true. */
    prompt?: string;
    /** Skill names preloaded into this agent's context. Omitted means none. */
    skills?: string[];
    /** Where the agent definition was loaded from */
    source?: AgentInfoSource;
    /** Allowed tool names for this agent. Empty array means none; omitted means inherit defaults. */
    tools?: string[];
    /** Whether the agent can be selected directly by the user. Agents marked `false` are subagent-only. */
    userInvocable?: boolean;
}

/** Where the agent definition was loaded from */
declare type AgentInfoSource = "user" | "project" | "inherited" | "remote" | "plugin" | "builtin";

/** Agents available to the session. */
declare interface AgentList {
    /** Available agents */
    agents: AgentInfo[];
}

declare interface AgentListOptions {
    /** Scope of the query. "immediate" includes self, direct siblings, and direct children. */
    scope?: AgentVisibilityScope;
    /** Current registry-visible agent id used to compute relation labels. */
    taskRegistryAgentId?: string;
    /** Include non-running agents (default: true). */
    includeCompleted?: boolean;
}

/** Controls whether built-in agents and authored prompt text are included. */
declare type AgentListRequest = {
    includeBuiltInAgents?: boolean;
    includePrompt?: boolean;
};

declare interface AgentLookupOptions {
    /** Scope of the query. "immediate" includes self, direct siblings, and direct children. */
    scope?: AgentVisibilityScope;
    /** Current registry-visible agent id used to compute relation labels. */
    taskRegistryAgentId?: string;
}

declare interface AgentLookupResult {
    task: AgentTaskEntry;
    registry: TaskRegistry;
    relation?: AgentRelation;
}

/**
 * A message sent to a background agent via the write_agent tool.
 */
declare interface AgentMessage {
    /** Unique message identifier */
    id: string;
    /** Agent ID of the sender, if sent by another agent */
    fromAgentId?: string;
    /** Message content */
    content: string;
    /** When the message was sent */
    timestamp: number;
    /** Recipient loop state when the message was accepted. */
    delivery?: UserMessageDelivery;
    /**
     * Optional interaction id associated with this message's turn. Used by
     * persistent sidekick agents to correlate published inbox entries and the
     * per-turn send budget with the user turn that delivered the message.
     */
    interactionId?: string;
}

/**
 * Lightweight progress information for a running background agent.
 * Stored on the registry entry so tools can read current progress directly.
 */
declare interface AgentProgressInfo {
    /** The most recent intent reported by the agent via the session database */
    latestIntent?: string;
    /** Number of tool calls the agent has completed since the agent was started */
    toolCallsCompleted: number;
    /** The resolved model name used by the agent at runtime */
    resolvedModel?: string;
    /** Accumulated input token count across all model calls */
    totalInputTokens: number;
    /** Accumulated output token count across all model calls */
    totalOutputTokens: number;
    /** Executor-provided telemetry for the tool_call_executed event (set before multi-turn idle wait) */
    executorTelemetry?: {
        properties?: Record<string, string>;
        restrictedProperties?: Record<string, string>;
        metrics?: Record<string, number>;
    };
    /**
     * MCP-task-specific data when this agent represents an MCP task created
     * via `tools/call` with task augmentation. Absent for normal subagents.
     */
    mcpTask?: McpTaskInfo;
}

declare interface AgentRecipient {
    agentId: string;
    registry: TaskRegistry;
    task?: AgentTaskEntry;
    relation?: AgentRelation;
}

declare interface AgentRecipientResolution {
    recipients: AgentRecipient[];
    selectionKind: "agent_ids" | "scope";
    scope?: "siblings" | "children";
    errorResult?: unknown;
}

/** Full registry entry for the spawned child. Lets the controller call `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a TOCTOU window). */
declare interface AgentRegistryLiveTargetEntry {
    /** Kind of attention required when status === "attention". Meaningful only when status === "attention". */
    attentionKind?: AgentRegistryLiveTargetEntryAttentionKind;
    /** Git branch of the session (when known) */
    branch?: string;
    /** Copilot CLI version that wrote the entry */
    copilotVersion: string;
    /** Working directory of the session (when known) */
    cwd?: string;
    /** Bind host for the entry's JSON-RPC server */
    host: string;
    /** Process kind tag for the registry entry */
    kind: AgentRegistryLiveTargetEntryKind;
    /** Wall-clock milliseconds since the watcher last observed this entry (heartbeat freshness) */
    lastSeenMs: number;
    /** How the most recent turn ended (clean vs aborted). Lets the renderer distinguish done from done_cancelled. */
    lastTerminalEvent?: AgentRegistryLiveTargetEntryLastTerminalEvent;
    /** Model identifier currently selected for the session */
    model?: string;
    /** Operating-system pid of the process owning this entry */
    pid: number;
    /** TCP port the entry's JSON-RPC server is listening on */
    port: number;
    /** Registry entry schema version (1 = ui-server, 2 = managed-server) */
    schemaVersion: number;
    /** Session ID of the foreground session for this entry */
    sessionId?: string;
    /** Friendly session name (when set) */
    sessionName?: string;
    /** ISO 8601 timestamp captured at registration */
    startedAt: string;
    /** Coarse lifecycle status of the foreground session */
    status?: AgentRegistryLiveTargetEntryStatus;
    /** Monotonic per-publisher revision counter incremented on every status update. Lets watchers detect transient flips. */
    statusRevision?: number;
    /** Connection token (null when the target is unauthenticated) */
    token?: string | null;
}

/** Kind of attention required when status === "attention". Meaningful only when status === "attention". */
declare type AgentRegistryLiveTargetEntryAttentionKind = "error" | "permission" | "exit_plan" | "elicitation" | "user_input";

/** Process kind tag for the registry entry */
declare type AgentRegistryLiveTargetEntryKind = "ui-server" | "managed-server";

/** How the most recent turn ended (clean vs aborted). Lets the renderer distinguish done from done_cancelled. */
declare type AgentRegistryLiveTargetEntryLastTerminalEvent = "turn_end" | "abort";

/** Coarse lifecycle status of the foreground session */
declare type AgentRegistryLiveTargetEntryStatus = "working" | "waiting" | "done" | "attention";

/** Per-spawn log-capture outcome; populated from spawnLiveTarget. */
declare interface AgentRegistryLogCapture {
    /** Whether per-spawn log capture is on (false when env-disabled or open failed) */
    enabled: boolean;
    /** Human-readable open failure message (only set when enabled === false AND the env-disable opt-out was NOT used) */
    openError?: string;
    /** Categorized reason for log-open failure */
    openErrorReason?: AgentRegistryLogCaptureOpenErrorReason;
    /** Absolute path to the per-spawn log file (only set when enabled) */
    path?: string;
}

/** Categorized reason for log-open failure */
declare type AgentRegistryLogCaptureOpenErrorReason = "permission" | "disk_full" | "other";

/** `child_process.spawn` itself failed before the child entered the registry. */
declare interface AgentRegistrySpawnError {
    /** Underlying errno code (e.g. ENOENT, EACCES) when available */
    code?: string;
    /** Discriminator: child_process.spawn itself failed */
    kind: "spawn-error";
    /** Human-readable error message */
    message: string;
}

/** Permission posture for the new session. 'yolo' requires the controller-local session to currently be in allow-all mode. */
declare type AgentRegistrySpawnPermissionMode = "default" | "yolo";

/** Spawn succeeded but the child did not publish a matching managed-server entry within the timeout. */
declare interface AgentRegistrySpawnRegistryTimeout {
    /** Process ID of the orphaned child (so the caller can offer 'kill the pid' guidance) */
    childPid: number;
    /** Discriminator: spawn succeeded but child never registered */
    kind: "registry-timeout";
    /** Per-spawn log-capture outcome; populated from spawnLiveTarget. */
    logCapture?: AgentRegistryLogCapture;
}

/** Inputs to spawn a managed-server child via the controller's spawn delegate. */
declare interface AgentRegistrySpawnRequest {
    /** Custom or built-in agent name (e.g. 'explore'). When omitted, the child uses its own default. */
    agentName?: string;
    /** Working directory for the spawned child (must be an existing directory) */
    cwd: string;
    /** Optional first user message. Forwarded to the caller (the CLI's spawn wrapper sends it post-attach via the standard LocalRpcSession.send path). */
    initialPrompt?: string;
    /** Model identifier to apply to the new session */
    model?: string;
    /** Friendly session name. Must satisfy validateSessionName: non-empty, no leading/trailing whitespace, <=100 chars, no control chars, no double quotes. */
    name?: string;
    /** Permission posture for the new session. 'yolo' requires the controller-local session to currently be in allow-all mode. */
    permissionMode?: AgentRegistrySpawnPermissionMode;
}

/** Outcome of an agentRegistry.spawn call. */
declare type AgentRegistrySpawnResult = AgentRegistrySpawnSpawned | AgentRegistrySpawnError | AgentRegistrySpawnRegistryTimeout | AgentRegistrySpawnValidationError;

/** Managed-server child was spawned and registered successfully. */
declare interface AgentRegistrySpawnSpawned {
    /** Full registry entry for the spawned child. Lets the controller call `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a TOCTOU window). */
    entry: AgentRegistryLiveTargetEntry;
    /** If the delegate attempted to send the initial prompt and failed, the categorized error message. */
    initialPromptError?: string;
    /** Whether the delegate already sent the initial prompt. Always omitted in the current wiring: the controller sends the prompt post-attach via the standard LocalRpcSession.send path. */
    initialPromptSent?: boolean;
    /** Discriminator: managed-server child spawned successfully */
    kind: "spawned";
    /** Per-spawn log-capture outcome; populated from spawnLiveTarget. */
    logCapture?: AgentRegistryLogCapture;
}

/** Synchronous pre-validation rejected the spawn request. */
declare interface AgentRegistrySpawnValidationError {
    /** Which parameter field was invalid. Omitted when the rejection is not field-specific. */
    field?: AgentRegistrySpawnValidationErrorField;
    /** Discriminator: synchronous pre-validation rejected the request */
    kind: "validation-error";
    /** Human-readable explanation; safe to surface in the UI banner. Never logged to unrestricted telemetry. */
    message: string;
    /** Categorized reason for the rejection. Low-cardinality enum so telemetry can aggregate by reason without leaking raw paths or agent/model names. */
    reason: AgentRegistrySpawnValidationErrorReason;
}

/** Which parameter field was invalid. Omitted when the rejection is not field-specific. */
declare type AgentRegistrySpawnValidationErrorField = "cwd" | "name" | "agentName" | "model" | "permissionMode";

/** Categorized reason for the rejection. Low-cardinality enum so telemetry can aggregate by reason without leaking raw paths or agent/model names. */
declare type AgentRegistrySpawnValidationErrorReason = "cwd-not-found" | "cwd-not-directory" | "invalid-name" | "unknown-agent" | "unknown-model" | "yolo-not-allowed";

declare type AgentRelation = "self" | "sibling" | "child";

/** Custom agents available to the session after reloading definitions from disk. */
declare interface AgentReloadResult {
    /** Reloaded custom agents */
    agents: AgentInfo[];
}

/** Optional project paths to include in agent discovery. */
declare interface AgentsDiscoverRequest {
    /** When true, omit the host's agents (the user-level agent directory and all plugin agents), leaving only project and remote agents. For multitenant deployments. */
    excludeHostAgents?: boolean;
    /** Optional list of project directory paths to scan for project-scoped agents. When omitted or empty, only user/plugin/remote-independent agents are returned (no project scan). */
    projectPaths?: string[];
}

/** Name of the custom agent to select for subsequent turns. */
declare interface AgentSelectRequest {
    /** Name of the custom agent to select */
    name: string;
}

/** The newly selected custom agent. */
declare interface AgentSelectResult {
    /** The newly selected custom agent */
    agent: AgentInfo;
}

/** An in-memory authored prompt override for an available agent. */
declare interface AgentSetPromptRequest {
    /** Stable effective agent id. Plugin namespace separators are normalized. */
    id: string;
    /** Replacement authored prompt. Empty text is valid. */
    prompt: string;
}

/** Optional project paths to include when enumerating agent discovery directories. */
declare interface AgentsGetDiscoveryPathsRequest {
    /** When true, omit the host's user-level agent directory, leaving only project directories. For multitenant deployments (mirrors `discover`'s `excludeHostAgents`). */
    excludeHostAgents?: boolean;
    /** Optional list of project directory paths. When omitted or empty, only the user-level directory is returned. */
    projectPaths?: string[];
}

export declare type AgentTask = {
    type: "agent";
    id: string;
    toolCallId: string;
    description: string;
    status: BackgroundTaskStatus;
    startedAt: number;
    completedAt?: number;
    activeTimeMs?: number;
    activeStartedAt?: number;
    error?: string;
    agentType: string;
    prompt: string;
    result?: string;
    modelOverride?: string;
    resolvedModel?: string;
    executionMode?: ShellExecutionMode;
    canPromoteToBackground?: boolean;
    latestResponse?: string;
    idleSince?: number;
    /**
     * Provenance of this task value. `"event-log"` marks a display-only stub
     * reconstructed from a session's bridged event stream (see
     * `getChildSubagentTasks` / `getSubagentTaskTree` in
     * `sharedApi/subagentEvent.ts`) rather than a live entry in the task
     * registry: its `status`, `executionMode`, and elapsed-time fields are
     * synthesized, and it cannot be killed, removed, or promoted because the
     * registry does not know its id. Absence means a real registered
     * background task.
     */
    source?: "event-log";
};

/**
 * A background agent task (subagent running in background mode).
 */
declare type AgentTask_2 = {
    type: "agent";
    id: string;
    /** Tool call ID for correlating session events with this agent. */
    toolCallId: string;
    description: string;
    status: BackgroundTaskStatus_2;
    startedAt: number;
    completedAt?: number;
    /** Accumulated milliseconds the agent has spent actively running (excludes idle time). */
    activeTimeMs?: number;
    /** Timestamp when the current active period began (undefined while idle or finished). */
    activeStartedAt?: number;
    error?: string;
    agentType: string;
    /** Most recent prompt delivered to the agent. Updated whenever the agent receives a follow-up message. */
    prompt: string;
    result?: string;
    modelOverride?: string;
    /** Model resolved by the agent runtime once the first model call is observed */
    resolvedModel?: string;
    /** Whether the agent is currently running synchronously or in background mode. */
    executionMode?: AgentExecutionMode;
    /** Whether the agent can currently be promoted into background mode. */
    canPromoteToBackground?: boolean;
    /** Latest response text from the agent (updated each turn). */
    latestResponse?: string;
    /** Timestamp when the agent entered idle state (undefined while running or finished). */
    idleSince?: number;
};

/** Narrowed entry type for agent tasks. */
declare type AgentTaskEntry = TaskEntryBase & AgentTaskFields;

/**
 * Fields specific to agent tasks.
 */
declare interface AgentTaskFields {
    type: "agent";
    /** The kind of agent (e.g. "explore", "task", "general-purpose") */
    agentType: string;
    /** Tool call ID for correlating session events with this agent */
    toolCallId?: string;
    /** The prompt sent to the agent */
    prompt?: string;
    /** Model override if specified */
    modelOverride?: string;
    /** Factory run that owns this agent, when it was spawned by factory.agent. */
    factoryRunId?: string;
    /** Factory run that owns this task's model usage, inherited across descendants. */
    factoryUsageRunId?: string;
    /** How the agent was started — only background agents receive idle notifications */
    executionMode: AgentExecutionMode;
    /** Result payload on completion */
    result?: unknown;
    /** Error message on failure */
    error?: string;
    /** Queued messages waiting to be processed (multi-turn) */
    messageQueue: AgentMessage[];
    /** Latest response text from the agent (updated each turn) */
    latestResponse?: string;
    /** Whether the latest completion or idle result was already delivered in a notification. */
    notificationResultConsumed?: boolean;
    /** Ordered history of all turn responses */
    turnHistory: AgentTurnResponse[];
    /** Last turn index returned by read_agent's default incremental cursor */
    lastReadTurnIndex?: number;
    /** Number of blocking reads currently waiting to consume this agent's next result */
    activeBlockingReads?: number;
    /** Lightweight progress information for the current run */
    progress?: AgentProgressInfo;
}

export declare type AgentTaskProgress = {
    type: "agent";
    recentActivity: ProgressLine[];
    latestIntent?: string;
};

/**
 * A recorded response from a single agent turn.
 */
declare interface AgentTurnResponse {
    /** 0-based turn index */
    turnIndex: number;
    /** The agent's response text for this turn */
    response: string;
    /** Whether a subagent stop hook explicitly rewrote this response */
    responseWasModified?: boolean;
    /** When this turn completed */
    timestamp: number;
    /** The inbound message that triggered this turn, if any (absent for the initial prompt turn) */
    inboundMessage?: InboundMessageInfo;
}

/**
 * Agent graph query scope.
 *
 * - local: agents in this registry only
 * - self: the current agent
 * - siblings: agents sharing the current agent's parent
 * - children: direct children of the current agent
 * - immediate: self, direct siblings, and direct children
 * - subtree: self and all descendants
 * - all: every agent in the registry tree
 */
declare type AgentVisibilityScope = "local" | "self" | "siblings" | "children" | "immediate" | "subtree" | "all";

/** Indicates whether the operation succeeded and reports the post-mutation state. */
declare interface AllowAllPermissionSetResult {
    /** Authoritative full allow-all state after the mutation */
    enabled: boolean;
    /** Authoritative allow-all mode after the mutation */
    mode?: PermissionsAllowAllMode;
    /** Whether the operation succeeded */
    success: boolean;
}

/** Current allow-all permission mode. */
declare interface AllowAllPermissionState {
    /** Whether full allow-all permissions are currently active */
    enabled: boolean;
    /** Current allow-all mode */
    mode?: PermissionsAllowAllMode;
}

/**
 * Discriminated union of the two concrete `Session` subclasses.
 *
 * Components that need to branch between local and remote sessions should
 * type their session reference as `AnySession` and check `session.isRemote`
 * for natural type narrowing — this avoids `instanceof LocalSession` /
 * `instanceof RemoteSession` checks scattered across the CLI and is the
 * recommended migration target as the runtime moves toward an opaque
 * schema-only public surface.
 */
export declare type AnySession = LocalSession | RemoteSession;

declare type ApiKeyAuthInfo = {
    readonly type: "api-key";
    readonly apiKey: string;
    readonly host: string;
    readonly copilotUser?: CopilotUserResponse;
};

/** Authentication-info variant for API-key authentication to a non-GitHub LLM provider, carrying the secret `apiKey` and host. */
declare interface ApiKeyAuthInfo_2 {
    /** The API key. Treat as a secret. */
    apiKey: string;
    /** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
    copilotUser?: CopilotUserResponse;
    /** Authentication host. */
    host: string;
    /** API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). */
    type: "api-key";
}

/** Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred */
export declare interface AssistantIdleData {
    /** True when the preceding agentic loop was cancelled via abort signal */
    aborted?: boolean;
}

/** Session event "assistant.idle". Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred */
export declare interface AssistantIdleEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload emitted whenever the main agent's processing loop goes idle, including while related background work (running agents or in-flight attached shell commands) is still pending and the session-level idle event is therefore deferred */
    data: AssistantIdleData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.idle". */
    type: "assistant.idle";
}

/** Agent intent description for current activity or plan */
export declare interface AssistantIntentData {
    /** Short description of what the agent is currently doing or planning to do */
    intent: string;
}

/** Session event "assistant.intent". Agent intent description for current activity or plan */
export declare interface AssistantIntentEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Agent intent description for current activity or plan */
    data: AssistantIntentData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.intent". */
    type: "assistant.intent";
}

/** Assistant response containing text content, optional tool requests, and interaction metadata */
export declare interface AssistantMessageData {
    /** Provider's completion / response identifier; shared across all chunks of a single API call. Used to group multi-chunk assistant utterances. */
    apiCallId?: string;
    /** Total messages the model call's response was split into, one per reasoning boundary. Absent for a single-message response; the last chunk is the one where chunkIndex is chunkCount - 1. */
    chunkCount?: number;
    /** Zero-based position of this message within its model call's response. Absent when the response was not split into chunks. */
    chunkIndex?: number;
    /** Provider-agnostic citations linking spans of this message's content to the sources that support them. Experimental; only populated when citation emission is enabled. */
    citations?: Citations;
    /** Client-minted request id (x-request-id header) echoed by the server. Distinct from requestId (x-github-request-id) and serviceRequestId (x-copilot-service-request-id). */
    clientRequestId?: string;
    /** The assistant's text response content */
    content: string;
    /** Encrypted reasoning content from OpenAI models. Session-bound and stripped on resume. */
    encryptedContent?: string;
    /** CAPI interaction ID for correlating this message with upstream telemetry */
    interactionId?: string;
    /** Unique identifier for this assistant message */
    messageId: string;
    /** Model that produced this assistant message, if known */
    model?: string;
    /** Actual output token count from the API response (completion_tokens), used for accurate token accounting */
    outputTokens?: number;
    /**
     * Tool call ID of the parent tool invocation when this event originates from a sub-agent
     * @deprecated
     */
    parentToolCallId?: string;
    /** Generation phase for phased-output models (e.g., thinking vs. response phases) */
    phase?: string;
    /** Opaque/encrypted extended thinking data from Anthropic models. Session-bound and stripped on resume. */
    reasoningOpaque?: string;
    /** Readable reasoning text from the model's extended thinking */
    reasoningText?: string;
    /** OpenAI-compatible wire field the provider used for reasoning (e.g. reasoning_content/reasoning). Populated only when non-canonical, so the dialect round-trips across turns. */
    reasoningWireField?: string;
    /** GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs */
    requestId?: string;
    rte?: boolean;
    /** Neutral provider-tagged server-side tool-use payload (tool search, advisor) for verbatim round-tripping */
    serverTools?: AssistantMessageServerTools;
    /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */
    serviceRequestId?: string;
    /** Tool invocations requested by the assistant in this message */
    toolRequests?: AssistantMessageToolRequest[];
    /** Identifier for the agent loop turn that produced this message, matching the corresponding assistant.turn_start event */
    turnId?: string;
}

/** Streaming assistant message delta for incremental response updates */
export declare interface AssistantMessageDeltaData {
    /** Incremental text chunk to append to the message content */
    deltaContent: string;
    /** Message ID this delta belongs to, matching the corresponding assistant.message event */
    messageId: string;
    /**
     * Tool call ID of the parent tool invocation when this event originates from a sub-agent
     * @deprecated
     */
    parentToolCallId?: string;
}

/** Session event "assistant.message_delta". Streaming assistant message delta for incremental response updates */
export declare interface AssistantMessageDeltaEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Streaming assistant message delta for incremental response updates */
    data: AssistantMessageDeltaData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.message_delta". */
    type: "assistant.message_delta";
}

/** Session event "assistant.message". Assistant response containing text content, optional tool requests, and interaction metadata */
export declare interface AssistantMessageEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Assistant response containing text content, optional tool requests, and interaction metadata */
    data: AssistantMessageData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.message". */
    type: "assistant.message";
}

/**
 * An event that is emitted by the `Client` for each message it receives from the LLM.
 *
 * When the model returns a multi-chunk response (e.g. gpt-5.5 with multiple
 * reasoning items), the client yields one event per chunk. All chunks of one
 * API call share the same `modelCall` and (consequently) the same
 * `modelCall.api_id`; consumers can group by that or by `chunkIndex` /
 * `chunkCount` to recover per-call semantics.
 *
 * Currently does not include telemetry.
 */
declare type AssistantMessageEvent_2 = {
    kind: "message";
    turn?: number;
    callId?: string;
    modelCall?: ModelCallParam;
    message: ChatCompletionMessageParamsWithToolCalls & ReasoningMessageParam_2;
    /**
     * Non-canonical reasoning wire dialect observed inbound (`reasoning_content`
     * / `reasoning`), captured before `cleanUpMessage` strips the breadcrumb.
     * Persisted on the assistant event so the dialect round-trips across turns.
     */
    reasoningWireField?: "reasoning_content" | "reasoning";
    /**
     * Zero-based index of this chunk within its parent API call. Absent (or
     * `0` with `chunkCount === 1`) for single-chunk responses. Consumed by
     * `session.ts` to align the streaming display's chunk-handle array with
     * the per-chunk message-id assignment, and to detect "this is the last
     * chunk" for `outputTokens` attribution.
     */
    chunkIndex?: number;
    /**
     * Total chunks for the parent API call. Absent (or `1`) for single-chunk
     * responses.
     */
    chunkCount?: number;
};

/** Neutral provider-tagged server-side tool-use payload (tool search, advisor) for verbatim round-tripping */
export declare interface AssistantMessageServerTools {
    advisorModel?: string;
    functionCallNamespaces?: Record<string, string>;
    items?: unknown[];
    provider: string;
    rawContentBlocks?: unknown[];
}

/** Streaming assistant message start metadata */
export declare interface AssistantMessageStartData {
    /** Message ID this start event belongs to, matching subsequent deltas and assistant.message */
    messageId: string;
    /** Generation phase this message belongs to for phased-output models */
    phase?: string;
}

/** Session event "assistant.message_start". Streaming assistant message start metadata */
export declare interface AssistantMessageStartEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Streaming assistant message start metadata */
    data: AssistantMessageStartData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.message_start". */
    type: "assistant.message_start";
}

/** A tool invocation request from the assistant */
export declare interface AssistantMessageToolRequest {
    /** Arguments to pass to the tool, format depends on the tool */
    arguments?: unknown;
    /** Resolved intention summary describing what this specific call does */
    intentionSummary?: string | null;
    /** Name of the MCP server hosting this tool, when the tool is an MCP tool */
    mcpServerName?: string;
    /** Original tool name on the MCP server, when the tool is an MCP tool */
    mcpToolName?: string;
    /** Name of the tool being invoked */
    name: string;
    /** Unique identifier for this tool call */
    toolCallId: string;
    /** Human-readable display title for the tool */
    toolTitle?: string;
    /** Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent. */
    type?: AssistantMessageToolRequestType;
}

/** Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent. */
export declare type AssistantMessageToolRequestType = "function" | "custom";

/** Assistant reasoning content for timeline display with complete thinking text */
export declare interface AssistantReasoningData {
    /** The complete extended thinking text from the model */
    content: string;
    /** Unique identifier for this reasoning block */
    reasoningId: string;
    rte?: boolean;
}

/** Streaming reasoning delta for incremental extended thinking updates */
export declare interface AssistantReasoningDeltaData {
    /** Incremental text chunk to append to the reasoning content */
    deltaContent: string;
    /** Reasoning block ID this delta belongs to, matching the corresponding assistant.reasoning event */
    reasoningId: string;
}

/** Session event "assistant.reasoning_delta". Streaming reasoning delta for incremental extended thinking updates */
export declare interface AssistantReasoningDeltaEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Streaming reasoning delta for incremental extended thinking updates */
    data: AssistantReasoningDeltaData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.reasoning_delta". */
    type: "assistant.reasoning_delta";
}

/** Session event "assistant.reasoning". Assistant reasoning content for timeline display with complete thinking text */
export declare interface AssistantReasoningEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Assistant reasoning content for timeline display with complete thinking text */
    data: AssistantReasoningData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.reasoning". */
    type: "assistant.reasoning";
}

/** Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message */
export declare interface AssistantServerToolProgressData {
    /** Kind of hosted server tool that is running. Only `web_search` is emitted today. */
    kind: string;
    /** Position of the hosted tool call in the response output. Stable across the call's lifecycle events (unlike the provider's per-event item id, which CAPI rotates), so the host keys the live in-progress row on it. */
    outputIndex: number;
    /** Lifecycle status of the hosted call: `in_progress`, `searching`, or `completed`. */
    status: string;
}

/** Session event "assistant.server_tool_progress". Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message */
export declare interface AssistantServerToolProgressEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Live progress signal for a provider-hosted server tool (e.g. hosted web search) while it runs, before the finalized serverTools envelope lands on the terminal assistant.message */
    data: AssistantServerToolProgressData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.server_tool_progress". */
    type: "assistant.server_tool_progress";
}

/** Streaming response progress with cumulative byte count */
export declare interface AssistantStreamingDeltaData {
    /** Cumulative total bytes received from the streaming response so far */
    totalResponseSizeBytes: number;
}

/** Session event "assistant.streaming_delta". Streaming response progress with cumulative byte count */
export declare interface AssistantStreamingDeltaEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Streaming response progress with cumulative byte count */
    data: AssistantStreamingDeltaData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.streaming_delta". */
    type: "assistant.streaming_delta";
}

/** Streaming tool-call input delta for incremental tool-call updates */
export declare interface AssistantToolCallDeltaData {
    /** Raw provider tool input fragment to append for this tool call. Function/tool-use providers stream serialized JSON argument text (so newlines inside JSON string values may appear as escaped `\n` until the accumulated JSON is parsed); custom tool calls stream raw custom input. */
    inputDelta: string;
    /** Tool call ID this delta belongs to, matching the corresponding assistant.message tool request */
    toolCallId: string;
    /** Name of the tool being invoked, when known from the stream */
    toolName?: string;
    /** Tool call type, when known from the stream */
    toolType?: AssistantMessageToolRequestType;
}

/** Session event "assistant.tool_call_delta". Streaming tool-call input delta for incremental tool-call updates */
export declare interface AssistantToolCallDeltaEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Streaming tool-call input delta for incremental tool-call updates */
    data: AssistantToolCallDeltaData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.tool_call_delta". */
    type: "assistant.tool_call_delta";
}

/** Turn completion metadata including the turn identifier */
export declare interface AssistantTurnEndData {
    /** Model identifier used for this turn, when known */
    model?: string;
    /** Identifier of the turn that has ended, matching the corresponding assistant.turn_start event */
    turnId: string;
}

/** Session event "assistant.turn_end". Turn completion metadata including the turn identifier */
export declare interface AssistantTurnEndEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Turn completion metadata including the turn identifier */
    data: AssistantTurnEndData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.turn_end". */
    type: "assistant.turn_end";
}

/** Metadata for an additional model inference attempt within an existing assistant turn */
export declare interface AssistantTurnRetryData {
    /** Model identifier used for this retry, when known */
    model?: string;
    /** Provider or runtime classification that caused the retry, when known */
    reason?: string;
    /** Identifier of the turn whose model inference is being retried */
    turnId: string;
}

/** Session event "assistant.turn_retry". Metadata for an additional model inference attempt within an existing assistant turn */
export declare interface AssistantTurnRetryEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Metadata for an additional model inference attempt within an existing assistant turn */
    data: AssistantTurnRetryData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.turn_retry". */
    type: "assistant.turn_retry";
}

/** Turn initialization metadata including identifier and interaction tracking */
export declare interface AssistantTurnStartData {
    /** CAPI interaction ID for correlating this turn with upstream telemetry */
    interactionId?: string;
    /** Model identifier used for this turn, when known */
    model?: string;
    /** Identifier for this turn within the agentic loop, typically a stringified turn number */
    turnId: string;
}

/** Session event "assistant.turn_start". Turn initialization metadata including identifier and interaction tracking */
export declare interface AssistantTurnStartEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Turn initialization metadata including identifier and interaction tracking */
    data: AssistantTurnStartData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.turn_start". */
    type: "assistant.turn_start";
}

/** API endpoint used for this model call, matching CAPI supported_endpoints vocabulary */
export declare type AssistantUsageApiEndpoint = "/chat/completions" | "/v1/messages" | "/responses" | "ws:/responses";

/** Per-request cost and usage data from the CAPI copilot_usage response field */
export declare interface AssistantUsageCopilotUsage {
    /** Itemized token usage breakdown */
    tokenDetails?: AssistantUsageCopilotUsageTokenDetail[];
    /** Total cost in nano-AI units for this request */
    totalNanoAiu: number;
}

/** Token usage detail for a single billing category */
export declare interface AssistantUsageCopilotUsageTokenDetail {
    /** Number of tokens in this billing batch */
    batchSize: number;
    /** Cost per batch of tokens */
    costPerBatch: number;
    /** Total token count for this entry */
    tokenCount: number;
    /** Token category (e.g., "input", "output") */
    tokenType: string;
}

/** LLM API call usage metrics including tokens, costs, quotas, and billing information */
export declare interface AssistantUsageData {
    /** Completion ID from the model provider (e.g., chatcmpl-abc123) */
    apiCallId?: string;
    /** API endpoint used for this model call, matching CAPI supported_endpoints vocabulary */
    apiEndpoint?: AssistantUsageApiEndpoint;
    /** Number of tools available to the model for this call */
    availableToolCount?: number;
    /** Updated prompt-cache expiration for this model call. Present only when the call establishes or refreshes known cache state. */
    cacheExpiresAt?: string;
    /** Number of tokens read from prompt cache */
    cacheReadTokens?: number;
    /** Number of tokens written to prompt cache */
    cacheWriteTokens?: number;
    /** Whether the model response was blocked or truncated by content filtering (finish_reason === 'content_filter'). For Anthropic models this corresponds to a 'refusal' stop reason. */
    contentFilterTriggered?: boolean;
    /** Per-request cost and usage data from the CAPI copilot_usage response field */
    copilotUsage?: AssistantUsageCopilotUsage;
    /** Model multiplier cost for billing purposes */
    cost?: number;
    /** Duration of the API call in milliseconds */
    duration?: number;
    /** Finish reason reported by the model for this API call (e.g. "stop", "length", "tool_calls", "content_filter"). Normalized to OpenAI vocabulary; for Anthropic models a "refusal" stop reason maps to "content_filter". */
    finishReason?: string;
    /** What initiated this API call (e.g., "sub-agent", "mcp-sampling"); absent for user-initiated calls */
    initiator?: string;
    /** Number of input tokens consumed */
    inputTokens?: number;
    /** Average inter-token latency in milliseconds. Only available for streaming requests */
    interTokenLatencyMs?: number;
    /** Coarse classification of the interaction that produced this call, mirroring the session's per-request agent context (e.g. `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, `conversation-user`). Non-billing; lets consumers attribute a model call to a call class (e.g. sub-agent/sidekick) independently of the billing initiator. Absent when the runtime did not classify the request. */
    interactionType?: string;
    /** Model identifier used for this API call */
    model: string;
    /** Number of tool calls returned by the model */
    numToolCalls?: number;
    /** Number of output tokens produced */
    outputTokens?: number;
    /**
     * Parent tool call ID when this usage originates from a sub-agent
     * @deprecated
     */
    parentToolCallId?: string;
    /** GitHub request tracing ID (x-github-request-id header) for server-side log correlation */
    providerCallId?: string;
    /** Per-quota resource usage snapshots, keyed by quota identifier */
    quotaSnapshots?: Record<string, AssistantUsageQuotaSnapshot>;
    /** Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") */
    reasoningEffort?: string;
    /** Number of output tokens used for reasoning (e.g., chain-of-thought) */
    reasoningTokens?: number;
    rte?: boolean;
    /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */
    serviceRequestId?: string;
    /** Time to first token in milliseconds. Only available for streaming requests */
    timeToFirstTokenMs?: number;
    /** Tool-call counts keyed by tool name */
    toolCounts?: Record<string, number>;
    /** Number of tokens used by tool definitions for this call */
    toolTokenCount?: number;
}

/** Session event "assistant.usage". LLM API call usage metrics including tokens, costs, quotas, and billing information */
export declare interface AssistantUsageEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** LLM API call usage metrics including tokens, costs, quotas, and billing information */
    data: AssistantUsageData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "assistant.usage". */
    type: "assistant.usage";
}

/** Privacy-minimal model usage for one assistant API call. */
declare interface AssistantUsageEventRow {
    session_id: string;
    turn_index?: number;
    agent_id?: string;
    parent_tool_call_id?: string;
    model: string;
    input_tokens?: number;
    output_tokens?: number;
    cache_read_tokens?: number;
    cache_write_tokens?: number;
    reasoning_tokens?: number;
    total_nano_aiu?: number;
    request_multiplier?: number;
    duration_ms?: number;
    time_to_first_token_ms?: number;
    inter_token_latency_ms?: number;
    initiator?: string;
    api_endpoint?: string;
    reasoning_effort?: string;
    finish_reason?: string;
    content_filter_triggered?: boolean;
    token_details_json?: string;
    created_at?: string;
}

/** Internal per-quota snapshot for assistant usage, including entitlement, consumed requests, overage, reset date, and remaining quota. */
export declare interface AssistantUsageQuotaSnapshot {
    /** Total requests allowed by the entitlement */
    entitlementRequests: number;
    /** Whether the user currently has quota available for use */
    hasQuota?: boolean;
    /** Whether the user has an unlimited usage entitlement */
    isUnlimitedEntitlement: boolean;
    /** Number of additional usage requests made this period */
    overage: number;
    /** Whether additional usage is allowed when quota is exhausted */
    overageAllowedWithExhaustedQuota: boolean;
    /** Pay-as-you-go additional-usage budget cap in AI credits (1 credit = $0.01); present only when CAPI emits a finite value */
    overageEntitlement?: number;
    /** Percentage of quota remaining (0 to 100) */
    remainingPercentage: number;
    /** Date when the quota resets */
    resetDate?: string;
    /** Whether this snapshot uses token-based billing (AI-credits allocation) */
    tokenBasedBilling?: boolean;
    /** Whether usage is still permitted after quota exhaustion */
    usageAllowedWithExhaustedQuota: boolean;
    /** Number of requests already consumed */
    usedRequests: number;
}

/** A user message attachment — a file, directory, code selection, blob, GitHub reference, GitHub-anchored pointer, or extension-supplied context payload */
export declare type Attachment = AttachmentFile | AttachmentDirectory | AttachmentSelection | AttachmentGitHubReference | AttachmentGitHubCommit | AttachmentGitHubRelease | AttachmentGitHubActionsJob | AttachmentGitHubRepository | AttachmentGitHubFileDiff | AttachmentGitHubTreeComparison | AttachmentGitHubUrl | AttachmentGitHubFile | AttachmentGitHubSnippet | AttachmentBlob | AttachmentExtensionContext;

/** A user message attachment — a file, directory, code selection, blob, GitHub-anchored pointer, or extension-supplied context payload */
declare type Attachment_2 = AttachmentFile_2 | AttachmentDirectory_2 | AttachmentSelection_2 | AttachmentGitHubReference_2 | AttachmentGitHubCommit_2 | AttachmentGitHubRelease_2 | AttachmentGitHubActionsJob_2 | AttachmentGitHubRepository_2 | AttachmentGitHubFileDiff_2 | AttachmentGitHubTreeComparison_2 | AttachmentGitHubUrl_2 | AttachmentGitHubFile_2 | AttachmentGitHubSnippet_2 | AttachmentBlob_2 | AttachmentExtensionContext_2;

/** Blob attachment with inline base64-encoded data */
declare interface AttachmentBlob {
    /** Internal: content-addressed id of the session.binary_asset event holding this attachment's model-facing bytes (e.g. "sha256:..."). Absent externally. */
    assetId?: string;
    /** Internal: decoded byte length of the attachment's model-facing bytes. Absent externally. */
    byteLength?: number;
    /** Base64-encoded content. Present on input and for external consumers; replaced by an internal `assetId` reference in persisted events when interned to a content-addressed asset. */
    data?: string;
    /** User-facing display name for the attachment */
    displayName?: string;
    /** MIME type of the inline data */
    mimeType: string;
    /** Internal: why model-facing bytes are absent from persistence. Absent externally. */
    omittedReason?: OmittedBinaryOmittedReason;
    /** Attachment type discriminator */
    type: "blob";
}
export { AttachmentBlob }
export { AttachmentBlob as BlobAttachment }

/** Blob attachment with inline base64-encoded data */
declare interface AttachmentBlob_2 {
    /** Internal: content-addressed id of the session.binary_asset event holding this attachment's model-facing bytes (e.g. "sha256:..."). Absent externally. */
    assetId?: string;
    /** Internal: decoded byte length of the attachment's model-facing bytes. Absent externally. */
    byteLength?: number;
    /** Base64-encoded content. Present on input and for external consumers; replaced by an internal `assetId` reference in persisted events when interned to a content-addressed asset. */
    data?: string;
    /** User-facing display name for the attachment */
    displayName?: string;
    /** MIME type of the inline data */
    mimeType: string;
    /** Internal: why model-facing bytes are absent from persistence. Absent externally. */
    omittedReason?: OmittedBinaryOmittedReason_2;
    /** Attachment type discriminator */
    type: "blob";
}

/** Directory attachment */
declare interface AttachmentDirectory {
    /** User-facing display name for the attachment */
    displayName: string;
    /** Absolute directory path */
    path: string;
    /** Frozen rendered line this attachment contributed to the <tagged_files> prompt block (e.g. "* /path (12 items)"). Captured at send time so resumed history reproduces the exact text the model saw, independent of later filesystem changes. */
    taggedFilesEntry?: string;
    /** Attachment type discriminator */
    type: "directory";
}
export { AttachmentDirectory }
export { AttachmentDirectory as DirectoryAttachment }

/** Directory attachment */
declare interface AttachmentDirectory_2 {
    /** User-facing display name for the attachment */
    displayName: string;
    /** Absolute directory path */
    path: string;
    /** Frozen rendered line this attachment contributed to the <tagged_files> prompt block (e.g. "* /path (12 items)"). Captured at send time so resumed history reproduces the exact text the model saw, independent of later filesystem changes. */
    taggedFilesEntry?: string;
    /** Attachment type discriminator */
    type: "directory";
}

/** Structured context contributed by an extension. Composer pills displayed in the host are forwarded back through session.send.attachments, then rendered into the model prompt as an <extension_context> XML block. */
declare interface AttachmentExtensionContext {
    /** Provider-local canvas identifier when the push was bound to a canvas instance */
    canvasId?: string;
    /** ISO 8601 timestamp captured by the runtime when the push was accepted */
    capturedAt: string;
    /** Owning extension identifier. Runtime-derived from the caller's connection when produced via session.extensions.sendAttachmentsToMessage; preserved verbatim on subsequent transports. */
    extensionId: string;
    /** Open canvas instance identifier when the push was bound to a canvas instance */
    instanceId?: string;
    /** Caller-supplied JSON payload */
    payload?: unknown;
    /** Human-readable composer pill label */
    title: string;
    /** Attachment type discriminator */
    type: "extension_context";
}
export { AttachmentExtensionContext }
export { AttachmentExtensionContext as ExtensionContextAttachment }

/** Structured context contributed by an extension. Composer pills displayed in the host are forwarded back through session.send.attachments, then rendered into the model prompt as an <extension_context> XML block. */
declare interface AttachmentExtensionContext_2 {
    /** Provider-local canvas identifier when the push was bound to a canvas instance */
    canvasId?: string;
    /** ISO 8601 timestamp captured by the runtime when the push was accepted */
    capturedAt: string;
    /** Owning extension identifier. Runtime-derived from the caller's connection when produced via session.extensions.sendAttachmentsToMessage; preserved verbatim on subsequent transports. */
    extensionId: string;
    /** Open canvas instance identifier when the push was bound to a canvas instance */
    instanceId?: string;
    /** Caller-supplied JSON payload */
    payload?: unknown;
    /** Human-readable composer pill label */
    title: string;
    /** Attachment type discriminator */
    type: "extension_context";
}

/** File attachment */
declare interface AttachmentFile {
    /** Internal: content-addressed id of the session.binary_asset event holding this attachment's model-facing bytes (e.g. "sha256:..."). Absent externally. */
    assetId?: string;
    /** Internal: decoded byte length of the attachment's model-facing bytes. Absent externally. */
    byteLength?: number;
    /** User-facing display name for the attachment */
    displayName: string;
    /** Optional line range to scope the attachment to a specific section of the file */
    lineRange?: AttachmentFileLineRange;
    /** Internal: MIME type of the file's model-facing bytes (post-resize for images). Set when the file's bytes are interned to an asset. Absent externally. */
    mimeType?: string;
    /** Internal: why model-facing bytes are absent from persistence. Absent externally. */
    omittedReason?: OmittedBinaryOmittedReason;
    /** Absolute file path */
    path: string;
    /** Frozen rendered line this attachment contributed to the <tagged_files> prompt block (e.g. "* /path (123 lines)"). Captured at send time so resumed history reproduces the exact text the model saw, independent of later filesystem changes. Present only for attachments routed to <tagged_files> (mutually exclusive with assetId, which marks bytes sent natively). */
    taggedFilesEntry?: string;
    /** Attachment type discriminator */
    type: "file";
}
export { AttachmentFile }
export { AttachmentFile as FileAttachment }

/** File attachment */
declare interface AttachmentFile_2 {
    /** Internal: content-addressed id of the session.binary_asset event holding this attachment's model-facing bytes (e.g. "sha256:..."). Absent externally. */
    assetId?: string;
    /** Internal: decoded byte length of the attachment's model-facing bytes. Absent externally. */
    byteLength?: number;
    /** User-facing display name for the attachment */
    displayName: string;
    /** Optional line range to scope the attachment to a specific section of the file */
    lineRange?: AttachmentFileLineRange_2;
    /** Internal: MIME type of the file's model-facing bytes (post-resize for images). Set when the file's bytes are interned to an asset. Absent externally. */
    mimeType?: string;
    /** Internal: why model-facing bytes are absent from persistence. Absent externally. */
    omittedReason?: OmittedBinaryOmittedReason_2;
    /** Absolute file path */
    path: string;
    /** Frozen rendered line this attachment contributed to the <tagged_files> prompt block (e.g. "* /path (123 lines)"). Captured at send time so resumed history reproduces the exact text the model saw, independent of later filesystem changes. Present only for attachments routed to <tagged_files> (mutually exclusive with assetId, which marks bytes sent natively). */
    taggedFilesEntry?: string;
    /** Attachment type discriminator */
    type: "file";
}

/** Optional line range to scope the attachment to a specific section of the file */
export declare interface AttachmentFileLineRange {
    /** End line number (1-based, inclusive) */
    end: number;
    /** Start line number (1-based) */
    start: number;
}

/** Optional line range to scope the attachment to a specific section of the file */
declare interface AttachmentFileLineRange_2 {
    /** End line number (1-based, inclusive) */
    end: number;
    /** Start line number (1-based) */
    start: number;
}

/** Pointer to a GitHub Actions job. */
declare interface AttachmentGitHubActionsJob {
    /** Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. */
    conclusion?: string;
    /** Job id within the workflow run */
    jobId: number;
    /** Display name of the job */
    jobName: string;
    /** Repository the workflow run belongs to */
    repo: GitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_actions_job";
    /** URL to the job on GitHub */
    url: string;
    /** Display name of the workflow the job ran in */
    workflowName: string;
}
export { AttachmentGitHubActionsJob }
export { AttachmentGitHubActionsJob as GitHubActionsJobAttachment }

/** Pointer to a GitHub Actions job. */
declare interface AttachmentGitHubActionsJob_2 {
    /** Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. */
    conclusion?: string;
    /** Job id within the workflow run */
    jobId: number;
    /** Display name of the job */
    jobName: string;
    /** Repository the workflow run belongs to */
    repo: GitHubRepoRef_2;
    /** Attachment type discriminator */
    type: "github_actions_job";
    /** URL to the job on GitHub */
    url: string;
    /** Display name of the workflow the job ran in */
    workflowName: string;
}

/** Pointer to a GitHub commit. */
declare interface AttachmentGitHubCommit {
    /** First line of the commit message */
    message: string;
    /** Full commit SHA */
    oid: string;
    /** Repository the commit belongs to */
    repo: GitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_commit";
    /** URL to the commit on GitHub */
    url: string;
}
export { AttachmentGitHubCommit }
export { AttachmentGitHubCommit as GitHubCommitAttachment }

/** Pointer to a GitHub commit. */
declare interface AttachmentGitHubCommit_2 {
    /** First line of the commit message */
    message: string;
    /** Full commit SHA */
    oid: string;
    /** Repository the commit belongs to */
    repo: GitHubRepoRef_2;
    /** Attachment type discriminator */
    type: "github_commit";
    /** URL to the commit on GitHub */
    url: string;
}

/** Pointer to a file in a GitHub repository at a specific ref. */
declare interface AttachmentGitHubFile {
    /** Repository-relative path to the file */
    path: string;
    /** Git ref the file is read at (branch, tag, or commit SHA) */
    ref: string;
    /** Repository the file lives in */
    repo: GitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_file";
    /** URL to the file on GitHub */
    url: string;
}
export { AttachmentGitHubFile }
export { AttachmentGitHubFile as GitHubFileAttachment }

/** Pointer to a file in a GitHub repository at a specific ref. */
declare interface AttachmentGitHubFile_2 {
    /** Repository-relative path to the file */
    path: string;
    /** Git ref the file is read at (branch, tag, or commit SHA) */
    ref: string;
    /** Repository the file lives in */
    repo: GitHubRepoRef_2;
    /** Attachment type discriminator */
    type: "github_file";
    /** URL to the file on GitHub */
    url: string;
}

/** Pointer to a single-file diff. At least one of `head` and `base` must be present. */
declare interface AttachmentGitHubFileDiff {
    /** File location on the base side of the diff. Absent for additions. */
    base?: AttachmentGitHubFileDiffSide;
    /** File location on the head side of the diff. Absent for deletions. */
    head?: AttachmentGitHubFileDiffSide;
    /** Attachment type discriminator */
    type: "github_file_diff";
    /** URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) */
    url: string;
}
export { AttachmentGitHubFileDiff }
export { AttachmentGitHubFileDiff as GitHubFileDiffAttachment }

/** Pointer to a single-file diff. At least one of `head` and `base` must be present. */
declare interface AttachmentGitHubFileDiff_2 {
    /** File location on the base side of the diff. Absent for additions. */
    base?: AttachmentGitHubFileDiffSide_2;
    /** File location on the head side of the diff. Absent for deletions. */
    head?: AttachmentGitHubFileDiffSide_2;
    /** Attachment type discriminator */
    type: "github_file_diff";
    /** URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) */
    url: string;
}

/** One side of a file diff (head or base) */
export declare interface AttachmentGitHubFileDiffSide {
    /** Repository-relative path to the file */
    path: string;
    /** Git ref (branch, tag, or commit SHA) the file is read at */
    ref: string;
    /** Repository the file lives in */
    repo: GitHubRepoRef;
}

/** One side of a file diff (head or base) */
declare interface AttachmentGitHubFileDiffSide_2 {
    /** Repository-relative path to the file */
    path: string;
    /** Git ref (branch, tag, or commit SHA) the file is read at */
    ref: string;
    /** Repository the file lives in */
    repo: GitHubRepoRef_2;
}

/** GitHub issue, pull request, or discussion reference */
declare interface AttachmentGitHubReference {
    /** Issue, pull request, or discussion number */
    number: number;
    /** Type of GitHub reference */
    referenceType: AttachmentGitHubReferenceType;
    /** Current state of the referenced item (e.g., open, closed, merged) */
    state: string;
    /** Title of the referenced item */
    title: string;
    /** Attachment type discriminator */
    type: "github_reference";
    /** URL to the referenced item on GitHub */
    url: string;
}
export { AttachmentGitHubReference }
export { AttachmentGitHubReference as GitHubReferenceAttachment }

/** GitHub issue, pull request, or discussion reference */
declare interface AttachmentGitHubReference_2 {
    /** Issue, pull request, or discussion number */
    number: number;
    /** Type of GitHub reference */
    referenceType: AttachmentGitHubReferenceType_2;
    /** Current state of the referenced item (e.g., open, closed, merged) */
    state: string;
    /** Title of the referenced item */
    title: string;
    /** Attachment type discriminator */
    type: "github_reference";
    /** URL to the referenced item on GitHub */
    url: string;
}

/** Type of GitHub reference */
export declare type AttachmentGitHubReferenceType = "issue" | "pr" | "discussion";

/** Type of GitHub reference */
declare type AttachmentGitHubReferenceType_2 = "issue" | "pr" | "discussion";

/** Pointer to a GitHub release. */
declare interface AttachmentGitHubRelease {
    /** Human-readable release name */
    name: string;
    /** Repository the release belongs to */
    repo: GitHubRepoRef;
    /** Git tag the release is anchored to */
    tagName: string;
    /** Attachment type discriminator */
    type: "github_release";
    /** URL to the release on GitHub */
    url: string;
}
export { AttachmentGitHubRelease }
export { AttachmentGitHubRelease as GitHubReleaseAttachment }

/** Pointer to a GitHub release. */
declare interface AttachmentGitHubRelease_2 {
    /** Human-readable release name */
    name: string;
    /** Repository the release belongs to */
    repo: GitHubRepoRef_2;
    /** Git tag the release is anchored to */
    tagName: string;
    /** Attachment type discriminator */
    type: "github_release";
    /** URL to the release on GitHub */
    url: string;
}

/** Pointer to a GitHub repository. */
declare interface AttachmentGitHubRepository {
    /** Short description of the repository */
    description?: string;
    /** Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. */
    ref?: string;
    /** Repository pointer */
    repo: GitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_repository";
    /** URL to the repository on GitHub */
    url: string;
}
export { AttachmentGitHubRepository }
export { AttachmentGitHubRepository as GitHubRepositoryAttachment }

/** Pointer to a GitHub repository. */
declare interface AttachmentGitHubRepository_2 {
    /** Short description of the repository */
    description?: string;
    /** Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. */
    ref?: string;
    /** Repository pointer */
    repo: GitHubRepoRef_2;
    /** Attachment type discriminator */
    type: "github_repository";
    /** URL to the repository on GitHub */
    url: string;
}

/** Pointer to a line range inside a file in a GitHub repository. */
declare interface AttachmentGitHubSnippet {
    /** Line range the snippet covers */
    lineRange: AttachmentFileLineRange;
    /** Repository-relative path to the file */
    path: string;
    /** Git ref the file is read at (branch, tag, or commit SHA) */
    ref: string;
    /** Repository the file lives in */
    repo: GitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_snippet";
    /** URL to the snippet on GitHub (with line anchor) */
    url: string;
}
export { AttachmentGitHubSnippet }
export { AttachmentGitHubSnippet as GitHubSnippetAttachment }

/** Pointer to a line range inside a file in a GitHub repository. */
declare interface AttachmentGitHubSnippet_2 {
    /** Line range the snippet covers */
    lineRange: AttachmentFileLineRange_2;
    /** Repository-relative path to the file */
    path: string;
    /** Git ref the file is read at (branch, tag, or commit SHA) */
    ref: string;
    /** Repository the file lives in */
    repo: GitHubRepoRef_2;
    /** Attachment type discriminator */
    type: "github_snippet";
    /** URL to the snippet on GitHub (with line anchor) */
    url: string;
}

/** Pointer to a comparison between two git revisions. */
declare interface AttachmentGitHubTreeComparison {
    /** Base side of the comparison */
    base: AttachmentGitHubTreeComparisonSide;
    /** Head side of the comparison */
    head: AttachmentGitHubTreeComparisonSide;
    /** Attachment type discriminator */
    type: "github_tree_comparison";
    /** URL to the comparison on GitHub */
    url: string;
}
export { AttachmentGitHubTreeComparison }
export { AttachmentGitHubTreeComparison as GitHubTreeComparisonAttachment }

/** Pointer to a comparison between two git revisions. */
declare interface AttachmentGitHubTreeComparison_2 {
    /** Base side of the comparison */
    base: AttachmentGitHubTreeComparisonSide_2;
    /** Head side of the comparison */
    head: AttachmentGitHubTreeComparisonSide_2;
    /** Attachment type discriminator */
    type: "github_tree_comparison";
    /** URL to the comparison on GitHub */
    url: string;
}

/** One side of a tree comparison (head or base) */
export declare interface AttachmentGitHubTreeComparisonSide {
    /** Repository the revision belongs to */
    repo: GitHubRepoRef;
    /** Git revision (branch, tag, or commit SHA) */
    revision: string;
}

/** One side of a tree comparison (head or base) */
declare interface AttachmentGitHubTreeComparisonSide_2 {
    /** Repository the revision belongs to */
    repo: GitHubRepoRef_2;
    /** Git revision (branch, tag, or commit SHA) */
    revision: string;
}

/** Generic GitHub URL reference. */
declare interface AttachmentGitHubUrl {
    /** Attachment type discriminator */
    type: "github_url";
    /** URL to the GitHub resource */
    url: string;
}
export { AttachmentGitHubUrl }
export { AttachmentGitHubUrl as GitHubUrlAttachment }

/** Generic GitHub URL reference. */
declare interface AttachmentGitHubUrl_2 {
    /** Attachment type discriminator */
    type: "github_url";
    /** URL to the GitHub resource */
    url: string;
}

/** Code selection attachment from an editor */
declare interface AttachmentSelection {
    /** User-facing display name for the selection */
    displayName: string;
    /** Absolute path to the file containing the selection */
    filePath: string;
    /** Position range of the selection within the file */
    selection: AttachmentSelectionDetails;
    /** The selected text content */
    text: string;
    /** Attachment type discriminator */
    type: "selection";
}
export { AttachmentSelection }
export { AttachmentSelection as SelectionAttachment }

/** Code selection attachment from an editor */
declare interface AttachmentSelection_2 {
    /** User-facing display name for the selection */
    displayName: string;
    /** Absolute path to the file containing the selection */
    filePath: string;
    /** Position range of the selection within the file */
    selection: AttachmentSelectionDetails_2;
    /** The selected text content */
    text: string;
    /** Attachment type discriminator */
    type: "selection";
}

/** Position range of the selection within the file */
export declare interface AttachmentSelectionDetails {
    /** End position of the selection */
    end: AttachmentSelectionDetailsEnd;
    /** Start position of the selection */
    start: AttachmentSelectionDetailsStart;
}

/** Position range of the selection within the file */
declare interface AttachmentSelectionDetails_2 {
    /** End position of the selection */
    end: AttachmentSelectionDetailsEnd_2;
    /** Start position of the selection */
    start: AttachmentSelectionDetailsStart_2;
}

/** End position of the selection */
export declare interface AttachmentSelectionDetailsEnd {
    /** End character offset within the line (0-based) */
    character: number;
    /** End line number (0-based) */
    line: number;
}

/** End position of the selection */
declare interface AttachmentSelectionDetailsEnd_2 {
    /** End character offset within the line (0-based) */
    character: number;
    /** End line number (0-based) */
    line: number;
}

/** Start position of the selection */
export declare interface AttachmentSelectionDetailsStart {
    /** Start character offset within the line (0-based) */
    character: number;
    /** Start line number (0-based) */
    line: number;
}

/** Start position of the selection */
declare interface AttachmentSelectionDetailsStart_2 {
    /** Start character offset within the line (0-based) */
    character: number;
    /** Start line number (0-based) */
    line: number;
}

declare interface AudioContent_2 extends BaseContentBlock {
    type: "audio";
    data: string;
    mimeType: string;
}

declare type AuthCallback = (authInfo: AuthInfo | null, token?: string) => void | Promise<void>;

declare interface AuthChangeOptions {
    /** When false, skips the initial invocation with the current auth state. Defaults to true. */
    immediate?: boolean;
}

declare type AuthFailedHeadersRefreshParams = HeadersRefreshParams;

/**
 * Represents the authentication information for a user.
 */
declare type AuthInfo = HMACAuthInfo | EnvAuthInfo | UserAuthInfo | GhCliAuthInfo | ApiKeyAuthInfo | TokenAuthInfo | CopilotApiTokenAuthInfo;

/** Initial authentication info for the session. */
declare type AuthInfo_2 = HMACAuthInfo_2 | EnvAuthInfo_2 | TokenAuthInfo_2 | CopilotApiTokenAuthInfo_2 | UserAuthInfo_2 | GhCliAuthInfo_2 | ApiKeyAuthInfo_2;

/** Authentication type */
declare type AuthInfoType = "hmac" | "env" | "user" | "gh-cli" | "api-key" | "token" | "copilot-api-token";

/**
 * Authentication information along with an optional token.
 */
declare type AuthInfoWithToken = {
    authInfo: AuthInfo;
    token?: string;
};

declare class AuthManager {
    private readonly rustHandle;
    private readonly authCallbackDisposers;
    constructor(_featureFlags?: FeatureFlags, config?: AuthManagerConfig);
    /** Release the native AuthManager instance owned by this shim. Idempotent. */
    destroy(): void;
    /**
     * Disposable hook for session-scoped lifetime management. Routes to the
     * {@link destroy} path so the native instance is released when the owning
     * session is disposed. Both `dispose()` and `destroy()` are idempotent.
     */
    dispose(): void;
    /**
     * Reads the Rust instance's last auth errors as structured
     * {@link AuthValidationError} values (`{ message, githubMessage? }`). The error
     * state is owned by the Rust runtime (cleared there on successful
     * login/logout/switch/refresh), so this is a pure read-through projection with
     * no host-side mirror.
     */
    private readLastAuthErrors;
    /**
     * Returns errors encountered during the most recent auth resolution attempt.
     * When non-empty, indicates tokens were found but could not be validated
     * (e.g., due to network failures or API errors). Useful for surfacing
     * the real cause of auth failure to the user instead of a generic
     * "no authentication found" message.
     */
    get lastAuthErrors(): readonly string[];
    /**
     * Returns structured errors from the most recent auth resolution attempt.
     * UI callers can use githubMessage to render upstream API reasons without
     * parsing formatted log strings.
     */
    get lastAuthErrorDetails(): readonly AuthValidationError[];
    /**
     * Register a callback to be called when authentication state changes.
     * By default the callback is invoked immediately with the current auth
     * state. Pass `{ immediate: false }` to only receive future changes.
     *
     * The listener registry, fan-out, immediate invocation, and subscription
     * lifetime are owned by the Rust runtime. The returned disposer unregisters
     * the native subscription directly.
     *
     * @param callback Function to call with auth info and token when auth state changes
     * @param options Options controlling subscription behavior
     */
    onAuthChange(callback: AuthCallback, options?: AuthChangeOptions): () => void;
    /**
     * Remove the first subscription registered for the callback.
     * @deprecated Prefer invoking the disposer returned by {@link onAuthChange}.
     */
    removeAuthCallback(callback: AuthCallback): void;
    /**
     * Returns the current auth info, loading it (in the Rust runtime) if the
     * cache is empty. The auth resolution, caching, and reload-on-miss all live
     * in Rust; this projects the result to the public shape.
     * @returns Current auth info.
     */
    getCurrentAuthInfo(): Promise<AuthInfo | null>;
    /**
     * Returns all the auth options available right now, sorted by priority.
     * @returns List of all available auth options, along with the token if available.
     */
    getAllAuthAvailable(): Promise<AuthInfoWithToken[]>;
    /**
     * Returns the auth options used by the user switcher, sorted by description.
     * The result is cached (and concurrent callers de-duplicated) inside the Rust
     * runtime, and invalidated there on any auth mutation, so the host keeps no
     * cache of its own.
     * @returns List of available auth options for the user switcher, along with the token if available.
     */
    getAllAuthAvailableForUserSwitch(): Promise<AuthInfoWithToken[]>;
    /**
     * Re-fetches the Copilot user info for the current auth and notifies callbacks.
     * Useful after actions that change the user's subscription status.
     * @returns Refreshed auth info on success; otherwise the latest auth info
     *          emitted to callbacks, or null if none.
     */
    refreshCopilotUser(): Promise<AuthInfo | null>;
    /**
     * Logs in the user with the provided credentials, persisting them via the
     * Rust runtime. The Rust runtime resolves the auth (with copilotUser),
     * caches it, and fans it out to registered listeners.
     * @param host User's host
     * @param login User's login
     * @param token User's token
     */
    loginUser(host: string, login: string, token: string): Promise<AuthInfo>;
    /**
     * Switches to the specified authentication info. The Rust runtime updates the
     * cache and notifies listeners.
     * @param auth The authentication method to switch to.
     */
    switchToAuth(auth: AuthInfoWithToken): Promise<void>;
    /**
     * Clears the current credentials.
     * @returns True if, after logging out a user, there are more users logged in.
     *          False otherwise.
     */
    logout(): Promise<boolean>;
    /**
     * Logs out a specific user identified by their auth info, removing their
     * token and persisted state via the Rust runtime. Rust re-resolves the
     * current auth and fans the result out to registered listeners. Used by the
     * user switcher / SDK account API, where the user being logged out may differ
     * from the currently active auth.
     * @param authInfo Auth info identifying the user to log out.
     * @returns True if other authenticated users remain after logout.
     */
    logoutUser(authInfo: AuthInfo): Promise<boolean>;
    resolveGitHubDotComToken(): Promise<string | undefined>;
}

/**
 * Configuration options for AuthManager.
 */
declare interface AuthManagerConfig {
    /**
     * If set, read auth token from this specific environment variable.
     * This takes highest priority and bypasses normal auth method precedence.
     */
    authTokenEnvVar?: string;
    /**
     * If true, disable automatic login detection (stored OAuth tokens and gh CLI).
     */
    disableAutoLogin?: boolean;
}

declare type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata;

declare type AuthValidationError = {
    readonly message: string;
    readonly githubMessage?: string;
};

/**
 * Virtual model id representing CAPI auto-mode. Selecting this triggers
 * `/models/session` resolution. Keep this as an import-time literal so tooling
 * that imports model types does not need the native runtime addon to be built.
 */
export declare const AUTO_MODEL_ID: "auto";

/**
 * Auto-approval judge information attached to a permission request. Present
 * (non-null) on a prompt request iff the session's allow-all mode is `auto`; its
 * absence means auto mode was off and the judge did not evaluate the request.
 * The {@link AutoApprovalRecommendation} conveys the judge's disposition. A
 * consumer (like the CLI) may choose to auto-approve when `recommendation` is
 * `approve`; others can ignore it and always prompt.
 */
declare type AutoApproval = {
    readonly recommendation: AutoApprovalRecommendation_2;
    readonly reason?: string;
    /**
     * Model id that produced the recommendation, when the judge was consulted
     * and reported one. Absent for `excluded` (the judge was not consulted) and
     * for failures that occurred before a model was selected.
     */
    readonly model?: string;
    /**
     * Classified cause of an `error` recommendation, absent for every other
     * recommendation. The `reason` for a failure is a fixed string, so this is
     * the only field that distinguishes a transport failure from a model that
     * replied without a verdict.
     */
    readonly failureReason?: AutoApprovalJudgeFailureReason_2;
};

/** Why the auto-approval judge produced no usable recommendation. Present only alongside an `error` recommendation, where the human-readable reason is a fixed string and therefore cannot distinguish these cases. Intended to make a judge failure reportable by a consumer that has no access to the host's logs. */
export declare type AutoApprovalJudgeFailureReason = "timeout" | "abort" | "empty_response" | "model_error" | "parse_error";

/**
 * Why the auto-approval judge produced no usable recommendation. Only
 * meaningful alongside an `error` recommendation.
 */
declare type AutoApprovalJudgeFailureReason_2 = "timeout" | "abort" | "empty_response" | "model_error" | "parse_error";

declare type AutoApprovalModelOutput = {
    readonly responseText: string;
    readonly model?: string;
};

/** Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). */
export declare type AutoApprovalRecommendation = "approve" | "requireApproval" | "excluded" | "error";

/**
 * The auto-approval safety judge's recommendation for a permission request.
 *
 * - `approve`: the judge recommends automatically approving the request.
 * - `requireApproval`: the judge does not recommend auto-approving; explicit
 *   approval is required. Whether that means prompting, denying, or something
 *   else is the consumer's decision.
 * - `excluded`: auto mode is on, but this request category is never
 *   auto-approvable (for example, sandbox-bypass), so the judge was not consulted.
 * - `error`: the judge was consulted but returned no usable recommendation.
 */
declare type AutoApprovalRecommendation_2 = "approve" | "requireApproval" | "excluded" | "error";

/** Why {@link AutoModeSessionManager.resolveIntent} settled the way it did. */
export declare type AutoIntentOutcome = 
/** The router confidently chose a model (which may or may not differ from the standard pick). */
"refined"
/** Multi-turn drift stayed below threshold; the current model was kept without adopting the fresh prediction. */
| "stay"
/** The router returned `fallback: true` or no chosen model; standard selection kept. */
| "fallback"
/** The intent proxy is not enabled for this integration (404). */
| "unsupported"
/** The intent proxy was unavailable (transient server/network condition). */
| "unavailable"
/** Any other transport/parse failure. */
| "error";

/** Result of {@link AutoModeSessionManager.resolveIntent}. */
declare type AutoIntentResolveResult = {
    /** The model to use for the conversation (the intent `chosenModel`, or the standard Auto fallback). */
    modelId: string;
    /** The session token (unchanged by the intent hop). */
    sessionToken: string;
    /** The raw intent outcome, when a prediction was obtained (absent on transport failure). */
    intent?: AutoIntentResult;
    /**
     * How the resolution settled. Present only when intent actually ran for this
     * call (absent on the latched fast-path / no-session cases), so callers can
     * gate one-shot telemetry on its presence.
     */
    outcome?: AutoIntentOutcome;
    /** The standard Auto selection prior to the intent hop, for telemetry comparison. */
    standardModel?: string;
    /**
     * The candidate-list size for this resolution (refined, or the standard list on
     * fallback/error). Carried per call so telemetry reports this session's count rather
     * than a process-global last-writer count when sessions classify concurrently.
     */
    availableModelsCount?: number;
    /** Models offered to the router for this resolution. */
    availableModels?: string[];
    /** Whether the routed prompt contained an image. */
    hasImage?: boolean;
};

/** Outcome of an Auto Intent prediction, normalized for the session manager. */
export declare type AutoIntentResult = {
    /** True when the router could not make a confident decision (keep standard Auto's model). */
    fallback: boolean;
    /** The server-provided reason for falling back, when available. */
    fallbackReason?: string;
    /** The router's chosen model, when `fallback` is false. */
    chosenModel?: string;
    /** Ordered candidate list replacing `/models/session`'s, when `fallback` is false. */
    candidateModels?: string[];
    /** The routing method the server applied, for telemetry. */
    routingMethod?: string;
    /** Classifier confidence, for telemetry. */
    confidence?: number;
    /** The predicted classifier label (e.g. `needs_reasoning`), for telemetry. */
    predictedLabel?: string;
    /** Server-side routing latency in milliseconds, for telemetry. */
    latencyMs?: number;
    /** Whether a sticky/pinned model overrode the router's classification, for telemetry. */
    stickyOverride?: boolean;
    /** The chosen model's score shortfall relative to the top candidate, for telemetry. */
    chosenShortfall?: number;
    /**
     * Coarse request-difficulty bucket (`low`/`medium`/`high`) for UX explainability
     * ("we picked X because this looks like high-reasoning work"). Absent on the
     * binary path or when the router didn't report one.
     */
    reasoningBucket?: "low" | "medium" | "high";
    /**
     * Per-category classifier scores (0–1), for explainability. Prefers the
     * granular HYDRA capability scores (`reasoning`, `code_gen`, `debugging`,
     * `tool_use`) and falls back to the binary `needs_reasoning`/`no_reasoning`
     * scores when HYDRA didn't run. Absent when the router reported neither.
     */
    categoryScores?: Record<string, number>;
    /** The multi-turn schedule config the server returned (JSON), for the drift state machine. */
    multiTurnJson?: string;
};

/** Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. */
export declare interface AutoModeResolvedData {
    /** Models offered to the router for this resolution */
    availableModels?: string[];
    /** Ordered candidate model list the router returned, when not a fallback */
    candidateModels?: string[];
    /** Per-category classifier scores (0-1) behind the bucket: the granular HYDRA capability scores (reasoning, code_gen, debugging, tool_use), or the binary needs_reasoning/no_reasoning scores when HYDRA didn't run. Lets clients show a breakdown rather than just the bucket. */
    categoryScores?: Record<string, number>;
    /** The concrete model the session will use after any intent refinement */
    chosenModel: string;
    /** The chosen model's score shortfall relative to the top candidate */
    chosenShortfall?: number;
    /** Classifier confidence for the predicted label, when available */
    confidence?: number;
    /** End-to-end client wait time for the router request in milliseconds */
    endToEndLatencyMs?: number;
    /** Whether the router fell back to the standard Auto selection */
    fallback?: boolean;
    /** Server-provided reason for falling back, when available */
    fallbackReason?: string;
    /** Whether the routed prompt contained an image */
    hasImage?: boolean;
    /** The predicted classifier label (e.g. `needs_reasoning`), when available */
    predictedLabel?: string;
    /** Coarse request-difficulty bucket, for explaining why a model was chosen ("picked X because this looks like high-reasoning work") */
    reasoningBucket?: AutoModeResolvedReasoningBucket;
    /** Server-reported router processing time in milliseconds */
    routerLatencyMs?: number;
    /** The routing method the server applied, when Auto Intent ran */
    routingMethod?: string;
    /** Whether a sticky model choice overrode the router result */
    stickyOverride?: boolean;
}

/** Session event "session.auto_mode_resolved". Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. */
export declare interface AutoModeResolvedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. */
    data: AutoModeResolvedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.auto_mode_resolved". */
    type: "session.auto_mode_resolved";
}

/** Coarse request-difficulty bucket for UX explainability */
export declare type AutoModeResolvedReasoningBucket = "low" | "medium" | "high";

/**
 * A dedicated auto-mode session token (T2) minted for a complementary-strategy
 * subagent (e.g. the rubber-duck critic), paired with the specific model it was
 * resolved for. When the subagent resolves to {@link AutoModeSession.pairedModel},
 * the child session forwards {@link AutoModeSession.token} as its own
 * `Copilot-Session-Token` so the request bills under this independent auto session
 * (at the discounted auto rate) instead of the parent's session or, worse, unbilled
 * at full price. Set only for complementary-strategy subagents dispatched from a
 * CAPI auto-mode parent.
 */
declare interface AutoModeSession {
    /** The minted auto-mode session token forwarded as the child's `Copilot-Session-Token`. */
    token: string;
    /** The concrete model this token was paired with; the token only attaches when the child resolves to it. */
    pairedModel: string;
}

/**
 * Stateful manager for auto-mode session resolution. One instance typically lives per
 * top-level entry point (CLI app, promptMode invocation, ACP server). Callers invoke
 * {@link resolve} each time they need to dispatch a request with the virtual `"auto"` model;
 * the manager caches the token and refreshes lazily when within the refresh lead time (5 minutes)
 * of the `expires_at` claim.
 *
 * In addition to lazy refresh, the manager schedules a background timer that proactively
 * re-resolves the token shortly before it expires (see {@link scheduleProactiveRefresh}).
 * This mirrors the behavior of other Copilot clients (e.g. VS Code) and matches CAPI's
 * guidance to refresh before `expires_at`: refreshing while the token is still valid yields
 * a `200` instead of the guaranteed `401` that results from sending an already-expired
 * `Copilot-Session-Token` to `POST /models/session` after a long idle gap.
 */
export declare class AutoModeSessionManager {
    private readonly state;
    private readonly listeners;
    private proactiveRefreshGeneration;
    private disposed;
    /**
     * Record a concrete model the user was using before switching into auto-mode; used
     * as a fallback when {@link resolve} fails terminally (e.g., 404 unsupported).
     */
    recordPreviousConcreteModel(modelId: string | undefined): void;
    /** The most recently resolved concrete model id, if any. */
    getLastResolved(): string | undefined;
    /** The number of models in the current auto-mode candidate list, if resolved. */
    getAvailableModelsCount(): number | undefined;
    /**
     * Whether the given concrete model id is part of the currently cached
     * auto-mode candidate list. Returns false when no session is cached.
     * Used by the request-retry path to decide whether an in-flight model
     * (e.g. one chosen by Auto Intent) can be preserved across a token refresh.
     */
    isModelAvailable(modelId: string): boolean;
    /**
     * The concrete model to display for the `Auto` selection, or `undefined`
     * when nothing concrete should be shown yet. Mirrors {@link getLastResolved}
     * except that it withholds the provisional standard-Auto pick until intent
     * settles on the first prompt (so the UI shows a plain `Auto` instead of a
     * model intent may immediately replace).
     */
    getDisplayModel(): string | undefined;
    /** Expiry (Unix seconds) of the currently cached session token, if known. */
    getLastExpiresAt(): number | undefined;
    /**
     * Derive the overall auto-mode discount percentage from the server's per-model
     * `discounted_costs` map. When a selected model entry is present, return that;
     * otherwise average all values. Returns a percentage (0–100) or `undefined`.
     */
    getDiscountPercent(): number | undefined;
    resolveDiscountPercent(args: AcquireArgs): Promise<number | undefined>;
    isOwnedBy(authInfo: AuthInfo): boolean;
    /** The previous concrete model id before auto was selected, for fallback purposes. */
    getPreviousConcreteModel(): string | undefined;
    /**
     * Subscribe to resolved-model changes. Called with the new value whenever {@link resolve}
     * updates, refreshes, or clears the cached session. Returns an unsubscribe.
     */
    subscribe(listener: (resolvedModel: string | undefined, discountPercent: number | undefined) => void): () => void;
    private notify;
    private notifyCurrentState;
    /**
     * The resolved concrete model for a specific SDK session: its own token-matched Auto
     * Intent decision when cached, else the pristine standard pick. Unlike
     * {@link getLastResolved} (a process-global last-writer snapshot), this never returns
     * another session's refinement. Returns `undefined` when no session is cached.
     */
    getResolvedModelForSession(sessionId: string): string | undefined;
    /**
     * Resolve the auto-mode model id + session token, using cache when valid. Returns
     * `undefined` when auto-mode is not supported or not available in the caller's environment.
     */
    resolve(args: ResolveArgs): Promise<{
        modelId: string;
        sessionToken: string;
    } | undefined>;
    /**
     * Resolve Auto with the prompt-aware single-call endpoint. Unlike the legacy
     * session-token flow, v2 tokens are cached until expiry and never proactively refreshed.
     *
     * The resolution is session-scoped: the token is only valid for this SDK
     * session and for the model `/auto` picked, so it is never published into
     * the process-global legacy state other sessions resolve against.
     */
    resolveV2(args: ResolveArgs & {
        prompt: string;
        hasImage: boolean;
        multiTurnRoutingEnabled: boolean;
        applyModelLimitCaps?: boolean;
        /** Multi-turn v2: also fold prior user messages into the routed prompt. */
        multiTurnContextRoutingEnabled?: boolean;
        /**
         * Lazy clean prior user messages for this session, oldest-to-newest.
         * The supplier is evaluated only for the context treatment so
         * flag-off and cached turns do not scan history.
         */
        previousUserMessages?: string[] | (() => string[]);
        /**
         * Renew a token the model rejected mid-turn. Bypasses the cache
         * without counting as a new user turn for multi-turn scheduling.
         */
        forceRefresh?: boolean;
        /**
         * Mint a token for a single ancillary request (compaction, MCP
         * sampling, a side question, the auto-approval judge) instead of for
         * a conversation turn.
         *
         * The result is handed to that one caller and never committed, so
         * the session keeps the model and multi-turn schedule its turns run
         * on. Resolves to `undefined` when the session has no v2 resolution
         * of its own, which is what keeps a session whose turns use the
         * legacy flow from issuing `/auto` calls for its background work.
         */
        ancillary?: boolean;
        /**
         * Reports how the resolution ended, including the failure modes that
         * return no result. A v2 failure silently falls back to the legacy
         * flow, so without this the fallback is indistinguishable from the
         * control arm in telemetry.
         */
        onOutcome?: (outcome: string) => void;
    }): Promise<AutoV2ResolveResult | undefined>;
    /**
     * Refine the resolved auto-mode model via the Auto Intent proxy. Each SDK session runs
     * its own classification, keyed by `sessionId`, so it classifies its own first prompt
     * instead of inheriting the first session's decision. {@link resolve} must have produced
     * a session token first — when no session is cached this returns `undefined`.
     *
     * Run-vs-skip is driven by Rust-owned per-session state: with multi-turn routing off, a one-shot latch runs
     * intent only on the first prompt; with it on, the first prompt anchors a drift schedule
     * and later prompts skip (cached) or re-check drift (`/predict`) per that schedule.
     *
     * On a confident, non-fallback prediction the cached model + candidate list are updated
     * (listeners notified). On fallback/404/transport failure the standard selection is kept.
     * The latch is set regardless so a failed attempt doesn't add intent-hop latency later.
     * The cached/skip result omits `outcome` so the caller only emits the event when intent ran.
     */
    resolveIntent(args: {
        authInfo: AuthInfo;
        integrationId: string;
        sessionId: string;
        logger: RunnerLoggerContract_2;
        prompt: string;
        hasImage: boolean;
        multiTurnRoutingEnabled?: boolean;
        /** Multi-turn v2: also send prior user messages so the router sees context. */
        multiTurnContextRoutingEnabled?: boolean;
        /**
         * Lazy clean prior user messages for this session, oldest-to-newest.
         * The supplier is evaluated only for the v2 context treatment so
         * explicit-model, flag-off, v1, and cached turns do not scan history.
         */
        previousUserMessages?: string[] | (() => string[]);
    }): Promise<AutoIntentResolveResult | undefined>;
    /**
     * Drop a single SDK session's cached Auto Intent state + any in-flight prediction. Call on
     * {@link Session} disposal. Rust also invalidates the dispatch marker so a later completion is dropped.
     */
    forgetIntentSession(sessionId: string): void;
    /**
     * Drop a single SDK session's Auto v2 resolution. Call when the session falls
     * back to the legacy two-hop flow so a stale v2 token can't be reused.
     */
    forgetAutoV2Session(sessionId: string): void;
    /**
     * The session's active Auto v2 resolution, when it has one that is still
     * usable. Lets token consumers reuse the v2 token instead of falling through
     * to the legacy session-token flow (which would resolve a different model).
     *
     * `selectedModel` is the normalized catalog entry `/auto` returned, so an
     * off-catalog pick can be merged into the model list the same way a fresh
     * resolution does.
     *
     * Set `ancillary` when the token will carry a single long request rather
     * than a turn that can cheaply re-resolve; it demands a much wider expiry
     * margin so the token outlives the whole call.
     */
    /**
     * Whether this session has an Auto v2 resolution of its own, however little
     * life its token has left. Lets an ancillary caller skip assembling a
     * resolution — which snapshots the conversation's user messages — for a
     * session whose turns run on the legacy flow.
     */
    hasAutoV2Session(sessionId: string, authInfo: AuthInfo): boolean;
    getAutoV2Session(sessionId: string, authInfo: AuthInfo, ancillary?: boolean): AutoV2SessionReuse | undefined;
    /** Drop the cached session and clear the token from {@link settings}. */
    clear(settings?: RuntimeSettings_2): void;
    /**
     * Cancel any pending proactive refresh and drop references that would keep
     * it scheduled. Call when the owning entry point is shutting down. Timers
     * are `unref`-ed so this is not required for the process to exit cleanly.
     */
    dispose(): void;
    /**
     * Update bookkeeping when the user switches models in the picker:
     * - Transitioning INTO auto: remember {@link prevModel} as the fallback concrete model.
     * - Transitioning AWAY from auto: drop the cached session token + resolved model.
     * No-op when the transition does not involve auto on either side.
     */
    handleModelChange(prevModel: string | undefined, nextModel: string, settings?: RuntimeSettings_2, sessionId?: string): void;
    /**
     * Reset a single SDK session's multi-turn drift schedule so its next resolution re-checks
     * drift. Call after a context compaction. The anchor is a single prompt's capability vector
     * (not the rewritten history), so it stays valid — we force one drift check, preserving the
     * anchor/backoff. No-op when the session has no routing state yet or multi-turn routing is inactive,
     * leaving the `intent_resolved` latch untouched so flag-off behavior is unchanged.
     */
    resetMultiTurn(sessionId: string): void;
    /**
     * Schedule a background refresh to fire the refresh lead time (5 minutes) before the
     * current token's `expires_at`, so the token is renewed while it is still valid
     * (yielding a `200` rather than a `401` on an expired-token refresh). Replaces any
     * previously scheduled timer. No-ops when the token has no expiry or no prior
     * {@link resolve} args are available to drive the refresh.
     *
     * The timer is `unref`-ed so it never keeps the process alive, and the callback
     * routes through {@link resolve} (sharing its in-flight dedup and rescheduling on
     * success). Failures are swallowed — the lazy refresh on the next {@link resolve}
     * remains the backstop.
     */
    private scheduleProactiveRefresh;
}

declare type AutoModeSessionResult = {
    sessionToken: string;
    selectedModel: string;
    availableModels: string[];
    expiresAt?: number;
    discountPercent?: number;
};

/** Auto mode switch completion notification */
export declare interface AutoModeSwitchCompletedData {
    /** Request ID of the resolved request; clients should dismiss any UI for this request */
    requestId: string;
    /** The user's auto-mode-switch choice */
    response: AutoModeSwitchResponse;
}

/** Session event "auto_mode_switch.completed". Auto mode switch completion notification */
export declare interface AutoModeSwitchCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Auto mode switch completion notification */
    data: AutoModeSwitchCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "auto_mode_switch.completed". */
    type: "auto_mode_switch.completed";
}

/** Auto mode switch request notification requiring user approval */
export declare interface AutoModeSwitchRequestedData {
    /** The rate limit error code that triggered this request */
    errorCode?: string;
    /** Unique identifier for this request; used to respond via session.respondToAutoModeSwitch() */
    requestId: string;
    /** Seconds until the rate limit resets, when known. Lets clients render a humanized reset time alongside the prompt. */
    retryAfterSeconds?: number;
}

/** Session event "auto_mode_switch.requested". Auto mode switch request notification requiring user approval */
export declare interface AutoModeSwitchRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Auto mode switch request notification requiring user approval */
    data: AutoModeSwitchRequestedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "auto_mode_switch.requested". */
    type: "auto_mode_switch.requested";
}

/** The user's auto-mode-switch choice */
export declare type AutoModeSwitchResponse = "yes" | "yes_always" | "no";

/** Response from the auto-mode switch dialog: switch once, switch and remember, or decline. */
declare type AutoModeSwitchResponse_2 = "yes" | "yes_always" | "no";

/** CAPI indicated auto-mode is not supported (404 / API version / feature flag gate). */
export declare class AutoModeUnsupportedError extends Error {
    readonly cause?: unknown | undefined;
    constructor(message: string, cause?: unknown | undefined);
}

/**
 * The currently completion-eligible objective together with the eligibility token that pins
 * the current eligibility era. The token lets an in-flight reviewer attempt detect when
 * eligibility changed underneath it (cancellation, pause/resume) and discard its stale verdict.
 */
declare interface AutopilotCompletionCandidate extends AutopilotObjectiveState {
    readonly eligibilityToken: number;
}

/** One root-agent tool execution, summarized for the reviewer prompt. */
declare interface AutopilotCompletionToolEvidence {
    readonly toolName?: string;
    readonly arguments?: string;
    readonly success: boolean;
    readonly result?: string;
}

/** Configuration for the session-level autopilot continuation driver. */
export declare interface AutopilotContinuationConfig {
    /** Whether the session should drive the autopilot continuation loop. */
    enabled: boolean;
    /**
     * Maximum number of continuation turns before the session stops autopilot.
     * When undefined, defaults to {@link DEFAULT_MAX_AUTOPILOT_CONTINUES}.
     */
    maxContinues?: number;
    /**
     * When true, autopilot force-stops after several consecutive turns that
     * execute no tools. Mirrors the `AUTOPILOT_NO_PROGRESS_STOP` feature flag
     * used in the CLI layer.
     */
    noProgressStopEnabled?: boolean;
}

/** Autopilot objective state file operation details indicating what changed */
export declare interface AutopilotObjectiveChangedData {
    /** Current autopilot objective id, if one exists */
    id?: number;
    /** The type of operation performed on the autopilot objective state file */
    operation: AutopilotObjectiveChangedOperation;
    /** Current autopilot objective status, if one exists */
    status?: AutopilotObjectiveChangedStatus;
}

/** Session event "session.autopilot_objective_changed". Autopilot objective state file operation details indicating what changed */
declare interface AutopilotObjectiveChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Autopilot objective state file operation details indicating what changed */
    data: AutopilotObjectiveChangedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.autopilot_objective_changed". */
    type: "session.autopilot_objective_changed";
}
export { AutopilotObjectiveChangedEvent }
export { AutopilotObjectiveChangedEvent as SessionAutopilotObjectiveChangedEvent }

/** The type of operation performed on the autopilot objective state file */
export declare type AutopilotObjectiveChangedOperation = "create" | "update" | "delete";

/** Current autopilot objective status, if one exists */
export declare type AutopilotObjectiveChangedStatus = "active" | "paused" | "cap_reached" | "completed";

declare type AutopilotObjectiveContinuationDecision = "continue" | "skip" | "stop";

declare interface AutopilotObjectiveContinuationProvider {
    getState(): AutopilotObjectiveState | undefined;
    isReady?(): boolean;
    shouldContinue(): AutopilotObjectiveContinuationDecision;
    buildContinuationPrompt(defaultPrompt: string): string;
    recordObjectiveTurnStarted(): void;
    recordObjectiveTurnFinished(): void;
    recordContinuation(): void;
}

/**
 * An objective's active credit limit window: the AI-credit cap (absent = unlimited)
 * plus the consumption accrued since the window opened (on `set`/`resume`).
 */
declare interface AutopilotObjectiveCreditLimit {
    readonly credits?: number;
    readonly creditsUsed: number;
}

/**
 * CreditLimit cap supplied by the user on `/goal <objective> --max-ai-credits` or a
 * bare `/goal --max-ai-credits` (resume). Only the cap is provided; per-window
 * consumption always starts fresh in the native registry.
 */
declare interface AutopilotObjectiveCreditLimitInput {
    readonly credits?: number;
}

declare interface AutopilotObjectiveMutationResult {
    readonly state: AutopilotObjectiveState;
    readonly previous?: AutopilotObjectiveState;
}

declare type AutopilotObjectiveOrigin = "objective" | "user" | null;

declare class AutopilotObjectiveRegistry implements AutopilotObjectiveContinuationProvider {
    private readonly session;
    private writeQueue;
    private readonly initialization;
    private readonly unsubscribeShutdown;
    private readonly unsubscribeTaskComplete;
    private readonly unsubscribeModeChanged;
    private readonly unsubscribeTurnStart;
    private readonly unsubscribeTurnEnd;
    private readonly unsubscribeUsage;
    private readonly unsubscribeCompaction;
    private readonly unsubscribeIdle;
    private readonly nativeRegistry;
    /**
     * Whether the user has sticky autopilot enabled (the `stayInAutopilot`
     * setting, default true in the CLI). When true, sticky autopilot takes
     * precedence over the native origin-based restore plan: completing, pausing,
     * or clearing an objective that owns autopilot must NOT drop the session back
     * to interactive. The gate is applied in {@link applyRestorePlan}, which every
     * origin-based revert path funnels through.
     * Defaults to false so non-CLI consumers preserve the historical
     * objective-owned-autopilot revert behavior until they opt in.
     */
    private stayInAutopilot;
    /**
     * Set while the registry itself is flipping `session.currentMode` back to
     * interactive (see {@link applyRestorePlan}). On the real `Session` that
     * assignment synchronously emits `session.mode_changed`, which would
     * otherwise re-enter {@link handleModeChanged} and, because the objective is
     * already paused, null its `autopilotOrigin` before a deferred credit-limit-pause
     * outcome reads it. The native registry already knows the intended state, so
     * we ignore the echo of our own write.
     */
    private suppressModeHandling;
    constructor(session: AutopilotObjectiveRegistrySession, nativeSessionId?: string);
    ready(): Promise<void>;
    flushPendingWrites(): Promise<void>;
    isReady(): boolean;
    getState(): AutopilotObjectiveState | undefined;
    /**
     * Sync the user's sticky-autopilot preference (`stayInAutopilot`) into the
     * registry. When enabled, completing an objective via `task_complete` keeps
     * the session in autopilot instead of reverting to interactive. The CLI
     * calls this from the same setting it feeds to the `useAutopilotContinuation`
     * hook (src/cli/hooks/useAutopilotContinuation.ts) so the objective and
     * non-objective completion paths honor sticky autopilot identically.
     */
    setStayInAutopilot(value: boolean): void;
    /**
     * Returns the currently completion-eligible objective together with the eligibility token
     * that pins the current eligibility era, or `undefined` when no active objective is eligible.
     * The token is used to discard a stale reviewer verdict when eligibility changes underneath
     * an in-flight reviewer attempt (see {@link AutopilotCompletionCandidate}).
     */
    getCompletionCandidate(): AutopilotCompletionCandidate | undefined;
    set(objectiveInput: string, creditLimit?: AutopilotObjectiveCreditLimitInput): Promise<AutopilotObjectiveMutationResult | {
        error: string;
    }>;
    resume(creditLimit?: AutopilotObjectiveCreditLimitInput): Promise<AutopilotObjectiveMutationResult | {
        error: string;
    }>;
    pause(reason?: string): Promise<AutopilotObjectiveMutationResult | {
        error: string;
    }>;
    clear(): Promise<AutopilotObjectiveMutationResult | {
        error: string;
    }>;
    recordObjectiveTurnStarted(): void;
    recordObjectiveTurnFinished(): void;
    recordContinuation(): void;
    markCompleted(summary: string): AutopilotObjectiveState | undefined;
    shouldContinue(): AutopilotObjectiveContinuationDecision;
    buildContinuationPrompt(defaultPrompt: string): string;
    dispose(): void;
    private initialize;
    private handleTaskComplete;
    private handleTaskBlocked;
    /**
     * Pause the objective behind a `blocked` completion, surfacing a warning on *either*
     * failure shape. `pause()` funnels through `applyUserMutationResult`, which reports
     * storage-unavailable / "no active objective" as a *returned* `{ error }` (not a
     * rejection). Awaiting only the rejection would let those cases silently leave the
     * objective `active` -- autopilot would keep looping on a completion consumers already
     * saw as `blocked`, with no warning -- so the resolved value is inspected too.
     */
    private pauseBlockedObjective;
    private warnBlockedPauseFailed;
    private recordAssistantTurnStarted;
    private recordAssistantTurnEnded;
    private recordUsage;
    /**
     * Charge a sub-agent's AI-backed compaction against the active objective's credit limit.
     *
     * A sub-agent's `session.compaction_complete` is bridged to ancestors as
     * `process_usage_metrics` — folded into parent native usage metrics but never
     * re-emitted as a parent event — so it bypasses this registry's own
     * `session.compaction_complete` subscription (unlike sub-agent `assistant.usage`,
     * which is re-emitted and caught via `{ includeSubAgents: true }`). The owning
     * `Session` invokes this from its `forwardSubagentUsageEvent` fold path so the
     * spend is charged identically to sub-agent model usage. Charging is gated
     * natively on the objective owning the in-flight turn, so a session with no active
     * objective (the common case) no-ops.
     */
    recordSubAgentCompactionUsage(compaction: CompactionCompleteCompactionTokensUsed | undefined): void;
    private chargeCompactionUsage;
    private recordSessionIdle;
    private handleModeChanged;
    private applyUserMutationResult;
    private persistMutationSafely;
    private emitInitializationPersistWarning;
    private applyRestorePlan;
    private applyStopPlan;
    private emitTelemetryPlans;
    private isDisposed;
    private hasStorage;
    private emitOutcomeTelemetry;
    private persistPlan;
}

declare type AutopilotObjectiveRegistrySession = Pick<Session, "abort" | "sessionId" | "currentMode" | "emit" | "getWorkspacePath" | "on" | "readAutopilotObjective" | "sendTelemetry" | "writeAutopilotObjective">;

declare interface AutopilotObjectiveState {
    readonly id: number;
    readonly objective: string;
    readonly status: AutopilotObjectiveStatus;
    readonly autopilotOrigin: AutopilotObjectiveOrigin;
    readonly continuationCount: number;
    readonly turnCount: number;
    readonly tokenCount: number;
    /**
     * Lifetime AI-credit consumption in integer nano-AIU (1 credit = 1e9
     * nano-AIU) for precise per-objective telemetry. Carried as the exact decimal
     * string the native registry emits — the underlying `i64` would lose integer
     * precision as a JS `number` above ~9M credits — so `getState()` and the
     * rollback token stay exact. It is parsed to a `number` only at the
     * telemetry-metric boundary (the Rust outcome builder tolerates the string)
     * and for display.
     */
    readonly creditCountNanoAiu: string;
    /** Number of times this objective has been resumed with a fresh AI-credit window (`/goal --max-ai-credits <N>`); 0 for a fresh objective. */
    readonly resumeCount: number;
    readonly createdAt: string;
    readonly updatedAt: string;
    readonly completionSummary?: string;
    readonly pauseReason?: string;
    readonly creditLimit?: AutopilotObjectiveCreditLimit;
}

declare type AutopilotObjectiveStatus = "active" | "paused" | "completed";

/** Result of the feature-gated single-call `POST /auto` resolution. */
export declare type AutoV2ResolveResult = {
    modelId: string;
    /** Fresh model routed by `/auto`, which may be declined by a multi-turn Stay decision. */
    routedModelId?: string;
    sessionToken: string;
    selectedModel: Model;
    expiresAt?: number;
    discountPercent?: number;
    categoryScores?: Record<string, number>;
    multiTurnJson?: string;
    routingDecision?: "anchor" | "stay" | "escalate";
    hasImage: boolean;
};

/**
 * A still-usable Auto v2 resolution replayed from session state, with no `/auto`
 * call. Carries no routing evidence (`categoryScores`, `routingDecision`, ...):
 * the router did not run, so a consumer must not report this as a routing turn.
 */
export declare type AutoV2SessionReuse = {
    modelId: string;
    sessionToken: string;
    selectedModel: Model;
    expiresAt?: number;
    discountPercent?: number;
    hasImage: boolean;
};

/**
 * Extended model type that includes reasoning effort metadata.
 * Returned by {@link getAvailableModels} for VS Code extension consumption.
 */
declare type AvailableModel = Model & {
    capabilities: Model["capabilities"] & {
        supports: Model["capabilities"]["supports"] & {
            reasoningEffort?: boolean;
        };
    };
    supportedReasoningEfforts?: ReasoningEffortLevel[];
};

/**
 * The small model projection needed by host callbacks that create subagents.
 * Full model data remains the canonical CAPI `Model` type.
 */
declare type AvailableModelInfo = Pick<Model, "id" | "billing"> & {
    label: string;
    description?: string;
    multiplier?: number;
    /**
     * Discrete server-driven price tier (`low` | `medium` | `high` | `very_high`)
     * from CAPI's `model_picker_price_category` — the same value the `/model`
     * picker displays. Used to derive a model's cost tier without re-deriving one
     * from the model id (e.g. rubber-duck critic selection), and as the
     * forward-looking cost signal under token-based billing (where the request
     * `multiplier` is deprecated); cost-tips ranks accessible models by this tier.
     */
    priceCategory?: string;
    /** Model capability metadata when available from the model API. */
    capabilities?: {
        supports?: {
            reasoning_effort?: string[];
        };
    };
    /**
     * True when this is a registry BYOK model (served by a user-configured provider,
     * not CAPI). The subagent cost-multiplier guard is bypassed whenever either the
     * session model or a candidate is BYOK, since BYOK models have no CAPI multiplier.
     */
    isByok?: boolean;
};

export declare type BackgroundTask = ShellTask | AgentTask;

export declare type BackgroundTaskProgress = AgentTaskProgress | ShellTaskProgress;

/** Empty payload for `session.background_tasks_changed`, indicating background task state changed. */
export declare interface BackgroundTasksChangedData {
}

/** Session event "session.background_tasks_changed". Empty payload for `session.background_tasks_changed`, indicating background task state changed. */
declare interface BackgroundTasksChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Empty payload for `session.background_tasks_changed`, indicating background task state changed. */
    data: BackgroundTasksChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.background_tasks_changed". */
    type: "session.background_tasks_changed";
}
export { BackgroundTasksChangedEvent }
export { BackgroundTasksChangedEvent as SessionBackgroundTasksChangedEvent }

export declare type BackgroundTaskStatus = TaskStatus_2;

/**
 * Status of a background task (agent or shell).
 */
declare type BackgroundTaskStatus_2 = "running" | "idle" | "completed" | "failed" | "cancelled";

/**
 * Telemetry categorization of an HTTP 400 response body. See
 * {@link ModelCallParam.badRequestKind}.
 */
declare type BadRequestKind = "bodyless" | "structured_error";

declare interface BaseContentBlock {
    annotations?: ContentAnnotations;
    _meta?: Record<string, unknown>;
}

/**
 * Plain string key for internal billing metadata attached to messages.
 *
 * This is a serializable marker (not a Symbol) so it survives the JSON round-trip
 * through the native Rust conversation state — a Symbol key is silently dropped by
 * `JSON.stringify` / `structuredClone`, which would lose the billable flag once the
 * authoritative conversation lives in Rust. To keep the original "won't leak to API
 * payloads" guarantee, the marker is stripped from request messages in the Rust
 * `ConversationState::build_request_messages` (the authoritative wire-build path
 * now that model orchestration runs in Rust), exactly like the screenshot
 * (`copilotScreenshot`) and compaction (`compactionCheckpoint`) markers.
 */
declare const BILLING_METADATA_KEY: "copilotBillingMetadata";

declare interface BillingMetadata {
    billable: boolean;
}

/** Canonical bytes for a content-addressed binary asset shared by reference across events */
export declare interface BinaryAssetData {
    /** Content-addressed id for this binary asset (e.g. "sha256:..."). */
    assetId: string;
    /** Decoded byte length of the binary asset */
    byteLength: number;
    /** Base64-encoded binary data */
    data: string;
    /** Human-readable description of the binary data */
    description?: string;
    /** Optional metadata from the producing tool. */
    metadata?: Record<string, unknown>;
    /** MIME type of the binary asset */
    mimeType: string;
    /** Binary asset type discriminator. Use "image" for images and "resource" otherwise. */
    type: BinaryAssetType;
}

/** Session event "session.binary_asset". Canonical bytes for a content-addressed binary asset shared by reference across events */
declare interface BinaryAssetEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Canonical bytes for a content-addressed binary asset shared by reference across events */
    data: BinaryAssetData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.binary_asset". */
    type: "session.binary_asset";
}
export { BinaryAssetEvent }
export { BinaryAssetEvent as SessionBinaryAssetEvent }

/** A reference to binary data persisted once on a session.binary_asset event and shared by id */
export declare interface BinaryAssetReference {
    /** Content-addressed id of the session.binary_asset event that holds this binary's bytes (e.g. "sha256:..."). */
    assetId: string;
    /** Decoded byte length of the referenced binary data */
    byteLength: number;
    /** Human-readable description of the binary data */
    description?: string;
    /** Optional metadata from the producing tool. */
    metadata?: Record<string, unknown>;
    /** MIME type of the referenced binary data */
    mimeType: string;
    /** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
    type: BinaryAssetReferenceType;
}

/** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
export declare type BinaryAssetReferenceType = "image" | "resource";

/** Binary asset type discriminator. Use "image" for images and "resource" otherwise. */
export declare type BinaryAssetType = "image" | "resource";

/**
 * This event is temporary until we extract vision support from being internal to getCompletionWithTools.
 */
declare type BinaryAttachmentRemovalEvent = {
    kind: "binary_attachments_removed";
    turn: number;
    largeImagesRemoved?: number;
    imagesRemoved: number;
    filesRemoved?: number;
};

declare interface BlobResourceContents {
    uri: string;
    mimeType?: string;
    _meta?: Record<string, unknown>;
    blob: string;
}

/**
 * A blocked egress request surfaced to callers.
 *
 * https://github.com/github/ebpf-padawan-egress-firewall/blob/c00dd1d15907585336fd154088a8eb7ee88c9841/pkg/logger/request.go#L71-L83
 */
declare interface BlockedRequest {
    because: string;
    blockedAt: string;
    cmd: string;
    domains: string;
    hasBeenRedirected: boolean;
    ip: string;
    originalIp: string;
    port: string;
    ruleSourceComment: string;
    url: string;
}

export declare function buildAvailableModelInfo(modelList: Model[], featureFlagService: IFeatureFlagService, byokIds?: ReadonlySet<string>): Promise<AvailableModelInfo[]>;

/** The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. */
declare interface BuiltInModelCatalog {
    /** Built-in model entries. */
    models: BuiltInModelCatalogEntry[];
}

/** A well-known model in the runtime's built-in catalog. */
declare interface BuiltInModelCatalogEntry {
    /** Well-known runtime model ID suitable for `ProviderConfig.modelId` or `ProviderModelConfig.modelId`. This is not necessarily the provider-facing deployment or model name and does not indicate CAPI entitlement or provider availability. */
    id: string;
}

declare type CacheControlCheckpoint = {
    type: "ephemeral";
};

declare interface CallbackRuntimeSink extends IAgentCallback {
    progressJson?(contentJson: string, opts?: AgentCallbackProgressOptions): Promise<void | AgentCallbackProgressResponse>;
    addBufferedUserMessages?(messages: UserMessage[]): void;
    drainUserMessages?(): UserMessage[];
    flush?(): Promise<void>;
}

declare interface CallToolResult extends Record<string, unknown> {
    content: CallToolResultContent[];
    isError?: boolean;
    structuredContent?: Record<string, unknown>;
    _meta?: Record<string, unknown>;
}

declare type CallToolResultContent = TextContent_2 | ImageContent_2 | AudioContent_2 | ResourceLinkContent | ResourceContent;

/** Cancellation result for a user-requested shell command. */
declare interface CancelUserRequestedShellCommandResult {
    /** Whether an in-flight execution was found and signalled to cancel */
    cancelled: boolean;
}

/** Canvas action that the agent or host can invoke. To discover the input schema for a particular action, call the list_canvas_capabilities tool. */
declare interface CanvasAction {
    /** Description of the action */
    description?: string;
    /** JSON Schema for the action input */
    inputSchema?: CanvasJsonSchema;
    /** Action name exposed by the canvas provider */
    name: string;
}

/** Canvas action invocation parameters. */
declare interface CanvasActionInvokeRequest {
    /** Action name to invoke */
    actionName: string;
    /** Action input */
    input?: unknown;
    /** Open canvas instance identifier */
    instanceId: string;
}

/** Canvas action invocation result. */
declare interface CanvasActionInvokeResult {
    /** Provider-supplied action result */
    result?: unknown;
}

/** Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. */
export declare interface CanvasClosedData {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Stable caller-supplied identifier of the canvas instance that was closed */
    instanceId: string;
}

/** Session event "session.canvas.closed". Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. */
declare interface CanvasClosedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.canvas.closed` with the closed canvas instance ID, provider ID, and canvas ID. */
    data: CanvasClosedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.canvas.closed". */
    type: "session.canvas.closed";
}
export { CanvasClosedEvent }
export { CanvasClosedEvent as SessionCanvasClosedEvent }

/** Canvas close parameters. */
declare interface CanvasCloseRequest {
    /** Open canvas instance identifier */
    instanceId: string;
}

/**
 * Canvas declaration supplied by an extension or embedder. This is the
 * in-process registration shape passed to `registerProvider` (alongside a live
 * {@link CanvasProviderConnection}); it never crosses a JSON-RPC boundary, so it
 * is a runtime-only type rather than part of the wire contract. The server
 * resolves it into the wire-facing {@link DiscoveredCanvas}.
 */
declare interface CanvasContribution {
    /** Provider-local canvas identifier */
    id: string;
    /** Human-readable canvas name */
    displayName: string;
    /** Short, single-sentence description shown to the agent in canvas catalogs. */
    description: string;
    /** PNG icon path. Extension-relative paths are resolved by the host. */
    icon?: string;
    /** JSON Schema for canvas open input */
    inputSchema?: CanvasJsonSchema;
    /** Actions the agent or host may invoke on an open instance */
    actions?: CanvasAction[];
}

/** Host context supplied by the runtime. */
declare interface CanvasHostContext {
    /** Host capabilities */
    capabilities?: CanvasHostContextCapabilities;
}

/** Host capabilities */
declare interface CanvasHostContextCapabilities {
    /** Whether canvas rendering is supported */
    canvases?: boolean;
}

/** JSON Schema for canvas open input */
declare type CanvasJsonSchema = unknown;

/** Declared canvases available in this session. */
declare interface CanvasList {
    /** Declared canvases available in this session */
    canvases: DiscoveredCanvas[];
}

/** Live open-canvas snapshot. */
declare interface CanvasListOpenResult {
    /** Currently open canvas instances */
    openCanvases: OpenCanvasInstance[];
}

/** Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. */
export declare interface CanvasOpenedData {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Owning extension display name, when available */
    extensionName?: string;
    /** Host-local PNG path for the canvas icon, when supplied */
    icon?: string;
    /** Input supplied when the instance was opened */
    input?: unknown;
    /** Stable caller-supplied canvas instance identifier */
    instanceId: string;
    /** Provider-supplied status text */
    status?: string;
    /** Rendered title */
    title?: string;
    /** URL for web-rendered canvases */
    url?: string;
}

/** Session event "session.canvas.opened". Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. */
declare interface CanvasOpenedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.canvas.opened` with canvas instance and provider IDs plus optional icon, title, status, URL, and input. */
    data: CanvasOpenedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.canvas.opened". */
    type: "session.canvas.opened";
}
export { CanvasOpenedEvent }
export { CanvasOpenedEvent as SessionCanvasOpenedEvent }

/** Canvas open parameters. */
declare interface CanvasOpenRequest {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier. Optional when the canvasId is unique across providers; required to disambiguate when multiple providers register the same canvasId. */
    extensionId?: string;
    /** Canvas open input */
    input?: unknown;
    /** Caller-supplied stable instance identifier */
    instanceId: string;
}

declare type CanvasProviderClientApi = ClientSessionApi["canvas"];

/** Canvas close parameters sent to the provider. */
declare interface CanvasProviderCloseRequest {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Host context supplied by the runtime. */
    host?: CanvasHostContext;
    /** Canvas instance identifier */
    instanceId: string;
    /** Session context supplied by the runtime. */
    session?: CanvasSessionContext;
}

declare interface CanvasProviderConnection {
    open: CanvasProviderClientApi["open"];
    close: CanvasProviderClientApi["close"];
    invokeAction(params: Parameters<CanvasProviderInvokeAction>[0]): ReturnType<CanvasProviderInvokeAction>;
}

declare interface CanvasProviderInfo {
    extensionId: string;
    extensionName?: string;
}

declare type CanvasProviderInvokeAction = CanvasProviderClientApi["action"]["invoke"];

/** Canvas action invocation parameters sent to the provider. */
declare interface CanvasProviderInvokeActionRequest {
    /** Action name to invoke */
    actionName: string;
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Host context supplied by the runtime. */
    host?: CanvasHostContext;
    /** Action input */
    input?: unknown;
    /** Canvas instance identifier */
    instanceId: string;
    /** Session context supplied by the runtime. */
    session?: CanvasSessionContext;
}

/** Canvas open parameters sent to the provider. */
declare interface CanvasProviderOpenRequest {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Host context supplied by the runtime. */
    host?: CanvasHostContext;
    /** Canvas open input */
    input?: unknown;
    /** Stable caller-supplied canvas instance identifier */
    instanceId: string;
    /** Session context supplied by the runtime. */
    session?: CanvasSessionContext;
}

/** Canvas open result returned by the provider. */
declare interface CanvasProviderOpenResult {
    /** Provider-supplied status text */
    status?: string;
    /** Provider-supplied title */
    title?: string;
    /** URL for web-rendered canvases */
    url?: string;
}

/** Durable record that a canvas instance is open, used to restore open canvases on cold session resume. Intentionally omits the transient url and availability. */
export declare interface CanvasRecordedData {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Input supplied when the instance was opened */
    input?: unknown;
    /** Stable caller-supplied canvas instance identifier */
    instanceId: string;
    /** Rendered title */
    title?: string;
}

/** Session event "session.canvas.recorded". Durable record that a canvas instance is open, used to restore open canvases on cold session resume. Intentionally omits the transient url and availability. */
export declare interface CanvasRecordedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Durable record that a canvas instance is open, used to restore open canvases on cold session resume. Intentionally omits the transient url and availability. */
    data: CanvasRecordedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.canvas.recorded". */
    type: "session.canvas.recorded";
}

/** A single canvas declaration in `session.canvas.registry_changed`, including provider IDs, display metadata, input schema, and actions. */
export declare interface CanvasRegistryChangedCanvas {
    /** Actions the agent or host may invoke */
    actions?: CanvasRegistryChangedCanvasAction[];
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Short, single-sentence description shown to the agent in canvas catalogs. */
    description: string;
    /** Human-readable canvas name */
    displayName: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Owning extension display name, when available */
    extensionName?: string;
    /** Host-local PNG path for the canvas icon, when supplied */
    icon?: string;
    /** JSON Schema for canvas open input */
    inputSchema?: unknown;
}

/** A single action within a canvas declaration, with its name, optional description, and optional input schema. */
export declare interface CanvasRegistryChangedCanvasAction {
    /** Action description */
    description?: string;
    /** JSON Schema for action input */
    inputSchema?: unknown;
    /** Action name */
    name: string;
}

/** Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. */
export declare interface CanvasRegistryChangedData {
    /** Canvas declarations currently available */
    canvases: CanvasRegistryChangedCanvas[];
}

/** Session event "session.canvas.registry_changed". Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. */
declare interface CanvasRegistryChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.canvas.registry_changed` listing the canvas declarations currently available. */
    data: CanvasRegistryChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.canvas.registry_changed". */
    type: "session.canvas.registry_changed";
}
export { CanvasRegistryChangedEvent }
export { CanvasRegistryChangedEvent as SessionCanvasRegistryChangedEvent }

/** Durable record that a canvas instance was closed, superseding a prior instance_recorded during resume replay. */
export declare interface CanvasRemovedData {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Stable caller-supplied identifier of the canvas instance that was closed */
    instanceId: string;
}

/** Session event "session.canvas.removed". Durable record that a canvas instance was closed, superseding a prior instance_recorded during resume replay. */
export declare interface CanvasRemovedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Durable record that a canvas instance was closed, superseding a prior instance_recorded during resume replay. */
    data: CanvasRemovedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.canvas.removed". */
    type: "session.canvas.removed";
}

/** Session context supplied by the runtime. */
declare interface CanvasSessionContext {
    /** Active session working directory, when known. */
    workingDirectory?: string;
}

/** Transient signal that an open canvas instance's provider has dropped (for example the extension is reloading mid-session). The host should keep the panel mounted and surface a reconnecting affordance rather than tearing it down; a subsequent `session.canvas.opened` for the same instanceId clears the affordance once the provider reconnects with a fresh url. Ephemeral and never persisted, so it is never replayed on cold resume. */
export declare interface CanvasUnavailableData {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Stable caller-supplied identifier of the canvas instance whose provider became unavailable */
    instanceId: string;
}

/** Session event "session.canvas.unavailable". Transient signal that an open canvas instance's provider has dropped (for example the extension is reloading mid-session). The host should keep the panel mounted and surface a reconnecting affordance rather than tearing it down; a subsequent `session.canvas.opened` for the same instanceId clears the affordance once the provider reconnects with a fresh url. Ephemeral and never persisted, so it is never replayed on cold resume. */
export declare interface CanvasUnavailableEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Transient signal that an open canvas instance's provider has dropped (for example the extension is reloading mid-session). The host should keep the panel mounted and surface a reconnecting affordance rather than tearing it down; a subsequent `session.canvas.opened` for the same instanceId clears the affordance once the provider reconnects with a fresh url. Ephemeral and never persisted, so it is never replayed on cold resume. */
    data: CanvasUnavailableData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.canvas.unavailable". */
    type: "session.canvas.unavailable";
}

/** Session capability change notification */
export declare interface CapabilitiesChangedData {
    /** UI capability changes */
    ui?: CapabilitiesChangedUI;
}

/** Session event "capabilities.changed". Session capability change notification */
export declare interface CapabilitiesChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session capability change notification */
    data: CapabilitiesChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "capabilities.changed". */
    type: "capabilities.changed";
}

/** UI capability changes */
export declare interface CapabilitiesChangedUI {
    /** Whether canvas rendering is now supported */
    canvases?: boolean;
    /** Whether elicitation is now supported */
    elicitation?: boolean;
    /** Whether MCP Apps (SEP-1865) UI passthrough is now supported */
    mcpApps?: boolean;
}

export declare const CAPI_SANITY_FLAGS_ENV_VAR: string;

declare type CAPIRepositoryContext = {
    repository?: string;
    repositoryHost?: string;
};

/**
 * Typed context for CAPI-specific request headers.
 */
declare type CAPIRequestContext = {
    /** The type of interaction: agent, subagent, sampling, background, compaction, or user-initiated. */
    interactionType: InteractionType;
    /** Stable trajectory identity shared with lifecycle events and provider callbacks. */
    agentId?: string;
    /** Stable identity of the immediate parent trajectory. Set for child trajectories such as subagents and sampling requests. */
    parentAgentId?: string;
    /** A unique GUID for this model run, sent as X-Agent-Task-Id. */
    agentTaskId: string;
    /** The parent model run ID, sent as X-Parent-Agent-Id. Set for child trajectories such as subagents and sampling requests. */
    parentAgentTaskId?: string;
    /** The client session ID, sent as X-Client-Session-Id. */
    clientSessionId?: string;
    /** Per-message interaction ID, sent as X-Interaction-Id. Overrides the default session-level value. */
    interactionId?: string;
};

/** Options scoped to the built-in CAPI (Copilot API) provider. */
declare interface CapiSessionOptions {
    /** Whether to use WebSocket transport for the CAPI Responses API. Enabled by default when the model advertises `ws:/responses` support; set to `false` to force the HTTP Responses transport in environments where WebSockets are blocked (e.g. behind a proxy). Setting this to `false` is equivalent to the `COPILOT_CLI_DISABLE_WEBSOCKET_RESPONSES` environment variable. */
    enableWebSocketResponses?: boolean;
}

/**
 * Options scoped to the built-in CAPI (Copilot API) provider. Kept as a nested
 * namespace so settings that only apply to CAPI stay isolated from BYOK provider
 * configuration, which can coexist with CAPI in the same session.
 */
declare interface CapiSessionOptions_2 {
    /**
     * Whether to use WebSocket transport for the CAPI Responses API. Enabled by
     * default whenever the model advertises `ws:/responses` support. Set to
     * `false` to force the HTTP Responses transport instead — for example, when
     * running in an environment where WebSockets are unavailable, such as behind
     * a proxy that doesn't support WebSocket connections. Setting this to `false`
     * is equivalent to setting the `COPILOT_CLI_DISABLE_WEBSOCKET_RESPONSES`
     * environment variable.
     * @default true
     */
    enableWebSocketResponses?: boolean;
}

declare interface ChatCompletion {
    id: string;
    choices: Array<ChatCompletionChoice>;
    created: number;
    model: string;
    object: "chat.completion";
    service_tier?: string | null;
    system_fingerprint?: string;
    usage?: CompletionUsage;
}

declare interface ChatCompletionAllowedToolChoice extends JsonObject {
    type: "allowed_tools";
}

declare interface ChatCompletionAssistantMessageParam {
    role: "assistant";
    content?: string | Array<ChatCompletionContentPartText | ChatCompletionContentPartRefusal> | null;
    function_call?: ModelWireFunctionCall | null;
    name?: string;
    refusal?: string | null;
    tool_calls?: Array<ChatCompletionMessageToolCall>;
}

declare interface ChatCompletionChoice {
    finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call";
    index: number;
    logprobs?: JsonObject | null;
    message: ChatCompletionMessage;
}

declare interface ChatCompletionChunk {
    id: string;
    choices: Array<ChatCompletionChunkChoice>;
    created: number;
    model: string;
    object: "chat.completion.chunk";
    service_tier?: string | null;
    system_fingerprint?: string;
    usage?: CompletionUsage | null;
}

declare interface ChatCompletionChunkChoice {
    delta: ChatCompletionChunkChoiceDelta;
    finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call" | null;
    index: number;
    logprobs?: JsonObject | null;
}

declare interface ChatCompletionChunkChoiceDelta {
    content?: string | null;
    function_call?: Partial<ModelWireFunctionCall>;
    refusal?: string | null;
    role?: "developer" | "system" | "user" | "assistant" | "tool";
    tool_calls?: Array<ChatCompletionChunkChoiceDeltaToolCall>;
}

declare interface ChatCompletionChunkChoiceDeltaToolCall {
    index: number;
    id?: string;
    type?: "function" | "custom";
    function?: Partial<ModelWireFunctionCall>;
    custom?: Partial<ModelWireCustomToolCall>;
}

declare type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartRefusal | ChatCompletionContentPartFile | ChatCompletionContentPartInputAudio;

declare interface ChatCompletionContentPartBase {
    type: string;
}

declare interface ChatCompletionContentPartFile extends ChatCompletionContentPartBase {
    type: "file";
    file: {
        file_data?: string;
        file_id?: string;
        filename?: string;
    };
}

declare interface ChatCompletionContentPartImage extends ChatCompletionContentPartBase {
    type: "image_url";
    image_url: {
        url: string;
        detail?: "auto" | "low" | "high";
    };
}

declare interface ChatCompletionContentPartInputAudio extends ChatCompletionContentPartBase {
    type: "input_audio";
    input_audio: {
        data: string;
        format: string;
    };
}

declare interface ChatCompletionContentPartRefusal extends ChatCompletionContentPartBase {
    type: "refusal";
    refusal: string;
}

declare interface ChatCompletionContentPartText extends ChatCompletionContentPartBase {
    type: "text";
    text: string;
}

declare interface ChatCompletionCustomTool {
    type: "custom";
    custom?: {
        name: string;
        description?: string;
        format?: JsonObject;
    };
    name?: string;
    description?: string;
    format?: JsonObject;
    [key: string]: unknown;
}

declare interface ChatCompletionDeveloperMessageParam {
    role: "developer";
    content: string | Array<ChatCompletionContentPartText>;
    name?: string;
}

declare interface ChatCompletionFunctionMessageParam {
    role: "function";
    content: string | null;
    name: string;
}

declare interface ChatCompletionFunctionTool {
    type: "function";
    function: {
        name: string;
        description?: string;
        parameters?: JsonObject;
        strict?: boolean | null;
    };
    [key: string]: unknown;
}

declare interface ChatCompletionMessage {
    role?: "assistant";
    content?: string | null;
    function_call?: ModelWireFunctionCall | null;
    refusal?: string | null;
    tool_calls?: Array<ChatCompletionMessageToolCall>;
}

declare interface ChatCompletionMessageCustomToolCall extends Omit<ModelWireChatCompletionMessageCustomToolCall, "custom" | "type"> {
    custom: ModelWireCustomToolCall;
    type: "custom";
}

declare interface ChatCompletionMessageFunctionToolCall extends Omit<ModelWireChatCompletionMessageFunctionToolCall, "function" | "type"> {
    function: ModelWireFunctionCall;
    type: "function";
}

declare type ChatCompletionMessageParam = (ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam | ChatCompletionUserMessageParam | ChatCompletionAssistantMessageParam | ChatCompletionToolMessageParam | ChatCompletionFunctionMessageParam) & {
    refusal?: string | null;
};

declare type ChatCompletionMessageParamsWithToolCalls = Omit<ChatCompletionAssistantMessageParam, "tool_calls"> & {
    tool_calls?: CopilotChatCompletionMessageToolCall[];
    copilot_annotations?: unknown;
    /** Phase of generation for phased-output models (e.g. gpt-5.3-codex). */
    phase?: string;
    /**
     * Neutral, provider-tagged server-side ("hosted") tool-use payload (tool
     * search, advisor, …) that must be round-tripped verbatim on subsequent
     * turns. See {@link ServerToolData}.
     */
    serverTools?: ServerToolData;
};

declare type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall;

declare interface ChatCompletionNamedToolChoice {
    type: "function";
    function: {
        name: string;
    };
}

declare interface ChatCompletionNamedToolChoiceCustom {
    type: "custom";
    custom: {
        name: string;
    };
}

declare interface ChatCompletionSystemMessageParam {
    role: "system";
    content: string | Array<ChatCompletionContentPartText>;
    name?: string;
}

declare type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool;

declare type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionAllowedToolChoice | ChatCompletionNamedToolChoice | ChatCompletionNamedToolChoiceCustom;

/**
 * Content parts a tool message may carry. Narrower than
 * {@link ChatCompletionContentPart}: the tool-result serializers only preserve
 * text, image, and file parts (Responses drops `refusal`/`input_audio` and the
 * Anthropic converter turns unsupported audio into empty text), so the wider
 * union would silently lose those kinds.
 */
declare type ChatCompletionToolContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartFile;

declare interface ChatCompletionToolMessageParam {
    role: "tool";
    content: string | Array<ChatCompletionToolContentPart>;
    tool_call_id: string;
}

declare interface ChatCompletionUserMessageParam {
    role: "user";
    content: string | Array<ChatCompletionContentPart>;
    name?: string;
}

declare interface CheckpointInfo {
    number: number;
    title: string;
    filename: string;
}

/** A compaction checkpoint broken into sections. */
declare interface CheckpointRow {
    session_id: string;
    checkpoint_number: number;
    title?: string;
    overview?: string;
    history?: string;
    work_done?: string;
    technical_details?: string;
    important_files?: string;
    next_steps?: string;
    created_at?: string;
}

/** A source supplied by a tool that should be made available to the model as citable content. */
export declare interface CitableSource {
    /** The source text made available to the model as citable content. */
    content: string;
    /** Stable identifier for this source within the tool result. Used for deduplication and may be used by future provider integrations to correlate response citations back to the originating source. */
    id: string;
    /** File path relative to the agent's workspace root, when the source is a file. */
    path?: string;
    /** Human-readable title of the source. */
    title?: string;
    /** URL of the source, when it is a web resource. */
    url?: string;
}

/** Location within a cited source (character, page, or content-block range) that supports a span. */
export declare type CitationLocation = CitationLocationChar | CitationLocationPage | CitationLocationBlock;

/** A content-block range within a structured source document. */
export declare interface CitationLocationBlock {
    /** Index of the last content block of the cited range (zero-based, exclusive). */
    endBlock: number;
    /** Index of the first content block of the cited range (zero-based, inclusive). */
    startBlock: number;
    /** Citation location type discriminator */
    type: "block";
}

/** A character range within the source's text content. */
export declare interface CitationLocationChar {
    /** End character offset within the source text (zero-based, exclusive). */
    endIndex: number;
    /** Start character offset within the source text (zero-based, inclusive). */
    startIndex: number;
    /** Citation location type discriminator */
    type: "char";
}

/** A page range within a paginated source document. */
export declare interface CitationLocationPage {
    /** Last page number of the cited range (inclusive). */
    endPage: number;
    /** First page number of the cited range. */
    startPage: number;
    /** Citation location type discriminator */
    type: "page";
}

/** The system that produced a citation. */
export declare type CitationProvider = "anthropic" | "openai" | "client";

/** A single citation occurrence linking a span of generated text to a supporting source. */
export declare interface CitationReference {
    /** The exact text from the source that supports the cited span, when provided by the model. */
    citedText?: string;
    /** Location within the source that supports the cited span, when the provider reports one. */
    location?: CitationLocation;
    /** Provider-native citation correlation data (e.g. Anthropic search_result_index / document_index), passed through opaquely for debugging and forward compatibility. */
    providerMetadata?: unknown;
    /** Identifier of the CitationSource this reference points to (CitationSource.id). */
    sourceId: string;
}

/** Provider-agnostic citations linking spans of the assistant's response to their supporting sources. */
export declare interface Citations {
    /** Deduplicated set of sources referenced by the citation spans. */
    sources: CitationSource[];
    /** Spans of generated text annotated with the sources that support them. */
    spans: CitationSpan[];
}

/** A source that backs one or more cited spans in the assistant's response. */
export declare interface CitationSource {
    /** Stable, turn-scoped identifier for this source, referenced by CitationReference.sourceId. */
    id: string;
    /** File path relative to the agent's workspace root, when the source is a file. */
    path?: string;
    /** The system that produced this citation. */
    provider: CitationProvider;
    /** Human-readable title of the source. */
    title?: string;
    /** URL of the source, when it is a web resource. */
    url?: string;
}

/** A contiguous span of generated assistant text and the source references that support it. */
export declare interface CitationSpan {
    /** End offset of the cited span within the final assistant message content (UTF-16 code units, zero-based, exclusive). */
    endIndex: number;
    /** The sources that support this span of generated text. */
    references: CitationReference[];
    /** Start offset of the cited span within the final assistant message content (UTF-16 code units, zero-based, inclusive). */
    startIndex: number;
}

declare interface Client {
    readonly model: string;
    /** Whether this client can carry persistent Responses WebSocket state across calls. */
    supportsPersistentWebSocketResponses?(): Promise<boolean>;
    /**
     * Returns a client for out-of-band model calls (e.g. a user side-question)
     * that must not interfere with the active request transport. For a
     * persistent-WebSocket client this is a distinct client on its own native
     * handle with WebSocket disabled, so such calls run over HTTP without
     * occupying the shared retained handle (a nested run left active on that
     * handle would make the next WebSocket turn trip the concurrent-reuse guard).
     * Implementations that never drive a persisted WebSocket connection may
     * return themselves.
     */
    getNestedPromptClient?(): Client;
    dispose?(): void;
    getCompletionWithTools(systemMessage: SystemMessageContent, initialMessages: ChatCompletionMessageParam[], tools: Tool[], options?: GetCompletionWithToolsOptions): AsyncGenerator<Event_2>;
}

/**
 * What initiated a client-triggered compaction, recorded as `trigger` on the
 * persisted compaction events. The native pre-request arm attributes its own
 * automatic starts (`threshold` / `context_limit_retry`) separately.
 */
export declare type ClientCompactionTrigger = Extract<SessionCompactionStartData["trigger"], "manual" | "memory_pressure" | "model_switch">;

declare type ClientInfo = {
    clientName: string;
    displayName?: string;
    mcpClient?: NativeMcpSession;
    listTools?: (options?: {
        timeoutMs?: number;
    }) => Promise<readonly LenientToolInfo[]>;
    preloadedTools?: readonly LenientToolInfo[];
    safeForTelemetry?: Tool["safeForTelemetry"];
    tools: string[];
    filterMapping?: Record<string, ContentFilterMode> | ContentFilterMode;
    timeout?: number;
    pendingConnection?: Promise<void>;
    isDefaultServer?: boolean;
    disableSecretMasking?: boolean;
    serverSupportsTaskTools?: boolean;
    excludeTools?: string[];
    deferTools?: "auto" | "never";
};

/** SDK-supplied managed permission policy accepted at session startup. */
declare interface ClientManagedPermissionsSettings {
    /** Disables bypass/allow-all permission modes while set to `"disable"`. */
    disableBypassPermissionsMode?: "disable";
    /** Matching requests are blocked. Highest decision precedence. */
    deny?: string[];
    /** Matching requests require interactive approval, even if another rule allows them. */
    ask?: string[];
    /** Matching requests are approved only when every declared source allowlist admits them and no deny/ask matches. */
    allow?: string[];
}

/**
 * Managed settings an SDK client may inject at session create/resume.
 *
 * The first public contract intentionally accepts only the permission slice.
 */
declare interface ClientManagedSettings {
    permissions?: ClientManagedPermissionsSettings;
}

declare type ClientNameContext = {
    clientName?: string;
    [key: string]: unknown;
};

declare type ClientNameContext_2 = {
    clientName?: string;
    [key: string]: unknown;
};

/**
 * The ideal set of options that a `{@link Client}` expose.
 */
declare type ClientOptions = {
    /**
     * The model to use for LLM completions.
     */
    model?: string;
    /**
     * The proportion of the model's input/prompt token limit
     * that should be given to tools as their token budget.
     */
    toolTokenBudgetProportion?: number;
    retryPolicy?: ClientRetryPolicy;
    /**
     * Controls optional adaptive thinking for models that support it.
     * When omitted, model capability defaults apply. `false` disables optional
     * adaptive thinking, though models that require adaptive thinking may still use it.
     */
    thinkingMode?: boolean;
    /**
     * The token budget for extended thinking/chain-of-thought for models that support it.
     * For Anthropic Claude models via CAPI, this maps to the `thinking_budget` parameter.
     * When set, enables extended thinking with the specified token budget.
     * Models that require adaptive thinking ignore this manual budget and use adaptive thinking.
     */
    thinkingBudget?: number | undefined;
    requestHeaders?: Record<string, string>;
    /**
     * Typed context for CAPI-specific request headers (interaction type, agent task IDs).
     * When set, these are mapped to HTTP headers by the CAPI client.
     */
    capiRequestContext?: CAPIRequestContext;
    /**
     * Repository metadata for CAPI request headers. Missing values are normalized
     * to the same sentinel used by restricted repository telemetry.
     */
    capiRepositoryContext?: CAPIRepositoryContext;
    /**
     * If true, enables cache control checkpoints on messages sent to the model.
     * This allows downstream services to better manage caching of responses.
     * Defaults to false.
     */
    enableCacheControl?: boolean;
    /** Whether this model supports explicit prompt-cache breakpoints through the OpenAI Responses API. */
    supportsExplicitPromptCaching?: boolean;
    /**
     * The default reasoning effort level for the model to use, if supported by the client.
     */
    defaultReasoningEffort?: string;
    /**
     * The default reasoning summary mode for model clients that support it.
     * Use "none" to suppress summary output regardless of whether reasoning is enabled.
     * Providers that do not support summary verbosity may ignore it.
     */
    defaultReasoningSummary?: ReasoningSummary_2;
    /**
     * The default output verbosity for model clients that support it.
     */
    defaultVerbosity?: ResponseVerbosity;
    /**
     * Deprecated compatibility alias for requesting reasoning summaries by default.
     * Use `defaultReasoningSummary: "detailed"` instead.
     */
    enableReasoningSummaries?: boolean;
    /**
     * Responses API text shaping options to send for models using the Responses API.
     */
    responsesTextConfig?: ResponseTextConfig;
    /**
     * The maximum number of output tokens for completions. When set, this value is sent
     * as `max_tokens` in the API request to cap the response length.
     */
    maxOutputTokens?: number;
    /**
     * Overrides the default sampling temperature for the model's non-reasoning
     * ("default") Chat Completions branch. When set, this value is sent as
     * `temperature` instead of the hardcoded `0`. Ignored on the
     * reasoning-effort and extended-thinking branches, which always use `1`.
     */
    temperature?: number;
    /**
     * Model family override for the agent. When set, uses the specified model family's
     * default configuration instead of looking up config by model name.
     */
    modelFamily?: string;
    /**
     * Feature flag service for accessing ExP assignment context.
     * When set, the CAPI client includes the latest assignment context as an
     * `X-Copilot-Client-Exp-Assignment-Context` header on every HTTP request,
     * or in the per-message header envelope for WebSocket requests (synchronously, never blocks).
     */
    featureFlagService?: IFeatureFlagService;
    /** Live gate for building restricted host-only engine-message telemetry. */
    shouldEmitHostEngineTelemetry?: () => boolean;
    /**
     * When true, disables WebSocket Responses routing even if the feature flag is
     * enabled and the model advertises `ws:/responses` support.
     */
    disableWebSocketResponses?: boolean;
    /**
     * Opaque partition key for native token-count caches. Sessions set this to
     * isolate cache hits from other tenants in the same runtime process.
     */
    tokenCacheScope?: string;
    /** SDK-supplied overrides for model capabilities, deep-merged over runtime defaults. */
    modelCapabilitiesOverride?: ModelCapabilitiesOverride;
    /** OpenAI Responses API prompt cache key. */
    promptCacheKey?: string;
    /**
     * Stable identifier for the conversation lineage this session belongs to,
     * shared by a session and every fork taken from it. When `promptCacheKey`
     * is not set explicitly, BYOK Responses requests derive their cache key
     * from this so forks retain the parent's prompt-cache affinity.
     */
    promptCacheLineageId?: string;
    /**
     * When set, enables the Anthropic advisor tool, allowing the executor model to
     * consult a higher-intelligence advisor model mid-generation for strategic guidance.
     * The value is the advisor model ID (e.g. "claude-opus-4-7").
     * Only applicable to Anthropic models.
     */
    advisorModel?: string;
    /**
     * Concrete fallback model id used for the visible refusal fallback. Claude
     * Fable 5 and Claude Opus 5 can decline a request with
     * `stop_reason: "refusal"` (→ `finish_reason: "content_filter"`). When this
     * is set and the `ANTHROPIC_REFUSAL_FALLBACK` feature flag is enabled and the
     * primary model returns a refusal, the runtime **re-issues the same request
     * directly to this fallback model at the CAPI Anthropic seam** (bypassing the
     * client model picker, so it works in pinned/benchmark sessions too), then
     * surfaces a visible notice and makes the fallback active for the current
     * session through a durable `session.model_change` event.
     *
     * The value must be a concrete, servable model id (e.g. `claude-opus-4.8`) —
     * `auto` is a client-side routing concept and cannot be a seam re-issue
     * target. Presence of this option marks the model as eligible; when unset the
     * refusal is surfaced as-is. Only applicable to Anthropic (CAPI) models. See
     * https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback
     */
    refusalFallbackModel?: string;
    /**
     * When true, uses Anthropic's built-in server-side tool search
     * (`tool_search_tool_regex_20251119`) instead of the client-side
     * `tool_search_tool` implementation. The API handles search
     * execution and tool reference expansion automatically.
     * Only applicable to Anthropic models.
     */
    builtinToolSearch?: boolean;
    /**
     * When true, uses OpenAI Responses client-executed tool search for deferred tools.
     */
    clientToolSearch?: boolean;
    /**
     * When true, preserves `tool_search_tool` as an ordinary function for
     * generic client-side search instead of converting it to a hosted
     * provider-native tool-search entry.
     */
    genericClientToolSearch?: boolean;
    /**
     * When true, enables the model provider's native ("hosted") web search. For
     * OpenAI Responses models this appends the hosted `{ type: "web_search" }`
     * tool so CAPI performs the search server-side and streams `web_search_call`
     * output items back. The session is the source of truth for this flag: it is
     * only set when the fully-gated decision in `Session.isNativeWebSearchActive`
     * holds — the model config advertises `supports.webSearch`, the model runs on
     * the Responses wire, AND the `copilot_cli_native_web_search` ExP flag is on.
     * Advertising the capability alone does NOT enable it. Only applicable to
     * OpenAI models today.
     */
    webSearch?: boolean;
    /**
     * Custom tool-search definition supplied by an SDK consumer's
     * `tool_search_tool` override (model-facing `description` / `input_schema`).
     * When OpenAI client-executed tool search is active, these fields override
     * the built-in tool-search description/parameters on the hosted
     * `tool_search` entry sent to the Responses API. Only applicable to OpenAI
     * models.
     */
    clientToolSearchDefinition?: {
        description?: string;
        input_schema?: ToolInputSchema;
    };
    /**
     * Experimental: enables native model citations for providers that support them.
     */
    enableCitations?: boolean;
    /**
     * Selects the BYOK OpenAI/Azure chat-completions behavior of
     * {@link ChatCompletionClient} (formerly the `AIClient` subclass in
     * `model/openai/ai-chat-completions.ts`). When `true`, the base client:
     * disables custom-tool definitions (the OpenAI SDK's `ChatCompletionStream`
     * cannot parse `type: "custom"` tool calls, so custom tools must be sent as
     * function tools); applies gpt-4-family completion
     * tuning plus `tool_choice` from {@link GetCompletionWithToolsOptions}; and
     * remaps Azure OpenAI's `cot_summary` reasoning own-prop onto CAPI's
     * `reasoning_text` for each emitted message
     * event. Defaults to `false` so every other CAPI/subclass caller is
     * unchanged. Set to `true` only by `agents/client.ts` for the Azure and
     * OpenAI-compatible chat-completions (non-Responses) BYOK paths.
     */
    openAiChatCompletionsVariant?: boolean;
    /**
     * Fallback for {@link GetCompletionWithToolsOptions.onSessionTokenExpired},
     * applied to every request this client makes that does not supply its own.
     *
     * The per-request option is how the agentic loop recovers a `401`, but
     * ancillary work (compaction, MCP sampling, a side question, the
     * auto-approval judge) calls `getCompletionWithTools` without one, so an
     * expired token there is unrecoverable — a `401` with no callback only earns
     * a bounded fast retry that replays the same dead token. Clients built on a
     * *reused* Auto session token need this, since they inherit whatever life
     * the token had left rather than minting a fresh one.
     */
    onSessionTokenExpired?: GetCompletionWithToolsOptions["onSessionTokenExpired"];
};

/**
 * Retry policies for the AI client.
 */
declare type ClientRetryPolicy = {
    /**
     * The maximum number of retries for **any** type of retryable failure or error.
     */
    maxRetries?: number;
    /**
     * Specific error codes that should always be retried.
     * - If a `number`, that specific error code will be retried.
     * - If a `[number, number]`, all error codes in the range will be retried (inclusive).
     * - If a `[number, undefined]`, all error codes greater than or equal to the first number will be retried.
     * - To retry all error codes based on an upper bound, simply use `[0, number]`.
     *
     * Some error codes are retried by default even if not specified here, for example 429 (rate limit exceeded).
     */
    errorCodesToRetry?: (number | [number, number | undefined])[];
    /**
     * How to handle retries for rate limiting (429) errors. If a policy is not provided, a default
     * policy will be used.
     */
    rateLimitRetryPolicy?: {
        /**
         * The default wait time in between retries if the server does not
         * provide a `retry-after` header.
         */
        defaultRetryAfterSeconds?: number;
        /**
         * Extra wait time added to the base `defaultRetryAfterSeconds` for 429
         * responses that lack a usable `retry-after` header (or when the header
         * exceeds the cap). Combined with the base, the first retry delay is
         * `defaultRetryAfterSeconds + initialRetryAfterBackoffExtraSeconds`, and
         * subsequent attempts grow by {@link retryAfterBackoffExtraGrowth}.
         */
        initialRetryAfterBackoffExtraSeconds?: number;
        /**
         * The growth factor for the exponential backoff extra time added
         * to rate-limit and transient-error retry delays (e.g. 2x doubles each attempt).
         */
        retryAfterBackoffExtraGrowth?: number;
        /**
         * The maximum wait time in between retries.
         */
        maxRetryAfterSeconds?: number;
    };
};

declare interface ClientSessionApi {
    canvas: {
        action: {
            invoke(params: CanvasProviderInvokeActionRequest): unknown | Promise<unknown>;
        };
        close(params: CanvasProviderCloseRequest): void | Promise<void>;
        open(params: CanvasProviderOpenRequest): CanvasProviderOpenResult | Promise<CanvasProviderOpenResult>;
    };
    factory: {
        abort(params: FactoryAbortRequest): FactoryAckResult | Promise<FactoryAckResult>;
        execute(params: FactoryExecuteRequest): FactoryExecuteResult | Promise<FactoryExecuteResult>;
    };
    providerToken: {
        getToken(params: ProviderTokenAcquireRequest): ProviderTokenAcquireResult | Promise<ProviderTokenAcquireResult>;
    };
    sessionFs: {
        appendFile(params: SessionFsAppendFileRequest): SessionFsError | Promise<SessionFsError>;
        exists(params: SessionFsExistsRequest): SessionFsExistsResult | Promise<SessionFsExistsResult>;
        mkdir(params: SessionFsMkdirRequest): SessionFsError | Promise<SessionFsError>;
        readFile(params: SessionFsReadFileRequest): SessionFsReadFileResult | Promise<SessionFsReadFileResult>;
        readdir(params: SessionFsReaddirRequest): SessionFsReaddirResult | Promise<SessionFsReaddirResult>;
        readdirWithTypes(params: SessionFsReaddirWithTypesRequest): SessionFsReaddirWithTypesResult | Promise<SessionFsReaddirWithTypesResult>;
        rename(params: SessionFsRenameRequest): SessionFsError | Promise<SessionFsError>;
        rm(params: SessionFsRmRequest): SessionFsError | Promise<SessionFsError>;
        sqliteExists(): SessionFsSqliteExistsResult | Promise<SessionFsSqliteExistsResult>;
        sqliteQuery(params: SessionFsSqliteQueryRequest): SessionFsSqliteQueryResult | Promise<SessionFsSqliteQueryResult>;
        sqliteTransaction(params: SessionFsSqliteTransactionRequest): SessionFsSqliteTransactionResult | Promise<SessionFsSqliteTransactionResult>;
        stat(params: SessionFsStatRequest): SessionFsStatResult | Promise<SessionFsStatResult>;
        writeFile(params: SessionFsWriteFileRequest): SessionFsError | Promise<SessionFsError>;
    };
}

/**
 * Available CLI color modes. Defined as a leaf module with no imports so
 * both layers that need it can pull from here without creating a layering
 * violation:
 *
 *   - `core/persistence/userSettings.ts` uses it for the `colorMode` setting.
 *   - `cli/tuikit/tokens/colors.ts` re-exports it for the renderer.
 *
 * Keeping this file dependency-free prevents the TUIkit token layer from
 * importing the persistence stack or native runtime. Do not add imports here.
 */
declare const COLOR_MODES: readonly ["default", "github", "dim", "high-contrast", "colorblind"];

declare type ColorMode = (typeof COLOR_MODES)[number];

declare type Command = {
    readonly identifier: string;
    readonly readOnly: boolean;
};

/** Queued command completion notification signaling UI dismissal */
export declare interface CommandCompletedData {
    /** Request ID of the resolved command request; clients should dismiss any UI for this request */
    requestId: string;
}

/** Session event "command.completed". Queued command completion notification signaling UI dismissal */
export declare interface CommandCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Queued command completion notification signaling UI dismissal */
    data: CommandCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "command.completed". */
    type: "command.completed";
}

/** Registered command dispatch request routed to the owning client */
export declare interface CommandExecuteData {
    /** Raw argument string after the command name */
    args: string;
    /** The full command text (e.g., /deploy production) */
    command: string;
    /** Command name without leading / */
    commandName: string;
    /** Unique identifier; used to respond via session.commands.handlePendingCommand() */
    requestId: string;
}

/** Session event "command.execute". Registered command dispatch request routed to the owning client */
export declare interface CommandExecuteEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Registered command dispatch request routed to the owning client */
    data: CommandExecuteData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "command.execute". */
    type: "command.execute";
}

/** Result type for external command execution (SDK-registered commands). */
declare type CommandExecutionResult = {
    error?: string;
};

/** Slash commands available in the session, after applying any include/exclude filters. */
declare interface CommandList {
    /** Commands available in this session */
    commands: SlashCommandInfo[];
}

/** Queued slash command dispatch request for client execution */
export declare interface CommandQueuedData {
    /** The slash command text to be executed (e.g., /help, /clear) */
    command: string;
    /** Unique identifier for this request; used to respond via session.respondToQueuedCommand() */
    requestId: string;
}

/** Session event "command.queued". Queued slash command dispatch request for client execution */
export declare interface CommandQueuedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Queued slash command dispatch request for client execution */
    data: CommandQueuedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "command.queued". */
    type: "command.queued";
}

/** A single slash command available in the session, as listed by the `commands.changed` event. */
export declare interface CommandsChangedCommand {
    /** Optional human-readable command description. */
    description?: string;
    /** Slash command name without the leading slash. */
    name: string;
}

/** SDK command registration change notification */
export declare interface CommandsChangedData {
    /** Current list of registered SDK commands */
    commands: CommandsChangedCommand[];
}

/** Session event "commands.changed". SDK command registration change notification */
declare interface CommandsChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** SDK command registration change notification */
    data: CommandsChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "commands.changed". */
    type: "commands.changed";
}
export { CommandsChangedEvent }
export { CommandsChangedEvent as SdkCommandsChangedEvent }

declare type CommandSegment = {
    readonly identifier: string;
    readonly fullCommandText: string;
};

/** Pending command request ID and an optional error if the client handler failed. */
declare interface CommandsHandlePendingCommandRequest {
    /** Error message if the command handler failed */
    error?: string;
    /** Request ID from the command invocation event */
    requestId: string;
}

/** Indicates whether the pending client-handled command was completed successfully. */
declare interface CommandsHandlePendingCommandResult {
    /** Whether the command was handled successfully */
    success: boolean;
}

/** Slash command name and optional raw input string to invoke. */
declare interface CommandsInvokeRequest {
    /** Raw input after the command name */
    input?: string;
    /** Command name. Leading slashes are stripped and the name is matched case-insensitively. */
    name: string;
}

/** Optional filters controlling which command sources to include in the listing. */
declare type CommandsListRequest = {
    includeBuiltins?: boolean;
    includeClientCommands?: boolean;
    includeSkills?: boolean;
};

/** Queued-command request ID and the result indicating whether the host executed it (and whether to stop processing further queued commands). */
declare interface CommandsRespondToQueuedCommandRequest {
    /** Request ID from the `command.queued` event the host is responding to. */
    requestId: string;
    /** Result of the queued command execution. */
    result: QueuedCommandResult;
}

/** Indicates whether the queued-command response was matched to a pending request. */
declare interface CommandsRespondToQueuedCommandResult {
    /** Whether a pending queued command with the given request ID was found and resolved. False when the request was already resolved, cancelled, or unknown. */
    success: boolean;
}

/** Token usage breakdown for the compaction LLM call (aligned with assistant.usage format) */
export declare interface CompactionCompleteCompactionTokensUsed {
    /** Cached input tokens reused in the compaction LLM call */
    cacheReadTokens?: number;
    /** Tokens written to prompt cache in the compaction LLM call */
    cacheWriteTokens?: number;
    /** Per-request cost and usage data from the CAPI copilot_usage response field */
    copilotUsage?: CompactionCompleteCompactionTokensUsedCopilotUsage;
    /** Duration of the compaction LLM call in milliseconds */
    duration?: number;
    /** Input tokens consumed by the compaction LLM call */
    inputTokens?: number;
    /** Model identifier used for the compaction LLM call */
    model?: string;
    /** Output tokens produced by the compaction LLM call */
    outputTokens?: number;
}

/** Per-request cost and usage data from the CAPI copilot_usage response field */
export declare interface CompactionCompleteCompactionTokensUsedCopilotUsage {
    /** Itemized token usage breakdown */
    tokenDetails?: CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail[];
    /** Total cost in nano-AI units for this request */
    totalNanoAiu: number;
}

/** Token usage detail for a single billing category */
export declare interface CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail {
    /** Number of tokens in this billing batch */
    batchSize: number;
    /** Cost per batch of tokens */
    costPerBatch: number;
    /** Total token count for this entry */
    tokenCount: number;
    /** Token category (e.g., "input", "output") */
    tokenType: string;
}

/** Conversation compaction results including success status, metrics, and optional error details */
declare interface CompactionCompleteData {
    /** Checkpoint snapshot number created for recovery */
    checkpointNumber?: number;
    /** File path where the checkpoint was stored */
    checkpointPath?: string;
    /** Token usage breakdown for the compaction LLM call (aligned with assistant.usage format) */
    compactionTokensUsed?: CompactionCompleteCompactionTokensUsed;
    /** Token count from non-system messages (user, assistant, tool) after compaction */
    conversationTokens?: number;
    /** User-supplied focus instructions provided to a manual `/compact` invocation. Omitted for automatic compaction and for manual compaction with no focus text. */
    customInstructions?: string;
    /** Error message if compaction failed */
    error?: string;
    /** Number of messages removed during compaction */
    messagesRemoved?: number;
    /** Total tokens in conversation after compaction */
    postCompactionTokens?: number;
    /** Number of messages before compaction */
    preCompactionMessagesLength?: number;
    /** Total tokens in conversation before compaction */
    preCompactionTokens?: number;
    /** GitHub request tracing ID (x-github-request-id header) for the compaction LLM call */
    requestId?: string;
    /** Copilot service request ID (x-copilot-service-request-id header) for the compaction LLM call */
    serviceRequestId?: string;
    /** For failed compaction only: the HTTP status code of the compaction LLM call failure, when it carried one. Absent for successful compaction and for failures without an HTTP status (e.g. an empty model response or a transport error). */
    statusCode?: number;
    /** Whether compaction completed successfully */
    success: boolean;
    /** LLM-generated summary of the compacted conversation history */
    summaryContent?: string;
    /** Token count from system message(s) after compaction */
    systemTokens?: number;
    /** Model context window token limit the compaction was targeting, when known */
    tokenLimit?: number;
    /** Number of tokens removed during compaction */
    tokensRemoved?: number;
    /** Token count from tool definitions after compaction */
    toolDefinitionsTokens?: number;
    /** What initiated this compaction, when known */
    trigger?: CompactionTrigger;
}
export { CompactionCompleteData }
export { CompactionCompleteData as SessionCompactionCompleteData }

declare type CompactionCompletedEvent = {
    kind: "compaction_completed";
    turn: number;
    performedBy: string;
    success: boolean;
    error?: string;
    /** HTTP status code of the failure, when it carried one. Set only when `success` is false. */
    statusCode?: number;
    /** GitHub request-tracing ID of the failed compaction call, when available. Set only on failure. */
    requestId?: string;
    /** Copilot service request ID of the failed compaction call, when available. Set only on failure. */
    serviceRequestId?: string;
    compactionResult?: CompactionEventResult;
};

/** Session event "session.compaction_complete". Conversation compaction results including success status, metrics, and optional error details */
declare interface CompactionCompleteEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Conversation compaction results including success status, metrics, and optional error details */
    data: CompactionCompleteData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.compaction_complete". */
    type: "session.compaction_complete";
}
export { CompactionCompleteEvent }
export { CompactionCompleteEvent as SessionCompactionCompleteEvent }

declare type CompactionEvent = CompactionStartedEvent | CompactionStaticContextBlockedEvent | CompactionCompletedEvent;

declare type CompactionEventResult = {
    tokenLimit: number;
    preCompactionTokens: number;
    preCompactionMessagesLength: number;
    postCompactionTokens?: number;
    postCompactionMessagesLength?: number;
    tokensRemoved?: number;
    messagesRemoved?: number;
    summaryContent: string;
    checkpointNumber?: number;
    requestId?: string;
    serviceRequestId?: string;
    compactionTokensUsed?: {
        inputTokens: number;
        outputTokens: number;
        cacheReadTokens: number;
        cacheWriteTokens: number;
        copilotUsage?: NormalizedCopilotUsage;
        duration?: number;
        model?: string;
    };
};

/**
 * Result of a conversation history compaction operation.
 */
export declare interface CompactionResult {
    success: boolean;
    tokensRemoved: number;
    messagesRemoved: number;
    summaryContent: string;
    /** Post-compaction context window usage, matching the shape of `session.usage_info` event data. */
    contextWindow?: {
        /** Maximum token count for the model's context window. */
        tokenLimit: number;
        /** Current total tokens in the context window (system + conversation + tool definitions). */
        currentTokens: number;
        /** Current number of messages in the conversation. */
        messagesLength: number;
        /** Token count from system message(s). */
        systemTokens?: number;
        /** Token count from non-system messages (user, assistant, tool). */
        conversationTokens?: number;
        /** Token count from tool definitions. */
        toolDefinitionsTokens?: number;
    };
}

/** Context window breakdown at the start of LLM-powered conversation compaction */
export declare interface CompactionStartData {
    /** Token count from non-system messages (user, assistant, tool) at compaction start */
    conversationTokens?: number;
    /** Total context tokens (system + conversation + tool definitions) at compaction start, when known */
    currentTokens?: number;
    /** Model identifier used for compaction, when known */
    model?: string;
    /** Token count from system message(s) at compaction start */
    systemTokens?: number;
    /** Model context window token limit the compaction is targeting, when known */
    tokenLimit?: number;
    /** Token count from tool definitions at compaction start */
    toolDefinitionsTokens?: number;
    /** What initiated this compaction, when known */
    trigger?: CompactionTrigger;
}

declare type CompactionStartedEvent = {
    kind: "compaction_started";
    turn: number;
    performedBy: string;
    /** Total prompt-token estimate at compaction start */
    currentTokens?: number;
    /** Effective prompt-token limit used for the compaction decision */
    tokenLimit?: number;
    /** Token count from system message(s) at compaction start */
    systemTokens?: number;
    /** Token count from non-system messages (user, assistant, tool) at compaction start */
    conversationTokens?: number;
    /** Token count from tool definitions at compaction start */
    toolDefinitionsTokens?: number;
};

/** Session event "session.compaction_start". Context window breakdown at the start of LLM-powered conversation compaction */
declare interface CompactionStartEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Context window breakdown at the start of LLM-powered conversation compaction */
    data: CompactionStartData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.compaction_start". */
    type: "session.compaction_start";
}
export { CompactionStartEvent }
export { CompactionStartEvent as SessionCompactionStartEvent }

declare type CompactionStaticContextBlockedEvent = {
    kind: "compaction_static_context_blocked";
    turn: number;
    message: string;
    /** Total prompt-token estimate when the request was blocked */
    currentTokens?: number;
    /** Effective prompt-token limit used for the compaction decision */
    tokenLimit?: number;
    /** Token count from system message(s) when the request was blocked */
    systemTokens?: number;
    /** Token count from non-system messages (user, assistant, tool) when the request was blocked */
    conversationTokens?: number;
    /** Token count from tool definitions when the request was blocked */
    toolDefinitionsTokens?: number;
};

declare type CompactionStaticContextBlockedEvent_2 = Extract<Event_2, {
    kind: "compaction_static_context_blocked";
}>;

/** What initiated a conversation compaction */
export declare type CompactionTrigger = "threshold" | "context_limit_retry" | "manual" | "memory_pressure" | "model_switch";

/** Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). */
declare interface CompletionsGetTriggerCharactersResult {
    /** Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. */
    triggerCharacters: string[];
}

/** Request host-driven completions for the current composer input. */
declare interface CompletionsRequestRequest {
    /** Cursor offset within `text`, in UTF-16 code units. */
    offset: number;
    /** The full composed composer input. */
    text: string;
}

/** Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. */
declare interface CompletionsRequestResult {
    /** Completion items in host-ranked order. */
    items: SessionCompletionItem[];
}

declare interface CompletionTokensDetails {
    accepted_prediction_tokens?: number;
    audio_tokens?: number;
    reasoning_tokens?: number;
    rejected_prediction_tokens?: number;
}

declare interface CompletionUsage {
    completion_tokens?: number;
    prompt_tokens?: number;
    total_tokens: number;
    completion_tokens_details?: CompletionTokensDetails;
    prompt_tokens_details?: PromptTokensDetails;
    reasoning_tokens?: number;
    input_tokens?: number;
    output_tokens?: number;
    input_tokens_details?: ResponseInputTokensDetails;
    output_tokens_details?: CompletionTokensDetails;
}

declare type CompletionWithToolsModel = {
    readonly name: string;
    readonly id: string;
    readonly capabilities?: {
        readonly supports?: {
            readonly vision?: boolean;
        };
        readonly limits?: {
            readonly max_prompt_tokens?: number;
            readonly max_output_tokens?: number;
            readonly max_context_window_tokens?: number;
            readonly vision?: {
                readonly supported_media_types: string[];
                readonly max_prompt_images: number;
                readonly max_prompt_image_size: number;
            };
        };
    };
};

/** ConfigEntry represents a single configuration entry in the ExP API response. */
declare interface ConfigEntry {
    Id: string;
    Parameters: Record<string, ExpFlagValue>;
}

/** Params to attach or detach an in-process ExtensionController delegate. */
declare interface ConfigureSessionExtensionsParams {
    /** In-process ExtensionController delegate (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. The post-SDK extension surface exposes list/enable/disable/reload via dedicated RPCs served by the runtime. */
    controller?: unknown;
    /** Session to attach the extension controller delegate to. */
    sessionId: string;
}

/** Metadata for a connected remote session. */
declare interface ConnectedRemoteSessionMetadata {
    /** Neutral SDK discriminator for the connected remote session kind. */
    kind: ConnectedRemoteSessionMetadataKind;
    /** Last session update time as an ISO 8601 string. */
    modifiedTime: string;
    /** Optional friendly session name. */
    name?: string;
    /** Pull request number associated with the session. */
    pullRequestNumber?: number;
    /** Repository associated with the connected remote session. */
    repository: ConnectedRemoteSessionMetadataRepository;
    /** Original remote resource identifier. */
    resourceId?: string;
    /** SDK session ID for the connected remote session. */
    sessionId: string;
    /** Remote session staleness deadline as an ISO 8601 string. */
    staleAt?: string;
    /** Session start time as an ISO 8601 string. */
    startTime: string;
    /** Remote session state returned by the backing service. */
    state?: string;
    /** Optional session summary. */
    summary?: string;
}

/** Neutral SDK discriminator for the connected remote session kind. */
declare type ConnectedRemoteSessionMetadataKind = "remote-session" | "coding-agent";

/** Repository associated with the connected remote session. */
declare interface ConnectedRemoteSessionMetadataRepository {
    /** Branch associated with the remote session. */
    branch: string;
    /** Repository name. */
    name: string;
    /** Repository owner or organization login. */
    owner: string;
}

/** Remote session connection parameters. */
declare interface ConnectRemoteSessionParams {
    /** Session ID to connect to. */
    sessionId: string;
}

/** Parameters for the `server.connect` handshake: an optional connection token and optional connection-level opt-ins (e.g. GitHub telemetry forwarding). */
declare interface ConnectRequest {
    /** Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification. Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); host-only compatibility events are forward-only and intentionally skip that path. Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled — using the process-global gate for ordinary events and an explicit session-scoped decision for host-only events. */
    enableGitHubTelemetryForwarding?: boolean;
    /** Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN */
    token?: string;
}

/** Handshake result reporting the server's protocol version and package version on success. */
declare interface ConnectResult {
    /** Always true on success */
    ok: true;
    /** Server protocol version number */
    protocolVersion: number;
    /** Server package version */
    version: string;
}

/**
 * Optional per-session context used to populate the consolidation
 * (rem-agent) system prompt with a fresh snapshot of the parent's
 * board, conversation turns, and latest checkpoint.
 */
declare type ConsolidationContext = {
    store: SessionStore;
    sessionId: string;
    /**
     * When set, identifies a parent session whose trajectory the rem-agent
     * should consolidate (e.g., when this session is a detached headless
     * child spawned on the parent's interactive shutdown). Turns and
     * checkpoints are read under `detachedFromSpawningParentSessionId` instead of `sessionId`
     * so the child consolidates the parent's work, not its own empty
     * trajectory. The board lookup is repo/branch-keyed and unaffected.
     */
    detachedFromSpawningParentSessionId?: string;
    repository: string;
    branch: string;
};

declare interface ContentAnnotations {
    audience?: Array<"user" | "assistant">;
    priority?: number;
    lastModified?: string;
}

/**
 * Response from the content exclusion API for a single repository.
 */
declare interface ContentExclusionApiResponse {
    [key: string]: unknown;
    rules: ContentExclusionRule[];
    last_updated_at: string | number;
    scope: "repo" | "all";
}

/** Local file system absolute paths within the session working directory to check against its content-exclusion policy. */
declare interface ContentExclusionCheckPathsRequest {
    /** Local file system absolute paths within the session working directory to check. Results are returned in the same order, including duplicates. */
    paths: string[];
}

/** Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. */
declare interface ContentExclusionCheckPathsResult {
    /** Whether the session's policy service was available for the complete batch. When false, checks is empty and callers must treat every requested path as excluded. */
    available: boolean;
    /** Per-path decisions in request order. Empty when available is false. */
    checks: ContentExclusionPathCheck[];
}

/** Content-exclusion decision for one requested path. */
declare interface ContentExclusionPathCheck {
    /** Whether the session's complete content-exclusion policy excludes the path. */
    excluded: boolean;
    /** The path supplied by the caller. */
    path: string;
}

/**
 * Types for GitHub Content Exclusion API responses and internal data structures.
 */
/**
 * A single content exclusion rule from the API.
 */
declare interface ContentExclusionRule {
    [key: string]: unknown;
    paths: string[];
    ifAnyMatch?: string[];
    ifNoneMatch?: string[];
    source: {
        [key: string]: unknown;
        name: string;
        type: string;
    };
}

declare enum ContentFilterMode {
    None = "none",
    Markdown = "markdown",
    HiddenCharacters = "hidden_characters"
}

/** Controls how MCP tool result content is filtered: none leaves content unchanged, markdown sanitizes HTML while preserving Markdown-friendly output, and hidden_characters removes characters that can hide directives. */
declare type ContentFilterMode_2 = "none" | "markdown" | "hidden_characters";

/** Session event "session.context_changed". Updated working directory and git context after the change */
declare interface ContextChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Updated working directory and git context after the change */
    data: WorkingDirectoryContext;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.context_changed". */
    type: "session.context_changed";
}
export { ContextChangedEvent }
export { ContextChangedEvent as SessionContextChangedEvent }

/** Context-cleared details emitted when the host clears the conversation (the session.history.clearContext RPC / Session.clearContextMessages) */
export declare interface ContextClearedData {
    /** Optional initial message set after clearing */
    initialMessage?: string;
    /** Number of conversation messages that were cleared */
    messagesCleared: number;
}

/** Session event "session.context_cleared". Context-cleared details emitted when the host clears the conversation (the session.history.clearContext RPC / Session.clearContextMessages) */
declare interface ContextClearedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Context-cleared details emitted when the host clears the conversation (the session.history.clearContext RPC / Session.clearContextMessages) */
    data: ContextClearedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.context_cleared". */
    type: "session.context_cleared";
}
export { ContextClearedEvent }
export { ContextClearedEvent as SessionContextClearedEvent }

/** A single large message currently in context. */
declare interface ContextHeaviestMessage {
    /** Stable identifier for this message within the snapshot. */
    id: string;
    /** Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. */
    label: string;
    /** Role of the chat message (`user`, `assistant`, or `tool`). */
    role: string;
    /** Token count currently in context for this individual message. */
    tokens: number;
}

/** Allowed values for the `ContextTier` enumeration. */
export declare type ContextTier = "default" | "long_context";

/** Context tier for models that support multiple context-window sizes. */
declare type ContextTier_2 = "default" | "long_context";

/**
 * Context tier for models with tiered context pricing.
 * "default" caps the session to the model's default context window;
 * "long_context" pins the session to the long-context tier when supported.
 * Closed union of the tiers the runtime understands — unlike `ReasoningEffort`
 * (open, because models declare their own effort levels), the tier set is fixed
 * and runtime-owned, so this mirrors `ReasoningSummary`. The wire boundary still
 * validates incoming values via `validateContextTierParam`. Ignored for models
 * without tiered pricing.
 */
declare type ContextTier_3 = "default" | "long_context";

declare type CopilotAPIEndpoint = "/chat/completions" | "/v1/messages" | "/responses" | "ws:/responses";

/** Represents direct Copilot API authentication (via GITHUB_COPILOT_API_TOKEN + COPILOT_API_URL). */
declare type CopilotApiTokenAuthInfo = {
    readonly type: "copilot-api-token";
    readonly host: "https://github.com";
    readonly copilotUser?: CopilotUserResponse;
};

/** Authentication-info variant for direct Copilot API token auth sourced from environment variables, with public GitHub host. */
declare interface CopilotApiTokenAuthInfo_2 {
    /** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
    copilotUser?: CopilotUserResponse;
    /** Authentication host (always the public GitHub host). */
    host: "https://github.com";
    /** Direct Copilot API authentication via the `GITHUB_COPILOT_API_TOKEN` + `COPILOT_API_URL` environment-variable pair. The token itself is read from the environment by the runtime, not carried in this struct. */
    type: "copilot-api-token";
}

/**
 * Note: agent sessions API depend on this type!
 */
declare type CopilotChatCompletionChunk = Omit<ChatCompletionChunk, "choices" | "usage"> & {
    choices: CopilotChatCompletionChunkChoices;
    usage?: CopilotCompletionUsage | null;
    copilot_usage?: CopilotUsage;
};

declare type CopilotChatCompletionChunkChoice = Omit<ChatCompletionChunkChoice, "delta"> & {
    delta: CopilotChatCompletionChunkDelta;
};

declare type CopilotChatCompletionChunkChoices = Array<CopilotChatCompletionChunkChoice>;

declare type CopilotChatCompletionChunkDelta = Omit<ChatCompletionChunkChoiceDelta, "tool_calls"> & ReasoningMessageParam & {
    responses_message_status?: ResponsesMessageStatus;
    tool_calls?: Array<CopilotChatCompletionToolCallDelta>;
    copilot_annotations?: string | undefined;
    /** Phase of generation for phased-output models (e.g. gpt-5.3-codex). */
    phase?: string;
};

declare type CopilotChatCompletionMessageParam = ChatCompletionMessageParam & ReasoningMessageParam & StoreItem & {
    /** Responses API message item status used to round-trip message items. */
    responses_message_status?: ResponsesMessageStatus;
    tool_calls?: Array<CopilotChatCompletionMessageToolCall>;
    copilot_cache_control?: CacheControlCheckpoint;
    [BILLING_METADATA_KEY]?: BillingMetadata;
    /** Phase of generation for phased-output models (e.g. gpt-5.3-codex). */
    phase?: string;
    /** Actual output token count from the API response, used for more accurate token counting on assistant messages. */
    outputTokens?: number;
    /**
     * Neutral, provider-tagged server-side ("hosted") tool-use payload
     * (tool search, advisor, …) that must be round-tripped verbatim on
     * subsequent turns. See {@link ServerToolData}.
     */
    serverTools?: ServerToolData_2;
    /**
     * Provider's completion / response identifier; shared across all chunks of
     * a single API call when the model emits multi-chunk responses (e.g. gpt-5.5
     * with tool_search). Set by the model client at chunk-segmentation time;
     * consumed by coalescing helpers (cross-transport, telemetry) and by the
     * session rebuild handler.
     */
    apiCallId?: string;
};

/**
 * Re-export the OpenAI union type for convenience.
 * ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall
 */
declare type CopilotChatCompletionMessageToolCall = ChatCompletionMessageToolCall & {
    index?: number;
};

/**
 * Streaming tool call delta that supports both function and custom tool calls.
 */
declare type CopilotChatCompletionToolCallDelta = FunctionToolCallDelta | CustomToolCallDelta;

declare type CopilotCompletionUsage = Omit<NonNullable<ChatCompletion["usage"]>, "prompt_tokens_details"> & {
    prompt_tokens_details?: CopilotPromptTokensDetails;
    /** Reasoning tokens reported by CAPI for models like Gemini. */
    reasoning_tokens?: number;
};

/**
 * CopilotExpAssignmentResponse represents the response structure from the ExP API for feature assignments.
 */
declare interface CopilotExpAssignmentResponse {
    Features: string[];
    Flights: Record<string, string>;
    Configs: ConfigEntry[];
    ParameterGroups?: unknown;
    FlightingVersion?: number;
    AssignmentContext: string;
}

declare type CopilotPromptTokensDetails = NonNullable<NonNullable<ChatCompletion["usage"]>["prompt_tokens_details"]> & {
    /** Tokens written to the prompt cache (e.g. Anthropic's `cache_creation_input_tokens`). */
    cache_creation_tokens?: number;
};

/** Per-request cost/usage data returned by CAPI as a peer of `usage`. */
declare interface CopilotUsage {
    token_details: CopilotUsageTokenDetail[];
    total_nano_aiu: number;
}

/** A single token-type cost entry returned by CAPI in `copilot_usage.token_details`. */
declare interface CopilotUsageTokenDetail {
    batch_size: number;
    cost_per_batch: number;
    token_count: number;
    token_type: string;
}

/** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
declare interface CopilotUserResponse {
    /** Copilot access SKU identifier (e.g. `free_limited_copilot`, `copilot_for_business_seat_quota`) used to gate model and feature access. */
    access_type_sku?: string;
    /** Opaque analytics tracking identifier for the user, forwarded from the Copilot API. */
    analytics_tracking_id?: string;
    /** Date the Copilot seat was assigned to the user, if applicable. */
    assigned_date?: string | null;
    /** Whether the user is eligible to sign up for the free/limited Copilot tier. */
    can_signup_for_limited?: boolean;
    /** Whether the user is able to upgrade their Copilot plan. */
    can_upgrade_plan?: boolean;
    /** Whether Copilot chat is enabled for the user. */
    chat_enabled?: boolean;
    /** Whether CLI remote control is enabled for the user. */
    cli_remote_control_enabled?: boolean;
    /** Whether cloud session storage is enabled for the user. */
    cloud_session_storage_enabled?: boolean;
    /** Whether the Codex agent is enabled for the user. */
    codex_agent_enabled?: boolean;
    /** Copilot plan name for the user (e.g. `individual`, `business`, `enterprise`). */
    copilot_plan?: string;
    /** Whether `.copilotignore` content-exclusion support is enabled for the user. */
    copilotignore_enabled?: boolean;
    /** Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. */
    endpoints?: CopilotUserResponseEndpoints;
    /** Whether MCP (Model Context Protocol) support is enabled for the user. */
    is_mcp_enabled?: boolean | null;
    /** Whether the user is a GitHub/Microsoft staff member. */
    is_staff?: boolean;
    /** Per-category quota allotments for free/limited-tier users, keyed by quota category. */
    limited_user_quotas?: Record<string, number>;
    /** Date the free/limited-tier user's quotas next reset, as a raw string from the Copilot API. */
    limited_user_reset_date?: string;
    /** GitHub login of the authenticated user. */
    login?: string;
    /** Per-category monthly quota allotments, keyed by quota category. */
    monthly_quotas?: Record<string, number>;
    /** Organizations the user belongs to, each with an optional login and display name. */
    organization_list?: ({
        login?: string | null;
        name?: string | null;
    } | null)[] | null;
    /** Logins of the organizations the user belongs to. */
    organization_login_list?: string[];
    /** Date the user's usage quota next resets, as a raw string from the Copilot API; see `quota_reset_date_utc` for the UTC-normalized value. */
    quota_reset_date?: string;
    /** UTC-normalized form of `quota_reset_date` (the date the user's usage quota next resets). */
    quota_reset_date_utc?: string;
    /** Quota snapshot map from the raw Copilot user-response passthrough, with chat, completions, premium-interactions, and other entries. */
    quota_snapshots?: CopilotUserResponseQuotaSnapshots;
    /** Whether the user's telemetry is subject to restricted-data handling. */
    restricted_telemetry?: boolean;
    /** Raw passthrough of the Copilot API `te` flag for the user (an opaque server-side eligibility signal surfaced in telemetry); not otherwise interpreted by the runtime. */
    te?: boolean;
    /** Whether the account is on usage-based (token/AI-credit) billing rather than a fixed premium-request quota. */
    token_based_billing?: boolean;
}

/** Endpoint URLs from the raw Copilot `/copilot_internal/v2/token` user-response passthrough. */
declare interface CopilotUserResponseEndpoints {
    api?: string;
    exp?: string;
    "origin-tracker"?: string;
    proxy?: string;
    telemetry?: string;
}

/** Quota snapshot map from the raw Copilot user-response passthrough, with chat, completions, premium-interactions, and other entries. */
declare interface CopilotUserResponseQuotaSnapshots {
    /** Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. */
    chat?: CopilotUserResponseQuotaSnapshotsChat;
    /** Completions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. */
    completions?: CopilotUserResponseQuotaSnapshotsCompletions;
    /** Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. */
    premium_interactions?: CopilotUserResponseQuotaSnapshotsPremiumInteractions;
}

/** Chat quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. */
declare interface CopilotUserResponseQuotaSnapshotsChat {
    /** Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. */
    entitlement?: number;
    /** Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. */
    has_quota?: boolean;
    /** Count of additional pay-per-request usage consumed this period beyond the entitlement. */
    overage_count?: number;
    /** Whether usage may continue at pay-per-request rates once the entitlement is exhausted. */
    overage_permitted?: boolean;
    /** Percentage of the entitlement remaining at the snapshot timestamp. */
    percent_remaining?: number;
    /** Identifier of the quota bucket this snapshot describes. */
    quota_id?: string;
    /** Amount of quota remaining at the snapshot timestamp. */
    quota_remaining?: number;
    /** Unix epoch time, in seconds, when this quota next resets. */
    quota_reset_at?: number;
    /** Remaining entitlement/quota amount at the snapshot timestamp. */
    remaining?: number;
    /** UTC timestamp when this snapshot was captured. */
    timestamp_utc?: string;
    /** Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. */
    token_based_billing?: boolean;
    /** Whether the entitlement for this category is unlimited. */
    unlimited?: boolean;
}

/** Completions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. */
declare interface CopilotUserResponseQuotaSnapshotsCompletions {
    /** Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. */
    entitlement?: number;
    /** Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. */
    has_quota?: boolean;
    /** Count of additional pay-per-request usage consumed this period beyond the entitlement. */
    overage_count?: number;
    /** Whether usage may continue at pay-per-request rates once the entitlement is exhausted. */
    overage_permitted?: boolean;
    /** Percentage of the entitlement remaining at the snapshot timestamp. */
    percent_remaining?: number;
    /** Identifier of the quota bucket this snapshot describes. */
    quota_id?: string;
    /** Amount of quota remaining at the snapshot timestamp. */
    quota_remaining?: number;
    /** Unix epoch time, in seconds, when this quota next resets. */
    quota_reset_at?: number;
    /** Remaining entitlement/quota amount at the snapshot timestamp. */
    remaining?: number;
    /** UTC timestamp when this snapshot was captured. */
    timestamp_utc?: string;
    /** Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. */
    token_based_billing?: boolean;
    /** Whether the entitlement for this category is unlimited. */
    unlimited?: boolean;
}

/** Premium-interactions quota snapshot from the raw Copilot user-response passthrough, with entitlement, overage, remaining quota, reset, and billing fields. */
declare interface CopilotUserResponseQuotaSnapshotsPremiumInteractions {
    /** Number of requests/units included in the entitlement for this period; `-1` denotes an unlimited entitlement. */
    entitlement?: number;
    /** Whether the user currently has quota available; when `false` and not unlimited, further requests are blocked until the quota resets. */
    has_quota?: boolean;
    /** Count of additional pay-per-request usage consumed this period beyond the entitlement. */
    overage_count?: number;
    /** Whether usage may continue at pay-per-request rates once the entitlement is exhausted. */
    overage_permitted?: boolean;
    /** Percentage of the entitlement remaining at the snapshot timestamp. */
    percent_remaining?: number;
    /** Identifier of the quota bucket this snapshot describes. */
    quota_id?: string;
    /** Amount of quota remaining at the snapshot timestamp. */
    quota_remaining?: number;
    /** Unix epoch time, in seconds, when this quota next resets. */
    quota_reset_at?: number;
    /** Remaining entitlement/quota amount at the snapshot timestamp. */
    remaining?: number;
    /** UTC timestamp when this snapshot was captured. */
    timestamp_utc?: string;
    /** Whether this category uses usage-based (token/AI-credit) billing rather than a fixed premium-request count. */
    token_based_billing?: boolean;
    /** Whether the entitlement for this category is unlimited. */
    unlimited?: boolean;
}

export declare interface CoreServices {
    telemetryService: TelemetryService;
    createFeatureFlagService: CreateFeatureFlagService;
    /** Shared auto-mode session manager that resolves the virtual `"auto"` model id to a concrete model. */
    autoModeManager: AutoModeSessionManager;
    /** Process-level MCP tool cache shared by every session in this runtime host, when enabled. */
    mcpToolSnapshotCache?: McpToolSnapshotCache;
}

declare type CoreServicesInput = {
    telemetryService: TelemetryService;
    createFeatureFlagService: CreateFeatureFlagService;
    autoModeManager: AutoModeSessionManager;
    /**
     * Enables loading and persistence of MCP tool snapshots for this runtime host.
     * Defaults to true; `COPILOT_MCP_TOOL_CACHE` can still disable it process-wide.
     */
    enableMcpToolSnapshotCache?: boolean;
};

export declare function createCoreServices({ telemetryService, createFeatureFlagService, autoModeManager, enableMcpToolSnapshotCache, }: CoreServicesInput): CoreServices;

export declare function createDeferredFeatureFlagService(options: FeatureFlagInitOptions): FeatureFlagService;

export declare type CreateFeatureFlagService = (options: {
    readonly sessionId: string;
    expAssignments?: CopilotExpAssignmentResponse;
    deferExpResponse?: boolean;
}) => SessionFeatureFlagService;

export declare function createLocalFeatureFlagService(options?: Partial<FeatureFlagInitOptions>): LocalFeatureFlagService;

export declare function createLocalFeatureFlagServiceCreator(options?: Partial<FeatureFlagInitOptions>): CreateFeatureFlagService;

declare interface CreateMessageRequestParams extends TaskAugmentedRequestParams, Record<string, unknown> {
    messages: SamplingMessage[];
    modelPreferences?: ModelPreferences;
    systemPrompt?: string;
    includeContext?: string;
    temperature?: number;
    maxTokens: number;
    stopSequences?: string[];
    metadata?: Record<string, unknown>;
    tools?: ToolDescriptor[];
    toolChoice?: ToolChoice;
}

declare interface CreateMessageResultWithTools extends Record<string, unknown> {
    role: "user" | "assistant";
    content: SamplingMessageContentBlock | SamplingMessageContentBlock[];
    model: string;
    stopReason?: "maxTokens" | "endTurn" | "stopSequence" | "toolUse" | (string & {});
    _meta?: Record<string, unknown>;
}

/**
 * Creates an assignment snapshot from raw context values.
 *
 * A secondary context extends the primary TAS attribution and must never be
 * emitted on its own. A blank primary suppresses the entire snapshot, and a
 * blank secondary is omitted. JavaScript callers can bypass the parameter
 * types; at runtime, non-string values are treated as absent so they cannot
 * make an otherwise valid telemetry event fail.
 */
export declare function createTelemetryAssignmentContext(primary: string | undefined, secondary?: string): TelemetryAssignmentContext | undefined;

/** The currently selected model, reasoning effort, and context tier for the session. The context tier reflects `Session.getContextTier()`, restored from the session journal on resume. */
declare interface CurrentModel {
    /** Context tier for models that support multiple context-window sizes. */
    contextTier?: ContextTier_2;
    /** Currently active model identifier */
    modelId?: string;
    /** Reasoning effort level currently applied to the active model, when one is set. Reads `Session.getReasoningEffort()` synchronously after `getSelectedModel()` resolves so the two values are reported as a snapshot. */
    reasoningEffort?: string;
}

/** Lightweight metadata for a currently initialized session tool */
declare interface CurrentToolMetadata {
    /** Whether the tool is loaded on demand via tool search */
    deferLoading?: boolean;
    /** Tool description */
    description: string;
    /** JSON Schema for tool input */
    input_schema?: Record<string, unknown>;
    /** MCP server name for MCP-backed tools */
    mcpServerName?: string;
    /** Raw MCP tool name for MCP-backed tools */
    mcpToolName?: string;
    /** Model-facing tool name */
    name: string;
    /** Optional MCP/config namespaced tool name */
    namespacedName?: string;
}

/**
 * Identifies the custom agent that owns an MCP server configuration.
 * Passed separately from the server config to avoid mixing agent context with server settings.
 */
declare interface CustomAgentInfo {
    name: string;
    version?: string;
}

/** A single loaded custom agent in `session.custom_agents_updated`, with identity, source, tools, invocability, and model override. */
export declare interface CustomAgentsUpdatedAgent {
    /** Description of what the agent does */
    description: string;
    /** Human-readable display name */
    displayName: string;
    /** Unique identifier for the agent */
    id: string;
    /** Model override for this agent, if set */
    model?: string;
    /** Internal name of the agent */
    name: string;
    /** Source location: user, project, inherited, remote, or plugin */
    source: string;
    /** List of tool names available to this agent, or null when all tools are available */
    tools: string[] | null;
    /** Whether the agent can be selected by the user */
    userInvocable: boolean;
}

/** Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. */
export declare interface CustomAgentsUpdatedData {
    /** Array of loaded custom agent metadata */
    agents: CustomAgentsUpdatedAgent[];
    /** Fatal errors from agent loading */
    errors: string[];
    /** Non-fatal warnings from agent loading */
    warnings: string[];
}

/** Session event "session.custom_agents_updated". Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. */
declare interface CustomAgentsUpdatedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.custom_agents_updated` with loaded custom agents plus non-fatal warnings and fatal errors. */
    data: CustomAgentsUpdatedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.custom_agents_updated". */
    type: "session.custom_agents_updated";
}
export { CustomAgentsUpdatedEvent }
export { CustomAgentsUpdatedEvent as SessionCustomAgentsUpdatedEvent }

declare type CustomModelMetadata = {
    key_name: string;
    owner_name: string;
    owner_type: "organization" | "enterprise";
    provider: string;
};

/** Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. */
export declare interface CustomNotificationData {
    /** Source-defined custom notification name */
    name: string;
    /** Source-defined JSON payload for the custom notification */
    payload: CustomNotificationPayload;
    /** Namespace for the custom notification producer */
    source: string;
    /** Optional source-defined string identifiers describing the payload subject */
    subject?: CustomNotificationSubject;
    /** Optional source-defined payload schema version */
    version?: number;
}

/** Session event "session.custom_notification". Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. */
export declare interface CustomNotificationEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. */
    data: CustomNotificationData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.custom_notification". */
    type: "session.custom_notification";
}

/** Source-defined JSON payload for the custom notification */
export declare type CustomNotificationPayload = unknown;

/** Optional source-defined string identifiers describing the payload subject */
export declare type CustomNotificationSubject = Record<string, string>;

/**
 * Type for a custom tool call delta (streaming).
 */
declare type CustomToolCallDelta = {
    index: number;
    id?: string;
    type?: "custom";
    custom?: {
        name?: string;
        input?: string;
    };
};

declare type CustomToolInputFormat = {
    type: "grammar";
    syntax: string;
    definition: string;
};

/**
 * A permission request for invoking an SDK-registered custom tool.
 */
declare type CustomToolPermissionRequest = {
    readonly kind: "custom-tool";
    /** The name of the custom tool being invoked */
    readonly toolName: string;
    /** The description of the custom tool */
    readonly toolDescription: string;
    readonly args?: unknown;
    /** When true, the tool declared skipPermission — auto-approve unless deny rules block it. */
    readonly skipPermission?: boolean;
};

/** A file included in the redacted debug bundle. */
declare interface DebugCollectLogsCollectedEntry {
    /** Relative path of the file in the staged bundle/archive. */
    bundlePath: string;
    /** Redacted output size in bytes. */
    sizeBytes: number;
    /** Source category for this entry. */
    source: DebugCollectLogsSource;
}

/** Destination for the redacted debug bundle. */
declare type DebugCollectLogsDestination = {
    kind: "archive";
    noOverwrite?: boolean;
    outputPath: string;
} | {
    kind: "directory";
    outputDirectory: string;
};

/** A caller-provided server-local file or directory to include in the debug bundle. */
declare interface DebugCollectLogsEntry {
    /** Relative path to use inside the staged bundle/archive. */
    bundlePath: string;
    /** Kind of source path to include. */
    kind: DebugCollectLogsEntryKind;
    /** Server-local source path to read. */
    path: string;
    /** How text content from this entry should be redacted. Defaults to plain-text. */
    redaction?: DebugCollectLogsRedaction;
    /** When true, collection fails if this entry cannot be read. Defaults to false, which records the entry in `skippedEntries`. */
    required?: boolean;
}

/** Kind of caller-provided debug log entry. */
declare type DebugCollectLogsEntryKind = "file" | "directory";

/** Built-in session diagnostics to include in the bundle. Omitted fields default to true. */
declare interface DebugCollectLogsInclude {
    /** Server-local path to the current process log. When set, it is included as `process.log` and its directory is searched for prior logs from the same session. */
    currentProcessLogPath?: string;
    /** Include the session event log (`events.jsonl`). Defaults to true. */
    events?: boolean;
    /** Server-local path to the session's events.jsonl file. Internal callers normally omit this and let the runtime derive it from the session. */
    eventsPath?: string;
    /** Maximum number of previous process logs to include. Defaults to 5. */
    previousProcessLogLimit?: number;
    /** Server-local process log directory to search when `currentProcessLogPath` is unavailable, useful for collecting logs for inactive sessions. */
    processLogDirectory?: string;
    /** Include process logs for the session. Defaults to true. */
    processLogs?: boolean;
    /** Include interactive shell logs written under the session's `shell-logs` directory. Defaults to true. */
    shellLogs?: boolean;
}

/** How a collected debug entry should be redacted before being staged. */
declare type DebugCollectLogsRedaction = "plain-text" | "events-jsonl";

/** Options for collecting a redacted session debug bundle. */
declare interface DebugCollectLogsRequest {
    /** Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. */
    additionalEntries?: DebugCollectLogsEntry[];
    /** Where the redacted bundle should be written. Use `archive` to produce a .tgz, or `directory` to stage redacted files for caller-managed upload/post-processing. */
    destination: DebugCollectLogsDestination;
    /** Which built-in session diagnostics to include. Omitted fields default to true. */
    include?: DebugCollectLogsInclude;
}

/** Result of collecting a redacted debug bundle. */
declare interface DebugCollectLogsResult {
    /** Files included in the redacted bundle. */
    entries: DebugCollectLogsCollectedEntry[];
    /** Destination kind that was written. */
    kind: DebugCollectLogsResultKind;
    /** Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. */
    path: string;
    /** Optional files or directories that could not be included. */
    skippedEntries?: DebugCollectLogsSkippedEntry[];
}

/** Destination kind that was written. */
declare type DebugCollectLogsResultKind = "archive" | "directory";

/** An optional debug bundle entry that could not be included. */
declare interface DebugCollectLogsSkippedEntry {
    /** Relative path requested for this bundle entry. */
    bundlePath: string;
    /** Server-local source path that could not be read. */
    path?: string;
    /** Reason the entry was skipped. */
    reason: string;
}

/** Source category for a collected debug bundle entry. */
declare type DebugCollectLogsSource = "events" | "process-log" | "shell-log" | "additional";

declare type DeepOptional<T> = {
    [P in keyof T]?: NonNullable<T[P]> extends (infer U)[] ? U[] : NonNullable<T[P]> extends object ? DeepOptional<NonNullable<T[P]>> : T[P];
};

export declare const defaultFeatureFlags: Readonly<Readonly<Record<string, boolean> & KnownFeatureFlagProperties>>;

declare enum DefinedExpFlags {
    COPILOT_CI = "copilot_ci",
    COPILOT_CLI = "copilot_cli",
    GPT_DEFAULT_MODEL = "copilot_cli_gpt_default_model",
    /**
     * Three-arm OpenAI Responses prompt-caching experiment. String-valued:
     * "control" (system prompt in `instructions`, no cache markers),
     * "explicit" (`prompt_cache_options: { mode: "explicit" }`, two marked
     * system content blocks, and a breakpoint on the latest eligible
     * conversation message), or "hybrid" (the two marked system content blocks
     * only — no `prompt_cache_options` and no latest-message breakpoint, so
     * OpenAI's implicit latest-message caching stays active). The legacy
     * booleans are still accepted: `true` → "explicit", `false` → "control".
     */
    OPENAI_EXPLICIT_PROMPT_CACHING = "copilot_cli_openai_explicit_prompt_caching",
    GPT_5_4_MINI_FOR_EXPLORE = "copilot_cli_gpt_5_4_mini_for_explore",
    DYNAMIC_INSTRUCTIONS_RETRIEVAL_MCP = "copilot_cli_dynamic_instructions_retrieval_mcp",
    /**
     * Three-arm dynamic instruction retrieval experiment. String-valued:
     * "control" (retrieval off), "blackbird" (metis-1024 model), or
     * "text-embedding" (text-embedding-3-small model). Drives both the on/off
     * gate and the embedding model selection from a single assignment so the
     * experiment can split traffic into clean thirds.
     */
    DYNAMIC_INSTRUCTIONS_RETRIEVAL_ARM = "copilot_cli_dynamic_instructions_retrieval_arm",
    /** When true, enables tool search with deferred loading for MCP and external tools (Anthropic models) */
    TOOL_SEARCH_ANTHROPIC = "copilot_cli_tool_search_anthropic",
    /** When true, enables tool search with deferred loading for MCP and external tools (OpenAI models) */
    TOOL_SEARCH_OPENAI = "copilot_cli_tool_search_openai",
    /** When true, uses Anthropic's built-in server-side tool search instead of client-side regex tool */
    TOOL_SEARCH_BUILTIN_ANTHROPIC = "copilot_cli_tool_search_builtin_anthropic",
    /**
     * When true, the built-in general-purpose subagent aggressively defers its
     * external/MCP tools behind tool search regardless of the total tool count.
     * Deferral still only takes effect on models that support tool search, and
     * the tool-search feature's universal always-eager exclusions still apply
     * (`defer: "never"` tools, the `tool_search_tool`, GitHub `web_search`, and
     * `bluebird` MCP tools are never deferred).
     */
    GENERAL_PURPOSE_SUBAGENT_AGGRESSIVE_TOOL_DEFERRAL = "copilot_cli_general_purpose_subagent_aggressive_tool_deferral",
    /**
     * When true, the built-in task subagent aggressively defers its
     * external/MCP tools behind tool search regardless of the total tool count.
     * Deferral still only takes effect on models that support tool search, and
     * the tool-search feature's universal always-eager exclusions still apply
     * (`defer: "never"` tools, the `tool_search_tool`, GitHub `web_search`, and
     * `bluebird` MCP tools are never deferred).
     */
    TASK_SUBAGENT_AGGRESSIVE_TOOL_DEFERRAL = "copilot_cli_task_subagent_aggressive_tool_deferral",
    /** Enables provider-neutral client-side tool search for ordinary function-calling models. */
    TOOL_SEARCH_CLIENT_GENERIC = "copilot_cli_tool_search_client_generic",
    /** When true, enables the rubber-duck subagent for adversarial feedback */
    RUBBER_DUCK_AGENT = "copilot_cli_rubber_duck_gpt_claude",
    /** When true, enables the GitHub Context sidekick agent that publishes context to the session inbox */
    GITHUB_CONTEXT_SIDEKICK_AGENT = "copilot_cli_github_context_sidekick_agent",
    /** When true, makes repeated read_agent calls default to unread turns since the previous read */
    READ_AGENT_INCREMENTAL_READS = "copilot_cli_read_agent_incremental_reads",
    /** When true, the client honors the server's multi-turn Auto-mode drift schedule to skip redundant router calls. */
    MULTI_TURN_ROUTING = "copilot_cli_multi_turn_routing",
    /**
     * Multi-turn v2. When true, the client also sends prior user messages so
     * the router scores conversational context rather than the current turn
     * alone. Implies the v1 drift schedule, but is a separate experiment with
     * its own cohort, so a v1 actor never picks up v2's behavior.
     */
    MULTI_TURN_CONTEXT_ROUTING = "copilot_cli_multi_turn_context_routing",
    /** When true, resolves Auto mode through the single-call POST /auto endpoint. */
    AUTO_V2_ENDPOINT = "copilot_cli_auto_v2_endpoint",
    /**
     * When true, enables MCP Apps (SEP-1865) UI extension passthrough — io.modelcontextprotocol/ui
     * capability negotiation, _meta.ui forwarding, ui:// resource auto-fetch, app-only tool
     * visibility filtering, and /mcp-app/* proxy endpoints. Local override: COPILOT_MCP_APPS=true.
     */
    MCP_APPS = "copilot_cli_mcp_apps",
    /** When true, uses ask_user / ask_user_2 prompt wording that reduces unnecessary user clarification requests (A/B experiment) */
    REDUCE_USER_INTERVENTION_PROMPTS = "copilot_cli_reduce_user_intervention_prompts",
    /** When true, guards against premature task_complete right after plan approval: strengthens the exit_plan_mode message and nudges autopilot to keep going instead of stopping (A/B experiment) */
    PLAN_IMPLEMENTATION_GUARD = "copilot_cli_plan_implementation_guard",
    /** When true, enables the client-side task-completion-criteria telemetry judge: on the first eligible user message after task_complete, a background LLM judges whether the agent satisfied the user's original request (telemetry only, A/B experiment) */
    TASK_COMPLETION_CRITERIA = "copilot_cli_task_completion_criteria",
    /** When true, enables the CLI search subagent tool (server-side ExP rollout, independent of the static feature flag) */
    SEARCH_SUBAGENT = "copilot_cli_search_subagent",
    /** Default model identifier assigned to the CLI search subagent by ExP */
    SEARCH_SUBAGENT_MODEL = "copilot_cli_search_subagent_model",
    /** When true, enables the CLI execution subagent tool (server-side ExP rollout, independent of the static feature flag) */
    EXECUTION_SUBAGENT = "copilot_cli_execution_subagent",
    /** String-valued model id override for the CLI execution subagent. */
    EXECUTION_SUBAGENT_MODEL = "copilot_cli_execution_subagent_model",
    /** When true, surfaces MCP `CallToolResult._meta` (incl. `_meta.ifc`) on `ToolResultExpanded.mcpMeta` for the FIDES labelling engine */
    FIDES_IFC = "copilot_cli_fides_ifc",
    /** When true, enables the async-only shell tool surface */
    ASYNC_ONLY_SHELL = "copilot_cli_async_only_shell",
    /** When true, uses compact CLI system prompt and tool guidance */
    COMPACT_SYSTEM_PROMPT = "copilot_cli_compact_system_prompt",
    /** When true, uses compact prompt guidance for task, read_agent, list_agents, and stop-shell tools */
    COMPACT_TASK_TOOL_PROMPT = "copilot_cli_compact_task_tool_prompt",
    /** When true, removes line number prefixes from view tool output */
    NO_VIEW_LINE_NUMBERS = "copilot_cli_no_view_line_numbers",
    /** When true, omits the per-turn `<sql_tables>` system reminder from the CLI user message (A/B experiment) */
    NO_SQL_TABLES_REMINDER = "copilot_cli_no_sql_tables_reminder",
    /** When true, batches notifications and injects read-tool results for completed background tasks */
    BACKGROUND_TASK_NOTIFICATION_PAYLOADS = "copilot_cli_background_task_notification_payloads",
    /** When true, enables Copilot Subconscious for cross-session context sharing (A/B via ExP) */
    COPILOT_SUBCONSCIOUS = "copilot_cli_subconscious",
    /** Numeric override for the max events per flush batch in the remote session exporter */
    REMOTE_EXPORT_MAX_EVENTS_PER_FLUSH = "copilot_cli_remote_export_max_events_per_flush",
    /** Numeric override for the non-steerable safety flush interval (ms) in the remote session exporter */
    REMOTE_EXPORT_SAFETY_INTERVAL_MS = "copilot_cli_remote_export_safety_interval_ms",
    /** When true, preserves reasoning across turns (`reasoning.context: "all_turns"`) for supported GPT models */
    PRESERVE_REASONING = "copilot_cli_preserve_reasoning",
    /** When true, reuses a Responses WebSocket and its response chain across user messages. */
    WEBSOCKET_RESPONSES_PERSISTENT = "copilot_cli_websocket_responses_persistent",
    /**
     * When true, enables model-provider native ("hosted") web search for models that
     * advertise the `webSearch` capability (OpenAI Responses today). Gates attaching the
     * hosted `{ type: "web_search" }` tool and surfacing the resulting `web_search_call`
     * items as "Searched the web" timeline rows.
     */
    NATIVE_WEB_SEARCH = "copilot_cli_native_web_search",
    /**
     * When true (and the base `AUTOPILOT_OBJECTIVES` flag is enabled), autopilot
     * `task_complete` requests are verified by a bounded, read-only independent
     * completion reviewer sub-agent before completion is accepted. Rollout gated via ExP.
     */
    AUTOPILOT_COMPLETION_REVIEWER = "copilot_cli_autopilot_completion_reviewer",
    /**
     * When true, extends the autopilot completion reviewer so it also runs for
     * plain autopilot completions that have no active `/goal` objective (it
     * otherwise runs only while an objective is active). Orthogonal to
     * {@link DefinedExpFlags.AUTOPILOT_COMPLETION_REVIEWER_STEERING}, which controls
     * the reviewer's ground data. Rollout gated via ExP.
     */
    AUTOPILOT_COMPLETION_REVIEWER_PLAIN_AUTOPILOT = "copilot_cli_autopilot_completion_reviewer_plain_autopilot",
    /**
     * When true, the autopilot completion reviewer verifies the `task_complete`
     * summary against the full task-span request — the opening message plus any
     * later steering — instead of the task's opening request alone, in every mode
     * (both `/goal` objectives and plain autopilot). Orthogonal to
     * {@link DefinedExpFlags.AUTOPILOT_COMPLETION_REVIEWER_PLAIN_AUTOPILOT}, which
     * controls where the reviewer runs. Rollout gated via ExP.
     */
    AUTOPILOT_COMPLETION_REVIEWER_STEERING = "copilot_cli_autopilot_completion_reviewer_steering",
    /**
     * Requests detailed reasoning summaries as if `--enable-reasoning-summaries` was passed.
     * Team repositories are statically enabled. ExP is enable-only: a true assignment enables
     * other repositories, while false or unassigned cannot disable the team default.
     */
    ENABLE_REASONING_SUMMARIES = "copilot_cli_enable_reasoning_summaries",
    /**
     * Three-arm reasoning-summaries experiment folded into one flag (see {@link parseReasoningSummariesArm}):
     * - `false` / `"control"`      → summaries visible, no hint (control)
     * - `true` / `"off_with_hint"` → summaries hidden by default + "ctrl+t" footer hint (treatment)
     * - `"off_no_hint"`            → summaries hidden by default, no hint (treatment, hint isolated out)
     *
     * A single flag makes the invalid "hint without hidden default" combination unrepresentable.
     */
    REASONING_SUMMARIES_OFF_BY_DEFAULT = "copilot_cli_reasoning_summaries_off_by_default",
    /** When true, nudges a reasoning-only completed turn to continue instead of stopping silently. */
    REASONING_ONLY_CONTINUATION = "copilot_cli_reasoning_only_continuation",
    /** When true, disables CLI outer-loop size truncation; CompactionProcessor truncates as a last resort instead. */
    NO_OUTER_LOOP_TRUNCATION = "copilot_cli_no_outer_loop_truncation",
    /** When true, enables the session-search sidekick agent */
    SESSION_SEARCH_SIDEKICK_AGENT = "copilot_cli_session_search_sidekick_agent",
    /** When true, enables the cloud session-search sidekick agent */
    CLOUD_SESSION_SEARCH_SIDEKICK_AGENT = "copilot_cli_cloud_session_search_sidekick_agent",
    /** When true, shows the GitHub Copilot desktop-app install nudge at startup. Rollout gated via ExP. */
    APP_INSTALL_NUDGE = "copilot_cli_app_install_nudge",
    /**
     * When true, recovers Anthropic content refusals (stop_reason: "refusal")
     * by re-issuing the request on the model's configured fallback and surfacing
     * a visible notice. Rollout gated via ExP.
     */
    ANTHROPIC_REFUSAL_FALLBACK = "copilot_cli_anthropic_refusal_fallback",
    /** When true, new clean worktrees default to the repository's default branch. */
    WORKTREE_DEFAULT_BRANCH = "copilot_cli_worktree_default_branch",
    /** When true, enables explicit autopilot objectives via `/autopilot <objective>` (and the `/goal` alias). Rollout gated via ExP. */
    AUTOPILOT_OBJECTIVES = "copilot_cli_autopilot_objectives",
    /** When true, enables content exclusion for users outside its static availability tier. */
    CONTENT_EXCLUSION = "copilot_cli_content_exclusion"
}

/** Human-readable title for a system notification, used as the notification hook title. */
export declare function describeSystemNotificationKind(kind: SystemNotification): string;

declare type DirectNativeSessionRegistration = {
    dispose(): void;
    ready: Promise<void>;
    isReady: boolean;
};

declare type DisableBypassPermissionsMode = "disable";

/** Canvas available in the current session. */
declare interface DiscoveredCanvas {
    /** Actions the agent or host may invoke on an open instance */
    actions?: CanvasAction[];
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Short, single-sentence description shown to the agent in canvas catalogs. */
    description: string;
    /** Human-readable canvas name */
    displayName: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Owning extension display name, when available */
    extensionName?: string;
    /** Host-local PNG path for the canvas icon, when supplied */
    icon?: string;
    /** JSON Schema for canvas open input */
    inputSchema?: CanvasJsonSchema;
}

/** Discovered extension metadata and persistent enablement state. */
declare interface DiscoveredExtension {
    /** Whether this extension's persistent per-ID preference is enabled */
    enabled: boolean;
    /** Source-qualified ID accepted by both server and session extension enablement methods */
    id: string;
    /** Human-readable extension name */
    name: string;
    /** Absolute path to the extension entry module, suitable for revealing it in a file manager */
    path: string;
    /** Containing plugin metadata for plugin-contributed extensions */
    plugin?: DiscoveredExtensionPlugin;
    /** Discovery source */
    source: DiscoveredExtensionSource;
}

/** Effective extension loading and agent-management mode */
declare type DiscoveredExtensionMode = "disabled" | "load_only" | "load_and_augment";

/** Installed plugin that contributes a discovered extension. */
declare interface DiscoveredExtensionPlugin {
    /** Installed plugin name */
    name: string;
}

/** Extensions discovered from persisted Copilot home state and their effective loading mode. Launch-scoped additional plugins are not included. */
declare interface DiscoveredExtensions {
    /** Discovered user and enabled installed-plugin extensions from persisted Copilot home state */
    extensions: DiscoveredExtension[];
    /** Effective extension loading mode. Defaults to load_and_augment when unset. */
    mode: DiscoveredExtensionMode;
}

/** Source-qualified extension identifiers to persistently disable for future sessions. */
declare interface DiscoveredExtensionsDisableRequest {
    /** Source-qualified user or plugin extension IDs to disable */
    ids: string[];
}

/** Source-qualified extension identifiers to persistently enable for future sessions. */
declare interface DiscoveredExtensionsEnableRequest {
    /** Source-qualified user or plugin extension IDs to enable */
    ids: string[];
}

/** Persisted extension discovery source */
declare type DiscoveredExtensionSource = "user" | "plugin";

/** MCP server discovered by `mcp.discover`, with config source, optional plugin source, transport type, and enabled state. */
declare interface DiscoveredMcpServer {
    /** Whether the server is enabled (not in the disabled list) */
    enabled: boolean;
    /** Server name (config key) */
    name: string;
    /** Configuration source: user, workspace, plugin, or builtin */
    source: McpServerSource_2;
    /** Plugin name that provided this server, when source is plugin. */
    sourcePlugin?: string;
    /** Plugin version that provided this server, when source is plugin. */
    sourcePluginVersion?: string;
    /** Server transport type: stdio, http, sse (deprecated), or memory */
    type?: DiscoveredMcpServerType;
}

/** Server transport type: stdio, http, sse (deprecated), or memory */
declare type DiscoveredMcpServerType = "stdio" | "http" | "sse" | "memory";

declare interface Disposable_2 {
    dispose(): void | Promise<void>;
}

declare interface DisposableTelemetrySender extends TelemetrySender {
    /** Deliver telemetry using the credential of the session that produced it. */
    sendTelemetryForUser?(event: TelemetryEvent_2, copilotUser: CopilotUserResponse | undefined): void;
    dispose(): void;
    setExtraFeatures(features: Record<string, string>): void;
    setInternalCorrelationIds?(internalCorrelationIds: SessionCorrelationIds | undefined): void;
    /**
     * Optional accessor for the current engagement id. Implemented by
     * `SessionTelemetryController`; forwarded by the parent CLI when spawning a
     * detached child so engagement-scoped analytics roll up correctly.
     */
    getEngagementId?(): string | undefined;
    /** Live gate for restricted host-only engine-message telemetry. */
    shouldEmitHostEngineTelemetry?(): boolean;
    /** Live gate for a child session's own credential. */
    shouldEmitHostEngineTelemetryFor?(copilotUser: CopilotUserResponse | undefined): boolean;
}

/**
 * Arms of the three-arm dynamic instruction retrieval experiment
 * ({@link DefinedExpFlags.DYNAMIC_INSTRUCTIONS_RETRIEVAL_ARM}):
 * - "control": retrieval disabled
 * - "blackbird": retrieval enabled using the metis-1024 embedding model
 * - "text-embedding": retrieval enabled using the text-embedding-3-small model
 */
declare const DYNAMIC_INSTRUCTIONS_RETRIEVAL_ARMS: readonly ["control", "blackbird", "text-embedding"];

/** A dynamic context board entry (projection without content). */
declare interface DynamicContextBoardEntry {
    src: string;
    name: string;
    description: string;
    read_count: number;
    count: number;
}

/** A dynamic context item row (full content, for read-back). */
declare interface DynamicContextItemRow {
    repository: string;
    branch: string;
    src: string;
    name: string;
    description: string;
    content: string;
    read_count: number;
    count: number;
}

declare type DynamicInstructionsRetrievalArm = (typeof DYNAMIC_INSTRUCTIONS_RETRIEVAL_ARMS)[number];

declare interface EffectivePluginContext {
    readonly requestedWorkingDirectory: string;
    readonly resolvedWorkingDirectory: string;
    readonly settingsRoot: string;
    readonly gitRoot?: string;
    readonly trustRoot?: string;
    readonly trusted: boolean;
    readonly trustSource: "allow-all" | "authoritative" | "persisted-folder" | "persisted-worktree" | "none";
}

declare interface EffectivePluginResolution {
    readonly generation: number;
    readonly snapshot: EffectivePluginSnapshot;
}

declare interface EffectivePluginSnapshot {
    readonly plugins: readonly InstalledPlugin[];
    readonly inventory: readonly PluginActivationDecision[];
    readonly context: EffectivePluginContext;
    readonly fingerprint: string;
}

declare type EffectivePluginTrustContext = {
    mode: "persisted";
} | {
    mode: "authoritative";
    trusted: boolean;
    source: "interactive" | "ide" | "sdk-host" | "acp-host";
};

/** The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed) */
export declare type ElicitationCompletedAction = "accept" | "decline" | "cancel";

/** Opaque JSON value submitted for one field in accepted `elicitation.completed` form content. */
export declare type ElicitationCompletedContent = unknown;

/** Elicitation request completion with the user's response */
export declare interface ElicitationCompletedData {
    /** The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed) */
    action?: ElicitationCompletedAction;
    /** The submitted form data when action is 'accept'; keys match the requested schema fields */
    content?: Record<string, ElicitationCompletedContent>;
    /** Request ID of the resolved elicitation request; clients should dismiss any UI for this request */
    requestId: string;
}

/** Session event "elicitation.completed". Elicitation request completion with the user's response */
export declare interface ElicitationCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Elicitation request completion with the user's response */
    data: ElicitationCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "elicitation.completed". */
    type: "elicitation.completed";
}

/** Elicitation request; may be form-based (structured input) or URL-based (browser redirect) */
export declare interface ElicitationRequestedData {
    /** The source that initiated the request (MCP server name, or absent for agent-initiated) */
    elicitationSource?: string;
    /** Message describing what information is needed from the user */
    message: string;
    /** Elicitation mode; "form" for structured input, "url" for browser-based. Defaults to "form" when absent. */
    mode?: ElicitationRequestedMode;
    /** Unique identifier for this elicitation request; used to respond via session.respondToElicitation() */
    requestId: string;
    /** JSON Schema describing the form fields to present to the user (form mode only) */
    requestedSchema?: ElicitationRequestedSchema;
    /** Tool call ID from the LLM completion; used to correlate with CompletionChunk.toolCall.id for remote UIs */
    toolCallId?: string;
    /** URL to open in the user's browser (url mode only) */
    url?: string;
    [key: string]: unknown;
}

/** Session event "elicitation.requested". Elicitation request; may be form-based (structured input) or URL-based (browser redirect) */
export declare interface ElicitationRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Elicitation request; may be form-based (structured input) or URL-based (browser redirect) */
    data: ElicitationRequestedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "elicitation.requested". */
    type: "elicitation.requested";
}

/** Elicitation mode; "form" for structured input, "url" for browser-based. Defaults to "form" when absent. */
export declare type ElicitationRequestedMode = "form" | "url";

/** JSON Schema describing the form fields to present to the user (form mode only) */
export declare interface ElicitationRequestedSchema {
    /** Form field definitions, keyed by field name */
    properties: Record<string, unknown>;
    /** List of required field names */
    required?: string[];
    /** Schema type indicator (always 'object') */
    type: "object";
}

declare interface ElicitRequestFormParams extends TaskAugmentedRequestParams, Record<string, unknown> {
    mode?: "form";
    message: string;
    requestedSchema: {
        type: "object";
        properties: Record<string, PrimitiveSchemaDefinition>;
        required?: string[];
    };
}

declare type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams;

declare interface ElicitRequestURLParams extends TaskAugmentedRequestParams, Record<string, unknown> {
    mode: "url";
    message: string;
    elicitationId?: string;
    url: string;
}

declare type ElicitRequestWithToolCallId = ElicitRequestFormParams & {
    toolCallId?: string;
};

declare interface ElicitResult extends Record<string, unknown> {
    action: "accept" | "decline" | "cancel";
    content?: Record<string, string | number | boolean | string[]>;
    _meta?: Record<string, unknown>;
}

/** Embedded binary resource contents identified by a URI, with an optional MIME type and a base64-encoded blob. */
export declare interface EmbeddedBlobResourceContents {
    /** Base64-encoded binary content of the resource */
    blob: string;
    /** MIME type of the blob content */
    mimeType?: string;
    /** URI identifying the resource */
    uri: string;
}

/** Embedded binary resource contents identified by a URI, with an optional MIME type and a base64-encoded blob. */
declare interface EmbeddedBlobResourceContents_2 {
    /** Base64-encoded binary content of the resource */
    blob: string;
    /** MIME type of the blob content */
    mimeType?: string;
    /** URI identifying the resource */
    uri: string;
}

/** Embedded text resource contents identified by a URI, with an optional MIME type and a text payload. */
export declare interface EmbeddedTextResourceContents {
    /** MIME type of the text content */
    mimeType?: string;
    /** Text content of the resource */
    text: string;
    /** URI identifying the resource */
    uri: string;
}

/** Embedded text resource contents identified by a URI, with an optional MIME type and a text payload. */
declare interface EmbeddedTextResourceContents_2 {
    /** MIME type of the text content */
    mimeType?: string;
    /** Text content of the resource */
    text: string;
    /** URI identifying the resource */
    uri: string;
}

/**
 * Emitted once per direct user (or autopilot) turn when the embedding retrieval
 * system folds dynamically-retrieved instructions (MCP server instructions,
 * skill instructions) into the user message's model-facing payload.
 *
 * The injected content lives inside the user message itself; this event exists
 * for observability/telemetry/benchmarking only — it does not add a separate
 * message to the conversation.
 */
declare type EmbeddingRetrievalInjectionEvent = {
    kind: "embedding_retrieval_injection";
    turn?: number;
    /** Per-source counts (e.g., { "mcp-server": 2, "skill": 1 }). */
    counts: Record<string, number>;
    /** Per-source result names. */
    names: Record<string, string[]>;
    /** Total number of instructions injected across all sources. */
    total: number;
    /** Raw injected content block (XML). Useful for debugging and benchmarks. */
    content: string;
};

/**
 * Enables a model's policy for the current user.
 * This is used for models that are available but require user consent (policy.state !== 'enabled').
 */
export declare function enableModelPolicy(authInfo: AuthInfo, modelId: string, integrationId?: string, sessionId?: string, logger?: RunnerLoggerContract_2): Promise<EnableModelPolicyResult>;

declare type EnableModelPolicyResult = {
    success: boolean;
    error?: string;
    canBeEnabled?: boolean;
};

/** Slash-prefixed command string to enqueue for FIFO processing. */
declare interface EnqueueCommandParams {
    /** Slash-prefixed command string to enqueue, e.g. '/compact' or '/model gpt-4'. Queued FIFO with any in-flight items; if the session is idle, processing kicks off immediately. */
    command: string;
}

/** Indicates whether the command was accepted into the local execution queue. */
declare interface EnqueueCommandResult {
    /** True when the command was accepted into the local execution queue. False when the call targets a session that does not support local command queueing (e.g. remote sessions). */
    queued: boolean;
}

/** Represents the Personal Access Token (PAT) or server-to-server token authentication information. */
declare type EnvAuthInfo = {
    readonly type: "env";
    readonly host: string;
    /** The login of the user. Undefined for server-to-server tokens (ghs_). */
    readonly login?: string;
    readonly token: string;
    readonly envVar: string;
    readonly copilotUser?: CopilotUserResponse;
};

/** Authentication-info variant for a token sourced from an environment variable, with host, optional login, token, and env var name. */
declare interface EnvAuthInfo_2 {
    /** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
    copilotUser?: CopilotUserResponse;
    /** Name of the environment variable the token was sourced from. */
    envVar: string;
    /** Authentication host (e.g. https://github.com or a GHES host). */
    host: string;
    /** User login associated with the token. Undefined for server-to-server tokens (those starting with `ghs_`). */
    login?: string;
    /** The token value itself. Treat as a secret. */
    token: string;
    /** Personal access token (PAT) or server-to-server token sourced from an environment variable. */
    type: "env";
}

declare type EnvValueMode = "direct" | "indirect";

/** Error details for timeline display including message and optional diagnostic information */
export declare interface ErrorData {
    /** Only set on `errorType: "rate_limit"`. When `true`, the runtime will follow this error with an `auto_mode_switch.requested` event (or silently switch if `continueOnAutoMode` is enabled). UI clients can use this flag to suppress duplicate rendering of the rate-limit error when they show their own auto-mode-switch prompt. */
    eligibleForAutoSwitch?: boolean;
    /** Fine-grained error code from the upstream provider, when available. For `errorType: "rate_limit"`, this is one of the `RateLimitErrorCode` values (e.g., `"user_weekly_rate_limited"`, `"user_global_rate_limited"`, `"rate_limited"`, `"user_model_rate_limited"`, `"integration_rate_limited"`). For `errorType: "quota"`, this is the CAPI quota error code (e.g., `"quota_exceeded"`, `"session_quota_exceeded"`, `"billing_not_configured"`). */
    errorCode?: string;
    /** Category of error (e.g., "authentication", "authorization", "quota", "rate_limit", "context_limit", "query") */
    errorType: string;
    /** Human-readable error message */
    message: string;
    /** GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs */
    providerCallId?: string;
    /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */
    serviceRequestId?: string;
    /** Error stack trace, when available */
    stack?: string;
    /** HTTP status code from the upstream request, if applicable */
    statusCode?: number;
    /** Optional URL associated with this error that the user can open in a browser */
    url?: string;
}

/** Session event "session.error". Error details for timeline display including message and optional diagnostic information */
declare interface ErrorEvent_2 {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Error details for timeline display including message and optional diagnostic information */
    data: ErrorData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.error". */
    type: "session.error";
}
export { ErrorEvent_2 as ErrorEvent }
export { ErrorEvent_2 as SessionErrorEvent }

/**
 * Outcome of a permission-escalation setter, reported by the operation itself
 * rather than reconstructed from shared session state afterwards.
 *
 * Shared state is unsafe to infer from: concurrent requests can move it between
 * the mutation and the read, and modes such as stored auto-approval intent are
 * reported without consulting managed policy. The setter is the only place that
 * knows whether *this* call took effect.
 */
export declare interface EscalationApplyResult {
    /**
     * Whether the requested state was applied. `false` means an authoritative
     * chokepoint refused it (managed policy, a feature gate, or an attach
     * target's own gate); it does not say which.
     */
    applied: boolean;
}

/**
 * All types of events that can be emitted by the `Client`.
 */
declare type Event_2 = MessageEvent_2 | ResponseEvent | ModelCallFailureEvent_2 | ModelCallStartedEvent | TurnEvent | TruncationEvent_2 | UsageInfoEvent_2 | ResponseLimitsStatusEvent | CompactionEvent | ImageProcessingEvent | BinaryAttachmentRemovalEvent | ModelCallSuccessEvent | ToolExecutionEvent | TelemetryEvent | MessagesSnapshotEvent | EmbeddingRetrievalInjectionEvent;

declare type EventData<T extends EventType> = EventPayload<T>["data"];

declare type EventHandler<T extends EventType> = (event: EventPayload<T>) => void | Promise<void>;

/** Cursor, batch size, and optional long-poll/filter parameters for reading session events. */
declare interface EventLogReadRequest {
    /** Optional non-empty list of subagent identifiers. When provided, only events owned by one of these agents are returned; ownership recognizes the event envelope's agentId plus legacy data.agentId and data.parentToolCallId markers. This filter takes precedence over agentScope. */
    agentIds?: string[];
    /** Agent-scope filter: 'primary' returns only main-agent events plus events whose type starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns events from all agents (matching wildcard-subscription behavior). Default is 'all' to preserve wildcard semantics for catch-up callers. */
    agentScope?: EventsAgentScope;
    /** Opaque cursor returned by a previous read. Omit on the first call to start from the beginning of the session's persisted history. */
    cursor?: string;
    /** Direction to page through the session's persisted event history. 'forward' (default) pages from the cursor toward newer events (or from the start of history when no cursor is given). 'backward' enables tail-first reads: with no cursor it returns the NEWEST `max` events, and the returned cursor pages toward OLDER events on subsequent backward reads. Events within a returned batch are always in chronological (oldest-to-newest) order, even for a backward read. Backward reads cover PERSISTED history only; ephemeral events are never returned by a backward read. `direction` selects the INITIAL read only: the returned cursor is self-describing, so a continuation read pages in the cursor's own direction regardless of the `direction` passed alongside it — a forward cursor always pages forward and a backward cursor always pages backward. Pass the direction that matches the cursor to avoid confusion. */
    direction?: EventsReadDirection;
    /** When false, skip ephemeral events entirely and return only durable (persisted) events. History-backfill callers that discard ephemerals anyway should set this so the read is bounded by the durable log length instead of racing the ephemeral ring on a busy session. Defaults to true (ephemerals are interleaved with durable events in creation order). Ignored by backward reads, which always cover persisted history only. */
    includeEphemeral?: boolean;
    /** Maximum number of events to return in this batch (1–1000, default 200). */
    max?: number;
    /** Either '*' to receive all event types, or a non-empty list of event types to receive */
    types?: EventLogTypes;
    /** Milliseconds to wait for new events when the cursor is at the tail of history. 0 (default) returns immediately even if no events are available. Capped at 30000ms. Ephemeral events that arrive during the wait are delivered in this batch but are NOT replayable on a subsequent read (use a non-zero waitMs in your next call to capture future ephemerals as they happen). This applies to forward reads only: a backward read always returns immediately and ignores `waitMs`, because backward paging covers persisted history only while new events append at the tail (the opposite end from a backward page), so no blocking or ephemeral delivery can occur. */
    waitMs?: number;
}

/** Indicates whether the operation succeeded. */
declare interface EventLogReleaseInterestResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** Snapshot of the current tail cursor without returning any events. Use this when a consumer wants to subscribe to live events going forward without first paginating through the entire persisted history (which would happen if `read` were called without a cursor on a long-lived session). */
declare interface EventLogTailResult {
    /** Opaque cursor pointing at the current tail of the session's persisted-events history. Pass back to `read` to receive only events that arrive AFTER this snapshot. When the session has no events, this returns the same sentinel as an unset cursor (i.e. equivalent to omitting the cursor on a first read). */
    cursor: string;
}

/** Either '*' to receive all event types, or a non-empty list of event types to receive */
declare type EventLogTypes = "*" | string[];

declare type EventPayload<T extends EventType> = Extract<SessionEvent, {
    type: T;
}>;

/** Agent-scope filter: 'primary' returns only main-agent events plus events whose type starts with 'subagent.' (matching the typed-subscription default behavior); 'all' returns events from all agents (matching wildcard-subscription behavior). Default is 'all' to preserve wildcard semantics for catch-up callers. */
declare type EventsAgentScope = "primary" | "all";

/** Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read fell back to a boundary of the remaining history (the beginning for a forward read, the tail for a backward read). The fallback page is a fresh boundary snapshot, not a continuation of the requested cursor, so it may overlap already-rendered events; on 'expired' a consumer should reset/rebase its pagination state (or deduplicate by event id) before continuing from the returned cursor. */
declare type EventsCursorStatus = "ok" | "expired";

/** Direction to page through the session's persisted event history. 'forward' pages from the cursor toward newer events; 'backward' returns the newest window first (tail-first) and pages toward older events. Events within a returned batch are always chronological (oldest-to-newest), even for a backward read. */
declare type EventsReadDirection = "forward" | "backward";

/** Batch of session events returned by a read, with cursor and continuation metadata. */
declare interface EventsReadResult {
    /** Opaque cursor for the next read. Pass back unchanged in the next read.cursor to continue from where this read left off. Always present, even when no events were returned. For a backward read this cursor pages toward OLDER events; keep passing `direction: backward` with it (the cursor is also self-describing, so backward paging continues correctly). */
    cursor: string;
    /** Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read fell back to a boundary of the remaining history. For a forward read the fallback starts from the beginning of the remaining history; for a backward read it falls back to the tail (the newest window). Because the fallback page is a fresh boundary snapshot rather than a continuation of the requested cursor, it may overlap events the consumer has already rendered — a backward fallback to the tail in particular can repeat the newest window. On 'expired', consumers should reset or rebase their local pagination state (or deduplicate by event id) before continuing from the returned cursor rather than blindly appending/prepending the fallback page. */
    cursorStatus: EventsCursorStatus;
    /** Session events for this batch, merged into a single stream in creation order: durable (persisted) events and ephemeral events interleave exactly as they were emitted. Set `includeEphemeral: false` to receive only durable events. Ephemeral events are never replayable once pruned from the in-memory ring, so a consumer that needs them should keep reading with a non-zero `waitMs`. For a backward (tail-first) read, the returned window contains persisted events only, still in chronological (oldest-to-newest) append order. */
    events: SessionEvent[];
    /** True when more events are available in the read's direction. For a forward read, true means the batch returned `max` events and more are available immediately. For a backward read, true means older persisted events remain before the returned window. */
    hasMore: boolean;
}

/**
 * Telemetry can be emitted by the runtime via progress events. Telemetry is attached to progress events
 * on a `telemetry` property whose type is this.
 */
declare type EventTelemetry<EventT = string, TelemetryT extends Telemetry = Telemetry> = {
    /**
     * The name of the telemetry event associated with the emitted runtime progress event.
     */
    event: EventT;
    /**
     * String-esque properties that are associated with the telemetry event.
     * WARNING: Do not put sensitive data here. Use restrictedProperties for that.
     */
    properties: TelemetryT["properties"];
    /**
     * String-esque properties that are associated with the telemetry event. These are only available on the restricted topics
     */
    restrictedProperties: TelemetryT["restrictedProperties"];
    /**
     * Number-esque metrics that are associated with the telemetry event. Both integer and floating point values are possible.
     */
    metrics: TelemetryT["metrics"];
    rte?: boolean;
    /** Internal first-party compatibility telemetry forwarded only to opted-in hosts. */
    forwardToHostOnly?: boolean;
};

declare type EventType = SessionEvent["type"];

export declare const EXCLUDED_MODELS: ReadonlySet<string>;

/** Slash command name and argument string to execute synchronously. */
declare interface ExecuteCommandParams {
    /** Argument string to pass to the command (empty string if none). */
    args: string;
    /** Name of the slash command to invoke (without the leading '/'). */
    commandName: string;
}

/** Error message produced while executing the command, if any. */
declare interface ExecuteCommandResult {
    /** Error message produced while executing the command, if any. Omitted when the handler succeeded. */
    error?: string;
}

/** CAPI-delivered flag name that gates the CLI execution subagent tool. */
export declare const EXECUTION_SUBAGENT_FEATURE_FLAG = "copilot_swe_agent_cli_execution_subagent";

/** Exit plan mode action */
export declare type ExitPlanModeAction = "exit_only" | "interactive" | "autopilot" | "autopilot_fleet";

/** Plan mode exit completion with the user's approval decision and optional feedback */
export declare interface ExitPlanModeCompletedData {
    /** Whether the plan was approved by the user */
    approved?: boolean;
    /** Whether edits should be auto-approved without confirmation */
    autoApproveEdits?: boolean;
    /** Free-form feedback from the user if they requested changes to the plan */
    feedback?: string;
    /** Request ID of the resolved exit plan mode request; clients should dismiss any UI for this request */
    requestId: string;
    /** Action selected by the user */
    selectedAction?: ExitPlanModeAction;
}

/** Session event "exit_plan_mode.completed". Plan mode exit completion with the user's approval decision and optional feedback */
export declare interface ExitPlanModeCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Plan mode exit completion with the user's approval decision and optional feedback */
    data: ExitPlanModeCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "exit_plan_mode.completed". */
    type: "exit_plan_mode.completed";
}

/**
 * Request for plan approval dialog.
 */
declare type ExitPlanModeRequest = {
    summary: string;
    actions: ExitPlanModeAction[];
    recommendedAction: ExitPlanModeAction;
    toolCallId?: string;
};

/** Plan approval request with plan content and available user actions */
export declare interface ExitPlanModeRequestedData {
    /** Available actions the user can take */
    actions: ExitPlanModeAction[];
    /** Full content of the plan file */
    planContent: string;
    /** Recommended action to preselect for the user */
    recommendedAction: ExitPlanModeAction;
    /** Unique identifier for this request; used to respond via session.respondToExitPlanMode() */
    requestId: string;
    /** Summary of the plan that was created */
    summary: string;
}

/** Session event "exit_plan_mode.requested". Plan approval request with plan content and available user actions */
export declare interface ExitPlanModeRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Plan approval request with plan content and available user actions */
    data: ExitPlanModeRequestedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "exit_plan_mode.requested". */
    type: "exit_plan_mode.requested";
}

declare type ExitPlanModeResponse = {
    approved: boolean;
    selectedAction?: ExitPlanModeAction;
    autoApproveEdits?: boolean;
    feedback?: string;
    /**
     * When true, the tool result tells the agent to end its turn without
     * starting implementation, so the client can restore the session model and
     * auto-submit a fresh implementation turn on it. Set by the CLI only when a
     * distinct plan configuration actually ran the planning turn — i.e. the plan
     * model, reasoning effort, or context tier differed from the session's, so
     * the restored implementation turn runs on different settings. When the plan
     * configuration matches the session's, this stays unset to preserve the
     * seamless same-turn handoff.
     */
    deferImplementation?: boolean;
};

export declare function expandCapiSanityFlagsEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;

export declare const experimentalFeatureFlagDescriptions: Readonly<Record<FeatureFlag, string>>;

/** Type-safe key for known experiment flags */
declare type ExpFlagKey = `${DefinedExpFlags}`;

/**
 * ExP flags record. Keyed by arbitrary string because the TAS API
 * returns parameters beyond the statically-known DefinedExpFlags.
 */
declare type ExpFlags = Record<string, ExpFlagValue>;

/** Value type for ExP (Experiment Platform) flags */
declare type ExpFlagValue = string | number | boolean | null;

/** Discovered extension metadata, including source-qualified ID, name, discovery source, status, and optional process ID. */
declare interface Extension {
    /** Source-qualified ID (e.g., 'project:my-ext', 'user:auth-helper', 'plugin:my-plugin:my-ext') */
    id: string;
    /** Extension name (directory name) */
    name: string;
    /** Process ID if the extension is running */
    pid?: number;
    /** Discovery source: project (.github/extensions/), user (~/.copilot/extensions/), plugin (installed plugin), or session (session-state/<id>/extensions/) */
    source: ExtensionSource;
    /** Current status: running, disabled, failed, or starting */
    status: ExtensionStatus;
}

/** Slim input shape for extension_context attachments; identity fields are runtime-derived. */
declare interface ExtensionContextPushInput {
    /** Caller-supplied JSON payload (required, may be null but not undefined) */
    payload: unknown;
    /** Human-readable composer pill label */
    title: string;
    /** Attachment type discriminator */
    type: "extension_context";
}

/**
 * Controller interface for managing extensions (subprocess-based tools).
 * Implemented by the server layer and injected into the session via updateOptions.
 */
export declare interface ExtensionController {
    /** Whether this controller can author a factory in its current live configuration. */
    canAuthorFactory(): boolean;
    /** Path to the SDK configured for this controller's extension loader. */
    getSdkPath(): string;
    /** List all discovered extensions with their current status. */
    listExtensions(): Array<{
        id: string;
        name: string;
        source: string;
        status: string;
        pid?: number;
    }>;
    /** Enable a disabled extension and reload to apply. */
    enableExtension(id: string): Promise<void>;
    /** Disable an extension, stop its process, and remove its tools. */
    disableExtension(id: string): Promise<void>;
    /** Reload all extensions from disk. */
    reloadExtensions(): Promise<void>;
    /** Reload one extension from disk. */
    reloadExtension(id: string): Promise<void>;
    /** Author and reload a session-scoped factory through the extension host. */
    authorFactory?(args: unknown, requestPermission: (request: PermissionRequest_2) => Promise<PermissionRequestResult>): Promise<ToolResultExpanded>;
}

/** Extensions discovered for the session, with their current status. */
declare interface ExtensionList {
    /** Discovered extensions and their current status */
    extensions: Extension[];
}

/**
 * A permission request for a dangerous extension management operation (scaffold, reload).
 */
declare type ExtensionManagementPermissionRequest = {
    readonly kind: "extension-management";
    /** The operation being performed */
    readonly operation: string;
    /** The extension name (for scaffold) */
    readonly extensionName?: string;
    readonly autoApproval?: AutoApproval;
};

/**
 * A permission request for an extension that wants to influence the permission system.
 * Fired at registration time when an extension declares skipPermission tools,
 * opts into permission request handling, or registers hooks.
 */
declare type ExtensionPermissionAccessRequest = {
    readonly kind: "extension-permission-access";
    /** The name of the extension */
    readonly extensionName: string;
    /** Which capabilities the extension is requesting */
    readonly capabilities: string[];
    readonly autoApproval?: AutoApproval;
};

/** Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. */
export declare interface ExtensionsAttachmentsPushedData {
    /** Attachments contributed by an extension; the host should surface these as composer pills and forward them via the next session.send call. */
    attachments: Attachment[];
}

/** Session event "session.extensions.attachments_pushed". Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. */
declare interface ExtensionsAttachmentsPushedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.extensions.attachments_pushed` with extension-contributed attachments for the next send. */
    data: ExtensionsAttachmentsPushedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.extensions.attachments_pushed". */
    type: "session.extensions.attachments_pushed";
}
export { ExtensionsAttachmentsPushedEvent }
export { ExtensionsAttachmentsPushedEvent as SessionExtensionsAttachmentsPushedEvent }

/** Source-qualified extension identifier to disable for the session. */
declare interface ExtensionsDisableRequest {
    /** Source-qualified extension ID to disable */
    id: string;
}

/** Source-qualified extension identifier to enable for the session. */
declare interface ExtensionsEnableRequest {
    /** Source-qualified extension ID to enable */
    id: string;
}

/** Payload of `session.extensions_loaded` listing discovered extensions and their statuses. */
export declare interface ExtensionsLoadedData {
    /** Array of discovered extensions and their status */
    extensions: ExtensionsLoadedExtension[];
}

/** Session event "session.extensions_loaded". Payload of `session.extensions_loaded` listing discovered extensions and their statuses. */
declare interface ExtensionsLoadedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.extensions_loaded` listing discovered extensions and their statuses. */
    data: ExtensionsLoadedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.extensions_loaded". */
    type: "session.extensions_loaded";
}
export { ExtensionsLoadedEvent }
export { ExtensionsLoadedEvent as SessionExtensionsLoadedEvent }

/** A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status. */
export declare interface ExtensionsLoadedExtension {
    /** Source-qualified extension ID (e.g., 'project:my-ext', 'user:auth-helper', 'plugin:my-plugin:my-ext') */
    id: string;
    /** Extension name (directory name) */
    name: string;
    /** Discovery source */
    source: ExtensionsLoadedExtensionSource;
    /** Current status: running, disabled, failed, or starting */
    status: ExtensionsLoadedExtensionStatus;
}

/** Discovery source */
export declare type ExtensionsLoadedExtensionSource = "project" | "user" | "plugin" | "session";

/** Current status: running, disabled, failed, or starting */
export declare type ExtensionsLoadedExtensionStatus = "running" | "disabled" | "failed" | "starting";

/** Discovery source: project (.github/extensions/), user (~/.copilot/extensions/), plugin (installed plugin), or session (session-state/<id>/extensions/) */
declare type ExtensionSource = "project" | "user" | "plugin" | "session";

/** Current status: running, disabled, failed, or starting */
declare type ExtensionStatus = "running" | "disabled" | "failed" | "starting";

/** External tool completion notification signaling UI dismissal */
export declare interface ExternalToolCompletedData {
    /** Request ID of the resolved external tool request; clients should dismiss any UI for this request */
    requestId: string;
}

/** Session event "external_tool.completed". External tool completion notification signaling UI dismissal */
export declare interface ExternalToolCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** External tool completion notification signaling UI dismissal */
    data: ExternalToolCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral?: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "external_tool.completed". */
    type: "external_tool.completed";
}

declare type ExternalToolCompletion = {
    status: "success";
    result: ExternalToolResult;
} | {
    status: "failure";
    error: string;
} | {
    status: "cancelled";
    message?: string;
};

export declare interface ExternalToolDefinition {
    name: string;
    description: string;
    /** Human-readable display title shown in the tool call timeline. Falls back to name if not set. */
    title?: string;
    parameters?: Record<string, unknown>;
    /**
     * When true, explicitly indicates this tool is intended to override a built-in tool
     * of the same name. If an external tool name clashes with a built-in tool and this
     * flag is not set, session creation will fail with an error.
     */
    overridesBuiltInTool?: boolean;
    /** When true, the tool can execute without a permission prompt. */
    skipPermission?: boolean;
    /**
     * Controls whether this tool is eligible for automatic deferral when the
     * tool-search mechanism is active.
     * - `"auto"` (default): the tool may be deferred when the total tool count
     *   exceeds the deferral threshold.
     * - `"never"`: the tool is always included in the initial tool list sent to
     *   the model, even when tool search is enabled. Use this for tools that the
     *   host system prompt mandates the model call.
     */
    defer?: "auto" | "never";
    /**
     * When true, a successful call to this tool ends the agent turn: the tool
     * phase halts instead of sending the tool result back to the model for
     * another round. A failed call (for example input validation) leaves the
     * loop running so the model can read the error and retry. Use this for
     * tools whose whole purpose is to terminate the turn.
     */
    isTerminal?: boolean;
    /**
     * Opaque, host-defined metadata forwarded verbatim from the SDK client.
     * Keys are namespaced and not part of the stable public contract; the
     * runtime may recognize specific keys (e.g. telemetry policy) to inform
     * host-specific behavior (e.g. the reserved
     * `github.com/copilot:safeForTelemetry` key).
     */
    metadata?: Record<string, unknown>;
}

/** Serializable external tool request, inferred from the event schema (minus the requestId added by the store). */
declare type ExternalToolRequest = Omit<ExternalToolRequestedEvent["data"], "requestId">;

/** External tool invocation request for client-side tool execution */
export declare interface ExternalToolRequestedData {
    /** Arguments to pass to the external tool */
    arguments?: unknown;
    /** Unique identifier for this request; used to respond via session.respondToExternalTool() */
    requestId: string;
    /** Session ID that this external tool request belongs to */
    sessionId: string;
    /** Tool call ID assigned to this external tool invocation */
    toolCallId: string;
    /** Name of the external tool to invoke */
    toolName: string;
    /** W3C Trace Context traceparent header for the execute_tool span */
    traceparent?: string;
    /** W3C Trace Context tracestate header for the execute_tool span */
    tracestate?: string;
    /** Active session working directory, when known. */
    workingDirectory?: string;
}

/** Session event "external_tool.requested". External tool invocation request for client-side tool execution */
export declare interface ExternalToolRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** External tool invocation request for client-side tool execution */
    data: ExternalToolRequestedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "external_tool.requested". */
    type: "external_tool.requested";
}

/** Tool call result (string or expanded result object) */
declare type ExternalToolResult = string | ExternalToolTextResultForLlm;

/** Expanded external tool result payload */
declare interface ExternalToolTextResultForLlm {
    /** Base64-encoded binary results returned to the model */
    binaryResultsForLlm?: ExternalToolTextResultForLlmBinaryResultsForLlm[];
    /** Structured content blocks from the tool */
    contents?: ExternalToolTextResultForLlmContent[];
    /** Optional error message for failed executions */
    error?: string;
    /** Execution outcome classification. Optional for back-compat; normalized to 'success' (or 'failure' when error is present) when missing or unrecognized. */
    resultType?: string;
    /** Detailed log content for timeline display */
    sessionLog?: string;
    /** Text result returned to the model */
    textResultForLlm: string;
    /** Tool references returned by a tool-search override: names of deferred tools to surface to the model. When set, the tool result is materialized as `tool_reference` content blocks (rather than plain text) so the model knows which deferred tools are now available. */
    toolReferences?: string[];
    /** Optional tool-specific telemetry */
    toolTelemetry?: Record<string, unknown>;
    [key: string]: unknown;
}

/** Binary result returned by a tool for the model */
declare interface ExternalToolTextResultForLlmBinaryResultsForLlm {
    /** Base64-encoded binary data */
    data: string;
    /** Human-readable description of the binary data */
    description?: string;
    /** Optional metadata from the producing tool. */
    metadata?: Record<string, unknown>;
    /** MIME type of the binary data */
    mimeType: string;
    /** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
    type: ExternalToolTextResultForLlmBinaryResultsForLlmType;
}

/** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
declare type ExternalToolTextResultForLlmBinaryResultsForLlmType = "image" | "resource";

/** A content block within a tool result, which may be text, terminal output, image, audio, or a resource */
declare type ExternalToolTextResultForLlmContent = ExternalToolTextResultForLlmContentText | ExternalToolTextResultForLlmContentTerminal | ExternalToolTextResultForLlmContentShellExit | ExternalToolTextResultForLlmContentImage | ExternalToolTextResultForLlmContentAudio | ExternalToolTextResultForLlmContentResourceLink | ExternalToolTextResultForLlmContentResource;

/** Audio content block with base64-encoded data */
declare interface ExternalToolTextResultForLlmContentAudio {
    /** Base64-encoded audio data */
    data: string;
    /** MIME type of the audio (e.g., audio/wav, audio/mpeg) */
    mimeType: string;
    /** Content block type discriminator */
    type: "audio";
}

/** Image content block with base64-encoded data */
declare interface ExternalToolTextResultForLlmContentImage {
    /** Base64-encoded image data */
    data: string;
    /** MIME type of the image (e.g., image/png, image/jpeg) */
    mimeType: string;
    /** Content block type discriminator */
    type: "image";
}

/** Embedded resource content block with inline text or binary data */
declare interface ExternalToolTextResultForLlmContentResource {
    /** The embedded resource contents, either text or base64-encoded binary */
    resource: ExternalToolTextResultForLlmContentResourceDetails;
    /** Content block type discriminator */
    type: "resource";
}

/** The embedded resource contents, either text or base64-encoded binary */
declare type ExternalToolTextResultForLlmContentResourceDetails = EmbeddedTextResourceContents_2 | EmbeddedBlobResourceContents_2;

/** Resource link content block referencing an external resource */
declare interface ExternalToolTextResultForLlmContentResourceLink {
    /** Human-readable description of the resource */
    description?: string;
    /** Icons associated with this resource */
    icons?: ExternalToolTextResultForLlmContentResourceLinkIcon[];
    /** MIME type of the resource content */
    mimeType?: string;
    /** Resource name identifier */
    name: string;
    /** Size of the resource in bytes */
    size?: number;
    /** Human-readable display title for the resource */
    title?: string;
    /** Content block type discriminator */
    type: "resource_link";
    /** URI identifying the resource */
    uri: string;
}

/** Icon image for a resource */
declare interface ExternalToolTextResultForLlmContentResourceLinkIcon {
    /** MIME type of the icon image */
    mimeType?: string;
    /** Available icon sizes (e.g., ['16x16', '32x32']) */
    sizes?: string[];
    /** URL or path to the icon image */
    src: string;
    /** Theme variant this icon is intended for */
    theme?: ExternalToolTextResultForLlmContentResourceLinkIconTheme;
}

/** Theme variant this icon is intended for */
declare type ExternalToolTextResultForLlmContentResourceLinkIconTheme = "light" | "dark";

/** Shell command exit metadata with optional output preview */
declare interface ExternalToolTextResultForLlmContentShellExit {
    /** Working directory where the shell command was executed */
    cwd?: string;
    /** Exit code from the completed shell command */
    exitCode: number;
    /** Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. */
    outputPreview?: string;
    /** Whether outputPreview is known to be incomplete or truncated */
    outputTruncated?: boolean;
    /** Shell id, as assigned by Copilot runtime */
    shellId: string;
    /** Content block type discriminator */
    type: "shell_exit";
}

/** Terminal/shell output content block with optional exit code and working directory */
declare interface ExternalToolTextResultForLlmContentTerminal {
    /** Working directory where the command was executed */
    cwd?: string;
    /** Process exit code, if the command has completed */
    exitCode?: number;
    /** Terminal/shell output text */
    text: string;
    /** Content block type discriminator */
    type: "terminal";
}

/** Plain text content block */
declare interface ExternalToolTextResultForLlmContentText {
    /** The text content */
    text: string;
    /** Content block type discriminator */
    type: "text";
}

export declare function extractExpFlagsFromResponse(response: CopilotExpAssignmentResponse): ExpFlags;

export declare function extractFeatureFlagEnvOverrides(resolvedFeatureFlags: FeatureFlags | undefined, env: NodeJS.ProcessEnv): Readonly<Record<string, boolean>>;

declare type ExtraKnownMarketplaces = Record<string, {
    source: ExtraKnownMarketplaceSource;
    /**
     * Opt this marketplace's installed plugins into the session-start
     * auto-update, like the built-in first-party marketplaces. Only honored
     * when set in the user's own settings; a managed (MDM/server) or
     * repository-level opt-in is accepted but currently ignored.
     */
    autoUpdate?: boolean;
    [key: string]: unknown;
}>;

declare type ExtraKnownMarketplaceSource = {
    source: "directory";
    path: string;
    [key: string]: unknown;
} | {
    source: "git";
    url: string;
    ref?: string;
    [key: string]: unknown;
} | {
    source: "github";
    repo: string;
    ref?: string;
    [key: string]: unknown;
};

declare interface FactoriesManageApi {
    getSdkPath(): string;
    getMetadataSnapshot(): FactoryMeta[];
    listRuns(params?: FactoryListRunsRequest): Promise<FactoryListRunsResult>;
    getRun(runId: string): Promise<{
        factoryName: string;
        run: FactoryRunResult;
    }>;
    author?(input: unknown): Promise<ToolResultExpanded>;
}

/** Parameters for cooperatively aborting a factory body. */
declare interface FactoryAbortRequest {
    /** Factory run identifier. */
    runId: string;
}

/** Acknowledgement that a factory request was accepted. */
declare interface FactoryAckResult {
}

/** Options for one factory-scoped subagent call. */
declare interface FactoryAgentOptions {
    /** Optional custom agent name for the subagent. This field is accepted but not yet honored. */
    agent?: string;
    /** Optional context tier for the subagent. This field is accepted but not yet honored. */
    contextTier?: ContextTier_2;
    /** Optional label distinguishing otherwise identical memoized agent calls. */
    label?: string;
    /** Optional model identifier for the subagent. */
    model?: string;
    /** Optional reasoning effort for the subagent. This field is accepted but not yet honored. */
    reasoningEffort?: string;
    /** Optional JSON Schema for structured agent output. */
    schema?: unknown;
}

/** Parameters for one factory-scoped subagent call. */
declare interface FactoryAgentRequest {
    /** Opaque token identifying the current factory execution attempt. */
    executionToken: string;
    /** Factory run identifier that owns the subagent. */
    factoryRunId: string;
    /** Subagent execution options. */
    opts: FactoryAgentOptions;
    /** Prompt to send to the subagent. */
    prompt: string;
}

/** Result of one factory-scoped subagent call. */
declare interface FactoryAgentResult {
    /** Agent result, omitted when the agent produced no result. */
    result?: unknown;
}

/** Prompt-safe durable identity and live status for a direct factory agent. */
declare interface FactoryAgentSummary {
    activeMs: number;
    activity?: string;
    agentId: string;
    agentType: string;
    completedAt?: number;
    label: string;
    phaseId: string | null;
    requestedModel?: string;
    resolvedModel?: string;
    runId: string;
    startedAt?: number;
    status: string;
    toolCallId: string;
}

/** Parameters for cancelling a factory run. */
declare interface FactoryCancelRequest {
    /** Factory run identifier. */
    runId: string;
}

export declare interface FactoryCompletionNotificationFallback {
    runId: string;
    factoryName: string;
    status: string;
    consumedSubagents: number;
    consumedNanoAiu: number;
    elapsedMs: number;
    attempt: number;
}

export declare interface FactoryCompletionNotificationLifecycle {
    isStillValid(): boolean;
    commitConsumption(): void;
    invalidate(): void;
}

export declare interface FactoryCompletionNotificationRecord {
    runId: string;
    factoryName: string;
    argsJson: string;
    status: string;
    resultJson?: string;
    error?: string;
    failureJson?: string;
    reason?: string;
    snapshotJson?: string;
    consumedSubagents: number;
    consumedNanoAiu: number;
    elapsedMs: number;
    approvedLimitsJson?: string;
    attempt: number;
}

/** Current factory phase identity. */
declare interface FactoryCurrentPhase {
    id: string;
    ordinal: number | null;
}

/** Declared or approved factory resource ceilings. */
declare interface FactoryDeclaredLimits {
    maxAiCredits?: number;
    maxConcurrentSubagents?: number;
    maxTotalSubagents?: number;
    timeoutSeconds?: number;
}

/** Execution-critical factory storage operation. */
declare type FactoryDurableOperation = "createRun" | "markRunStarted" | "finishRun" | "reserveAgent" | "releaseAgent" | "chargeCredit" | "addElapsed" | "reconcileCreditTotal" | "journalGet" | "journalPut";

/** Parameters sent to the owning extension to execute a factory closure. */
declare interface FactoryExecuteRequest {
    /** Factory input value. */
    args: unknown;
    /** Opaque token identifying this factory execution attempt. */
    executionToken: string;
    /** Registered factory name. */
    name: string;
    /** Factory run identifier. */
    runId: string;
}

/** Result returned by an extension factory closure. */
declare interface FactoryExecuteResult {
    /** Factory result value. */
    result?: unknown;
}

/** Parameters for paging factory progress. */
declare interface FactoryGetRunProgressRequest {
    /** Exclusive forward cursor. */
    afterSeq?: number;
    /** Exclusive backward cursor. */
    beforeSeq?: number;
    /** Maximum records to return. Defaults to 200 and is capped at 500. */
    limit?: number;
    /** Optional phase identifier used to scope records and cursors. */
    phaseId?: string;
    /** Factory run identifier. */
    runId: string;
}

/** Parameters for retrieving a factory run. */
declare interface FactoryGetRunRequest {
    /** Factory run identifier. */
    runId: string;
}

/** Parameters for reading a factory journal entry. */
declare interface FactoryJournalGetRequest {
    /** Opaque token identifying the current factory execution attempt. */
    executionToken: string;
    /** Namespaced journal key. */
    key: string;
    /** Factory run identifier. */
    runId: string;
}

/** Result of reading a factory journal entry. */
declare interface FactoryJournalGetResult {
    /** Whether the journal contained the requested key. */
    hit: boolean;
    /** Cached JSON result. The hit field distinguishes a cached JSON null from a miss. */
    resultJson?: unknown;
}

/** Parameters for storing a factory journal entry. */
declare interface FactoryJournalPutRequest {
    /** Opaque token identifying the current factory execution attempt. */
    executionToken: string;
    /** Namespaced journal key. */
    key: string;
    /** JSON result to memoize. */
    resultJson: unknown;
    /** Factory run identifier. */
    runId: string;
}

/** Static resource ceilings declared by a factory before it runs. */
declare interface FactoryLimits {
    /** Maximum number of factory subagents that may run concurrently. Must be positive when present. */
    maxConcurrentSubagents?: number;
    /** Maximum total number of factory subagents that may be spawned. Must be positive when present. */
    maxTotalSubagents?: number;
    /** Maximum AI credits consumed by factory subagents and descendants. This post-paid ceiling is soft. */
    maxAiCredits?: number;
    /**
     * Maximum accumulated active-execution time, in seconds. Active execution includes the entire extension body,
     * subprocess waits, queued-agent waits, and sleeps. The limit is armed from the remaining headroom when a run
     * resumes; time between attempts is not counted. Must be finite and positive when present.
     */
    timeoutSeconds?: number;
}

/** Parameters for paging factory runs. */
declare interface FactoryListRunsRequest {
    /** Exclusive forward cursor. */
    afterSeq?: number;
    /** Exclusive backward cursor. */
    beforeSeq?: number;
    /** Maximum terminal runs to return. Defaults to 200 and is capped at 500. */
    limit?: number;
}

/** A page of factory runs in durable creation order. */
declare interface FactoryListRunsResult {
    /** Whether terminal runs newer than this page exist. */
    hasMoreNewer?: boolean;
    /** Newest terminal-run cursor in this page, or null when the terminal window is empty. */
    newestSeq?: number | null;
    /** Oldest terminal-run cursor in this page, or null when the terminal window is empty. */
    oldestSeq?: number | null;
    /** Number of terminal runs older than this page. */
    omittedOlder?: number;
    runs: FactoryRunSummary[];
}

/** One ordered factory progress line. */
declare interface FactoryLogLine {
    /** Progress line kind. */
    kind: FactoryLogLineKind;
    /** Monotonic sequence number within the factory run. */
    seq: number;
    /** Progress text. */
    text: string;
}

/** Kind of factory progress line. */
declare type FactoryLogLineKind = "log" | "phase";

/** Parameters for recording factory progress. */
declare interface FactoryLogRequest {
    /** Opaque token identifying the current factory execution attempt. */
    executionToken: string;
    /** Ordered progress lines to append. */
    lines: FactoryLogLine[];
    /** Factory run identifier. */
    runId: string;
}

/** Registration metadata for an extension-authored factory. */
declare interface FactoryMeta {
    /** Stable factory name used for invocation. */
    name: string;
    /** Human-readable factory description. */
    description: string;
    /** Display metadata for the progress phases the factory may report. */
    phases: Array<{
        title: string;
        detail?: string;
    }>;
    /** JSON Schema describing the value available to the factory as `ctx.args`. */
    argsSchema?: unknown;
    /** Optional resource ceilings presented to the user before execution. */
    limits?: FactoryLimits;
}

/** Operation gated by a factory permission request. */
export declare type FactoryPermissionOperation = "run" | "author";

/** A declared phase shown in a factory permission prompt. */
export declare interface FactoryPermissionPhase {
    /** Optional phase detail */
    detail?: string;
    /** Phase title */
    title: string;
}

declare type FactoryPermissionPhase_2 = {
    readonly title: string;
    readonly detail?: string;
};

/**
 * A permission request for running or authoring a factory.
 */
declare type FactoryPermissionRequest = {
    readonly kind: "factory";
    readonly operation: "run" | "author";
    readonly name: string;
    readonly description: string;
    readonly phases: readonly FactoryPermissionPhase_2[];
    readonly maxConcurrentSubagents?: number;
    readonly maxTotalSubagents?: number;
    readonly timeoutSeconds?: number;
    readonly maxAiCredits?: number;
    readonly declaredMaxConcurrentSubagents?: number;
    readonly declaredMaxTotalSubagents?: number;
    readonly declaredTimeoutSeconds?: number;
    readonly declaredMaxAiCredits?: number;
    readonly approvalKey: string;
    readonly canPersistApproval: boolean;
    readonly autoApproval?: AutoApproval;
};

/** Durable lifecycle and timing for one factory phase. */
declare interface FactoryPhaseObservation {
    accumulatedActiveMs: number;
    completedAt?: number;
    currentActiveMs: number;
    detail?: string;
    entryCount: number;
    id: string;
    lastEnteredRunAttempt: number;
    liveAgentCount: number;
    ordinal: number | null;
    startedAt?: number;
    status: FactoryPhaseStatus;
    title: string;
    totalAgentCount: number;
}

/** Derived lifecycle state of a factory phase. */
declare type FactoryPhaseStatus = "pending" | "active" | "completed" | "skipped";

/** One durable factory progress record. */
declare interface FactoryProgressLine {
    /** Resume attempt that emitted this record. */
    attempt: number;
    /** Progress record kind. */
    kind: FactoryLogLineKind;
    /** Phase active when the record was emitted, or null before any phase. */
    phaseId: string | null;
    /** Epoch milliseconds when the record was persisted. */
    recordedAt: number;
    /** Global monotonic sequence number within the run. */
    seq: number;
    /** Prompt-safe progress text. */
    text: string;
}

/** A bidirectional page of factory progress. */
declare interface FactoryProgressPage {
    hasMoreNewer: boolean;
    hasMoreOlder: boolean;
    newestSeq: number | null;
    oldestSeq: number | null;
    records: FactoryProgressLine[];
    /** Run revision reflected by this page. */
    revision: number;
}

/** Parameters for resuming a factory run from its persisted identity. */
declare interface FactoryResumeRequest {
    /** Optional per-invocation resource ceiling overrides. */
    limits?: FactoryRunLimits;
    /** Factory run identifier. */
    runId: string;
}

/** Resolved persisted factory identity and resumed run envelope. */
declare interface FactoryResumeResult {
    /** Persisted factory name resolved for the resumed run. */
    factoryName: string;
    /** Terminal resumed run envelope. */
    run: FactoryRunResult;
}

/** Durable factory resource consumption. */
declare interface FactoryRunConsumed {
    activeMs: number;
    nanoAiu: number;
    subagents: number;
}

/** Full factory run observability detail. */
declare interface FactoryRunDetail {
    activeSegmentStartedAt: number | null;
    agents: FactoryAgentSummary[];
    approved: FactoryDeclaredLimits | null;
    completedAt: number | null;
    consumed: FactoryRunConsumed;
    createdAt: number;
    currentPhase: FactoryCurrentPhase | null;
    declaredLimits: FactoryDeclaredLimits;
    declaredPhaseCount: number;
    description: string;
    factoryName: string;
    liveAgentCount: number;
    observedAt: number;
    phases: FactoryPhaseObservation[];
    progress: FactoryProgressPage;
    revision: number;
    runId: string;
    startedAt: number | null;
    status: FactoryRunStatus;
    terminal: FactoryRunTerminal | null;
    totalSpawnedAgentCount: number;
    updatedAt: number;
}

/** Machine-readable factory run failure. */
declare type FactoryRunFailure = {
    kind: FactoryRunFailureKind;
    runId: string;
    type: "factory_limit_reached";
    value: number;
} | {
    reason: string;
    runId: string;
    type: "factory_resume_declined";
} | {
    code: string;
    operation: FactoryDurableOperation;
    runId: string;
    type: "factory_durable_failure";
} | {
    drainedNanoAiu: number;
    runId: string;
    type: "factory_accounting_incomplete";
};

/** Cumulative resource ceiling that stopped a factory run. */
declare type FactoryRunFailureKind = "maxTotalSubagents" | "timeoutSeconds" | "maxAiCredits";

/** Wire-only per-invocation factory resource ceiling overrides. */
declare interface FactoryRunLimits {
    /** Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. */
    maxAiCredits?: number;
    /** Maximum number of factory subagents that may run concurrently. */
    maxConcurrentSubagents?: number;
    /** Maximum total number of factory subagents that may be admitted. */
    maxTotalSubagents?: number;
    /** Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. */
    timeoutSeconds?: number;
}

/** Parameters for invoking a registered factory. */
declare interface FactoryRunRequest {
    /** Factory input value. */
    args: unknown;
    /** Registered factory name. */
    name: string;
    /** Factory invocation options. */
    options?: RunOptions;
}

/** Complete current or terminal factory run envelope. */
declare interface FactoryRunResult {
    /** Error message for an errored run. */
    error?: string;
    /** Machine-readable failure details for an errored run. */
    failure?: FactoryRunFailure;
    /** Reason for a halted or cancelled run. */
    reason?: string;
    /** Completed factory result. */
    result?: unknown;
    /** Factory run identifier. */
    runId: string;
    /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */
    snapshot?: unknown;
    /** Current or terminal factory run status. */
    status: FactoryRunStatus;
}

/** Current or terminal state of a factory run. */
declare type FactoryRunStatus = "pending" | "running" | "completed" | "halted" | "cancelled" | "error";

/** Durable factory run summary with read-time live overlays. */
declare interface FactoryRunSummary {
    activeSegmentStartedAt: number | null;
    approved: FactoryDeclaredLimits | null;
    completedAt: number | null;
    consumed: FactoryRunConsumed;
    createdAt: number;
    currentPhase: FactoryCurrentPhase | null;
    declaredLimits: FactoryDeclaredLimits;
    declaredPhaseCount: number;
    description: string;
    factoryName: string;
    liveAgentCount: number;
    observedAt: number;
    revision: number;
    runId: string;
    startedAt: number | null;
    status: FactoryRunStatus;
    terminal: FactoryRunTerminal | null;
    totalSpawnedAgentCount: number;
    updatedAt: number;
}

/** Prompt-safe terminal factory outcome. */
declare interface FactoryRunTerminal {
    error?: string;
    failure?: FactoryRunFailure;
    reason?: string;
    resultPreview?: string;
}

/** Ephemeral invalidation signal for a changed factory run. */
export declare interface FactoryRunUpdatedData {
    /** Monotonic revision now available for the run. */
    revision: number;
    runId: string;
}

/** Session event "factory.run_updated". Ephemeral invalidation signal for a changed factory run. */
export declare interface FactoryRunUpdatedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Ephemeral invalidation signal for a changed factory run. */
    data: FactoryRunUpdatedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "factory.run_updated". */
    type: "factory.run_updated";
}

declare interface FactoryTaskLifecycleChange {
    type: FactoryTaskLifecycleChangeType;
    task: AgentTaskEntry;
}

declare type FactoryTaskLifecycleChangeType = "created" | "status" | "model_resolved" | "settled";

declare type FactoryTaskLifecycleObserver = (change: FactoryTaskLifecycleChange) => void;

declare interface FactoryUsageCoordinator {
    acquireProducer(): FactoryUsageProducerLease;
    enqueueCharge(chargeId: string, nanoAiu: number): void;
    drain(): Promise<void>;
}

declare interface FactoryUsageProducerLease {
    release(): void;
}

export declare type FeatureFlag = keyof KnownFeatureFlagProperties | (string & {});

export declare type FeatureFlagAssignmentSink = Pick<FeatureFlagService, "setExpAssignments">;

export declare type FeatureFlagAvailability = "on" | "team" | "staff-or-experimental" | "staff" | "experimental" | "off";

export declare const featureFlagAvailability: Readonly<Record<FeatureFlag, FeatureFlagSpec>>;

export declare type FeatureFlagChangeListener = (flags: FeatureFlags, expFlags: ExpFlags, response: CopilotExpAssignmentResponse) => void;

export declare interface FeatureFlagInitOptions {
    isStaff: boolean;
    isExperimental: boolean;
    isTeam: boolean;
    streamerMode?: boolean;
    config?: UserSettings;
    firstLaunchAt?: Date;
    flagOverrides?: Partial<Record<FeatureFlag, boolean>>;
    expFlagOverrides?: Partial<Record<ExpFlagKey, ExpFlagValue>>;
    settings?: SettingsStorageContext;
}

declare interface FeatureFlagResolutionOptions {
    baseFlags?: FeatureFlags;
    env?: NodeJS.ProcessEnv;
    useCurrentEnv?: boolean;
    config?: UserSettings;
    flagOverrides?: Partial<Record<FeatureFlag, boolean>>;
}

export declare type FeatureFlags = Readonly<Record<string, boolean> & KnownFeatureFlagProperties>;

export declare class FeatureFlagService implements Disposable_2 {
    private readonly handle;
    private snapshot;
    private nativeHandleActive;
    private readonly listeners;
    private latestSecondaryAssignmentContext;
    constructor(options: FeatureFlagInitOptions, constructorOptions?: {
        deferExpResponse?: boolean;
    });
    dispose(): void;
    static createForTest(options: FeatureFlagInitOptions): FeatureFlagService;
    resetInstance(): void;
    resetExpResponse(): void;
    setExpAssignments(assignments?: CopilotExpAssignmentResponse): void;
    getLegacyFlag(flag: FeatureFlag): boolean;
    getFlag(flag: FeatureFlag): Promise<boolean>;
    getAllFlags(): FeatureFlags;
    getAllExpFlagsSync(): ExpFlags;
    getLatestExpResponse(): CopilotExpAssignmentResponse;
    getLatestAssignmentIfPresent(): string | undefined;
    getSecondaryAssignmentIfPresent(): string | undefined;
    captureSecondaryAssignmentContext(assignmentContext: string): void;
    subscribe(listener: FeatureFlagChangeListener): () => void;
    applyConfigOverride(partialConfig: Partial<UserSettings>): void;
    waitForExpResponse(): Promise<void>;
    getFlagWithExpOverride(expFlag: ExpFlagKey, featureFlag: FeatureFlag): Promise<boolean>;
    getExpFlag(flag: ExpFlagKey): Promise<ExpFlagValue | undefined>;
    isGpt54MiniForExploreEnabled(): Promise<boolean>;
    getDynamicInstructionsRetrievalArm(): Promise<DynamicInstructionsRetrievalArm | undefined>;
    isDynamicInstructionsRetrievalMcpEnabled(): Promise<boolean>;
    isGptDefaultModelEnabled(): Promise<boolean>;
    isFidesIfcEnabled(): Promise<boolean>;
    isCopilotSubconsciousEnabled(): Promise<boolean>;
    isPreserveReasoningEnabled(): Promise<boolean>;
    isWebsocketResponsesPersistentEnabled(): Promise<boolean>;
    isNativeWebSearchEnabled(): Promise<boolean>;
    /**
     * Resolve the arm of the three-arm OpenAI Responses prompt-caching
     * experiment. Falls back to "control" when there is no assignment and the
     * static `OPENAI_EXPLICIT_PROMPT_CACHING` flag is off.
     */
    getOpenAiPromptCachingArm(): Promise<OpenAiPromptCachingArm>;
    isAutopilotCompletionReviewerEnabled(): Promise<boolean>;
    /**
     * Whether the reviewer should also run for plain autopilot completions that
     * have no active `/goal` objective (it otherwise runs only while an objective
     * is active). Orthogonal to {@link isAutopilotCompletionReviewerSteeringEnabled},
     * which controls the ground data. Control is today's behavior (reviewer only on
     * `/goal`).
     */
    isAutopilotCompletionReviewerPlainAutopilotEnabled(): Promise<boolean>;
    /**
     * Whether the reviewer should verify against the full task-span request — the
     * opening message plus any later steering — instead of the task's opening
     * request alone, in every mode. Orthogonal to
     * {@link isAutopilotCompletionReviewerPlainAutopilotEnabled}, which controls
     * where the reviewer runs. Control is today's behavior (opening request only).
     */
    isAutopilotCompletionReviewerSteeringEnabled(): Promise<boolean>;
    getReasoningSummariesArm(): Promise<ReasoningSummariesArmState>;
    isReasoningOnlyContinuationEnabled(): Promise<boolean>;
    destroy(): void;
    private notifyListeners;
}

export declare interface FeatureFlagSpec {
    availability: FeatureFlagAvailability;
    capiSanity: boolean;
}

export declare const featureFlagToExpFlag: Partial<Record<FeatureFlag, ExpFlagKey>>;

/** A file touched during a session. */
declare interface FileRow {
    session_id: string;
    file_path: string;
    tool_name?: string;
    turn_index?: number;
    first_seen_at?: string;
}

/**
 * Minimal capture surface that the rewind file store exposes to the tool
 * wrapper. Lives in core (no CLI dependencies) so it can be referenced from
 * {@link import("../../tools").ToolConfig} and the tool layer, while the
 * concrete implementation lives in the runtime's rewind store.
 *
 * The wrapper is intentionally dumb about turn lifecycle: it only resolves the
 * set of paths an editing tool is about to mutate, asks the store to back up
 * their pre-edit state, runs the inner tool, then tells the store which paths
 * were written so it can compute the post-edit ownership token. All turn
 * bookkeeping (which user message a capture belongs to, finalize, restore)
 * lives in the store. Every successful `stageToolPreimages` call must be
 * paired with `recordToolResult`, including when the wrapped tool fails.
 */
declare interface FileSnapshotCapture {
    /**
     * Back up the pre-edit ("preimage") state of every path before the inner
     * tool mutates it. Must complete before the inner tool runs. First write
     * wins per path within a turn, so calling this repeatedly for a path that
     * was already staged this turn is a no-op.
     */
    stageToolPreimages(paths: string[]): Promise<void>;
    /**
     * Record the post-edit ("postimage") state of every path the inner tool
     * wrote. Used both as mutation evidence (a path whose postimage equals its
     * preimage produced no real change and is dropped at finalize) and as an
     * ownership token (restore only reverts a path whose current content still
     * matches the postimage Copilot last produced, so user/bash edits made
     * afterwards are never clobbered).
     */
    recordToolResult(paths: string[]): Promise<void>;
}

/** Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. */
declare type FilterMapping = Record<string, ContentFilterMode_2> | ContentFilterMode_2;

export declare function flattenAvailabilityMap(): Record<string, FeatureFlagAvailability>;

/** Flat token pricing (legacy format, API < 2026-06-01). */
declare type FlatTokenPrices = {
    input_price?: number;
    output_price?: number;
    cache_price?: number;
    batch_size?: number;
};

/** Optional user prompt to combine with the fleet orchestration instructions. */
declare interface FleetStartRequest {
    /** Optional user prompt to combine with fleet instructions */
    prompt?: string;
}

/** Indicates whether fleet mode was successfully activated. */
declare interface FleetStartResult {
    /** Whether fleet mode was successfully activated */
    started: boolean;
}

/** Folder path to add to trusted folders. */
declare interface FolderTrustAddParams {
    /** Folder path to mark as trusted */
    path: string;
}

/** Folder path to check for trust. */
declare interface FolderTrustCheckParams {
    /** Folder path to check */
    path: string;
}

/** Folder trust check result. */
declare interface FolderTrustCheckResult {
    /** Whether the folder is trusted */
    trusted: boolean;
}

declare type ForgeSkillProposalChangeType = "added" | "modified" | "deleted" | "renamed";

declare interface ForgeSkillProposalManifestEntry {
    path: string;
    change_type: ForgeSkillProposalChangeType;
    old_path?: string;
    before_hash?: string | null;
    after_hash?: string | null;
    before_content?: string | null;
}

declare interface ForgeSkillProposalRecord extends ForgeSkillProposalScope {
    id: string;
    trigger_mode: ForgeSkillProposalTriggerMode;
    status: ForgeSkillProposalStatus;
    fingerprint?: string;
    manifest: ForgeSkillProposalManifestEntry[];
    summary?: ForgeSkillProposalSummary;
    superseded_by?: string;
    failure_reason?: string;
    created_at: string;
    updated_at: string;
}

declare interface ForgeSkillProposalScope {
    repo_owner?: string;
    repo_name?: string;
    git_root_path: string;
    branch_name: string;
}

declare type ForgeSkillProposalStatus = "generating" | "ready" | "reviewing" | "accepted" | "rejected" | "superseded" | "failed";

declare interface ForgeSkillProposalSummary {
    file_count: number;
    added_count: number;
    modified_count: number;
    deleted_count: number;
    renamed_count: number;
}

declare type ForgeSkillProposalTriggerMode = "auto_close" | "on_demand";

/** A Forge-specific trajectory event derived from session tool activity. */
declare interface ForgeTrajectoryEventRow {
    session_id: string;
    tool_call_id?: string;
    turn_index?: number;
    event_type: string;
    command?: string;
    output?: string;
    exit_code?: number;
    event_key?: string;
    event_value?: string;
    created_at?: string;
}

/** Scope for reading Forge trajectory events across sessions. */
declare interface ForgeTrajectoryScope {
    repository?: string;
    branch?: string;
    limitSessions?: number;
}

/**
 * Type for a function tool call delta (streaming).
 */
declare type FunctionToolCallDelta = {
    index: number;
    id?: string;
    type?: "function";
    function?: {
        name?: string;
        arguments?: string;
    };
};

/**
 * Retrieves the list of available models based on availability, policies, and integration including
 * capabilities and billing information, which may be cached from previous calls.
 *
 * This list is in order of preference to be the default model for new sessions where the first model is
 * the most preferred.  It can be empty if no models are available.
 *
 * @deprecated Used solely by vscode-copilot-chat extension, use {@link retrieveAvailableModels} instead.
 */
export declare function getAvailableModels(authInfo: AuthInfo): Promise<AvailableModel[]>;

export declare function getCapiSanityFeatureFlags(): FeatureFlag[];

declare type GetCompletionWithToolsOptions = {
    /**
     * If `true`, then calls do `getCompletionWithTools` will check if the token counts of
     * the initial system messages, user messages, and tool definitions, exceed the limits
     * of the model. If they do, then the call will throw an error. If `false`, then the
     * call will not perform any checks.
     *
     * Defaults to `false`.
     */
    failIfInitialInputsTooLong?: boolean;
    toolChoice?: ChatCompletionToolChoiceOption;
    requestHeaders?: Record<string, string>;
    /** Current per-run settings for tool callbacks on clients retained across calls. */
    runtimeSettings?: RuntimeSettings_2;
    /**
     * If true, performs the request in streaming mode. This results in additional events
     * as each chunk is received from the service.
     */
    stream?: boolean;
    /**
     * If this call is a continuation of a previous `getCompletionWithTools` call, this specifies what turn
     * that conversation was/is on. This is used to determine the initial turn count in this
     * call to `getCompletionWithTools`.
     */
    initialTurnCount?: number;
    /**
     * Processors provide a way to do work during different stages of the completion with tools
     * lifecycle. Processors will be called in the order they are provided.
     */
    processors?: {
        preRequest?: IPreRequestProcessor[];
        postRequest?: IPostRequestProcessor[];
        onRequestError?: IOnRequestErrorProcessor[];
        preToolsExecution?: IPreToolsExecutionProcessor[];
        postToolExecution?: IPostToolExecutionProcessor[];
        onStreamingChunk?: IOnStreamingChunkProcessor[];
    };
    /**
     * The native-document MIME types the active model cannot ingest, computed once
     * before the turn loop via `documentHelpersCollectNativeFileAttachmentMimeTypes`. The
     * native client strips matching `file` content parts from the canonical
     * conversation at the start of every request (the native port of
     * `UnsupportedNativeFileAttachmentProcessor`, which used to run as the first
     * `preRequest` processor). Omit/empty to disable the strip.
     */
    unsupportedNativeFileMimeTypes?: string[];
    /**
     * Whether the resolved client registered the `PremiumRequestProcessor`
     * (premium-request billing-header tracking). When set, the native client
     * runs the billing port at the end of every request: it sets the
     * `X-Initiator` / `X-Interaction-Type` headers from the presence of billable
     * messages (`copilotBillingMetadata.billable === true`) and clears those
     * markers so they are not re-billed on subsequent turns. Omit/false to
     * disable (no billing-header tracking).
     */
    enablePremiumBilling?: boolean;
    /**
     * Per-tool throttle configuration (the native port of `ToolThrottleProcessor`).
     * When set with a non-empty config, the native client caps runaway bursts of the
     * configured function tools: in the `preToolsExecution` stage it denies surplus
     * calls (per-response and per-interaction caps) with a precomputed "denied" tool
     * result so they are never executed, and emits a `tool_throttled` telemetry event
     * per throttled tool. Omit/empty to disable (every call site except the main
     * agent session path).
     */
    toolThrottleConfig?: ToolThrottleConfig;
    /** Native session whose IFC state applies to this model/tool loop. */
    ifcSessionId?: string;
    /**
     * Native plan-mode write-gate configuration for this session run.
     *
     * Deliberately carries no `active` / `isPlanModeOwner` flags: the native gate
     * re-reads `sessionId`'s live agent mode on every tool batch, because
     * `exit_plan_mode` flips the mode mid-loop and the run then continues.
     */
    planModeWriteGate?: {
        /** Native session id whose live agent mode drives the gate. */
        sessionId: string;
        /** Whether this session inherited the gate from a plan-mode parent. */
        inheritedActive: boolean;
        /**
         * Native session ids of this session's plan-mode ancestors, outermost
         * first. The gate re-reads each one's live mode per tool batch, so a
         * background subagent keeps tracking its parent's mode changes.
         */
        inheritedSessionIds?: string[];
        planPath?: string;
        workingDir: string;
        isWindows: boolean;
        homeDir: string;
    };
    /**
     * Native screenshot-prune configuration (the native port of
     * `ScreenshotProcessor`). When set, the native client prunes already-tagged
     * screenshots in its `preRequest` stage — before and/or after the JS leaf
     * processors (per `preLeaf`/`postLeaf`) or after a segmented native image
     * pre-request split (per `preRequestInsertionIndex`) — capping the number of
     * screenshot images retained in long computer-use sessions, and emits a
     * `screenshot_compaction` telemetry event whenever it prunes. Omit to
     * disable.
     */
    screenshotPruneConfig?: ScreenshotPruneConfig;
    /**
     * Native image-processor pre-request configuration. When set, the native
     * model client drains/finalizes the shared image processor state in its
     * `preRequest` stage instead of relying on a JS `preRequest` processor.
     * Omit to keep image processing entirely in the JS processor pipeline.
     */
    nativeImageProcessorPreRequestConfig?: NativeImageProcessorPreRequestConfig;
    /**
     * Insertion index for the native image-processor pre-request stage within
     * `processors.preRequest`. When set with
     * `nativeImageProcessorPreRequestConfig`, Rust runs JS pre-request
     * processors before this index, then native image pre-request processing,
     * then the remaining JS pre-request processors.
     */
    nativeImageProcessorPreRequestInsertionIndex?: number;
    /**
     * Insertion index for the native image-processor post-tool stage within
     * `processors.postToolExecution`. When set with
     * `nativeImageProcessorPreRequestConfig`, Rust runs JS post-tool processors
     * before this index, then native image post-tool processing, then the
     * remaining JS post-tool processors.
     */
    nativeImageProcessorPostToolInsertionIndex?: number;
    /**
     * Signal to abort the completion request.
     */
    abortSignal?: AbortSignal;
    /**
     * Registers a wait-only tool interruption that immediate user steering can invoke.
     */
    registerSteeringInterrupt?: (interrupt: () => void) => () => void;
    /**
     * Called immediately before a host tool callback is invoked.
     */
    onToolCallStarted?: (toolCall: ActiveToolCall) => void;
    /**
     * An optional identifier for the completion with tools call. This can be used for logging
     * and tracing purposes.
     */
    callId?: string;
    /**
     * Stable trajectory identity for provider callback attribution. Unlike
     * `agentInvocationId`, this remains constant across turns and retries.
     */
    agentId?: string;
    /** Stable identity of the immediate parent trajectory. */
    parentAgentId?: string;
    /** Identity of the agent invocation (one agentic loop), distinct from the stable trajectory identity. */
    agentInvocationId?: string;
    /**
     * The reasoning effort level for the model to use, if supported by the client.
     */
    reasoningEffort?: ReasoningEffort;
    /**
     * Reasoning summary mode for providers that support configurable reasoning summaries.
     * Use "none" to suppress summary output regardless of whether reasoning is enabled.
     * Providers that do not support summary verbosity may ignore it.
     */
    reasoningSummary?: ReasoningSummary_2;
    /**
     * Output verbosity level for model clients that support it.
     */
    verbosity?: ResponseVerbosity;
    /**
     * Optional callback to refresh the tool list mid-turn. Called after each batch of
     * tool executions. If it returns a new tool array (or a promise resolving to one),
     * the toolSet and tool definitions sent to the model are rebuilt for subsequent
     * rounds within the same turn. Return undefined to keep the current tools.
     *
     * May be async to support refresh sources that require I/O (e.g. fetching the
     * updated tool list from an MCP server after a `tools/list_changed` notification).
     */
    refreshTools?: () => Tool[] | undefined | Promise<Tool[] | undefined>;
    /**
     * Optional callback to refresh the system message mid-turn. Called after each batch
     * of tool executions, alongside `refreshTools`. If it returns a new value, the
     * system message sent to the model is replaced for subsequent rounds within the
     * same turn. Return undefined (or a promise resolving to undefined) to keep the
     * current system message.
     *
     * Used when a tool transitions the session to a new mode (e.g. `exit_plan_mode`
     * switching to autopilot) and the rest of the loop should continue under the new
     * system prompt without terminating and starting a fresh user turn.
     */
    refreshSystemMessage?: () => Promise<SystemMessageContent | undefined> | SystemMessageContent | undefined;
    /**
     * Session filesystem for session-scoped file I/O (e.g. large output handling).
     */
    sessionFs?: SessionFs;
    /**
     * Callback invoked when a 401 response is received on a request that carried a
     * CAPI session token (auto-mode). The callback should clear the expired session,
     * acquire a fresh token, and return it. Returning `undefined` skips the retry.
     * Called at most once per `getCompletionWithTools` invocation.
     *
     * When the refresh re-routes to a *different* model than the in-flight one
     * (Auto v2 mints each renewal token for whichever model `/auto` picks at
     * renewal time), `modelInfoJson` must carry that model's catalog metadata:
     * the native transport only adopts the swap when the refreshed model provably
     * uses the same vendor, family, dispatch route (including WebSocket
     * eligibility), capability flags, and token limits as the model the request
     * was assembled for. Missing or incomplete metadata is treated as "cannot
     * prove", declining the retry.
     */
    onSessionTokenExpired?: () => Promise<{
        sessionToken: string;
        model: string;
        modelInfoJson?: string;
    } | undefined>;
};

/** Gets the list of available custom agents. */
export declare function getCustomAgents(authInfo: AuthInfo, workingDir: string, integrationId?: string, logger?: RunnerLoggerContract, settings?: SettingsStorageContext, additionalPlugins?: InstalledPlugin[]): Promise<SweCustomAgent[]>;

export declare function getExpFlagEnvKey(flag: ExpFlagKey): string;

/**
 * Resolve enterprise managed settings for an account **without an active
 * session**.
 *
 * Managed settings are inherently account-scoped: the server layer is keyed by
 * the authenticated host + login (see {@link managedSettingsAuthIdentity}), with
 * a device-MDM overlay. They are session-independent, so this query needs no
 * session — it lets a host (e.g. an IDE) render/gate enterprise-managed UI right
 * after startup, before the user has created a session.
 *
 * The returned {@link ResolvedManagedSettingsSnapshot.resolved} payload is
 * identical to the `session.managed_settings_resolved` event, so clients share a
 * single render path; subscribe to that event for live updates that occur within
 * a session (e.g. the hourly policy refresh).
 *
 * `resolved.settings` here is the whole-layer resolution (the server layer wins
 * outright when both channels are present), not the per-key device/MDM-wins
 * result a session enforces; read `resolved.serverResponse` /
 * `resolved.deviceResponse` and resolve them yourself when a caller needs the
 * per-key answer.
 *
 * The only fail-closed server path is the token-unavailable case
 * (`resolved.failClosed === true`); an ordinary fetch failure falls back to the
 * cache or fails **open**. With no auth context the server layer is simply
 * skipped (not failed), so an unauthenticated caller still gets any device-MDM
 * policy.
 */
export declare function getManagedSettings(input?: GetManagedSettingsInput): Promise<ResolvedManagedSettingsSnapshot>;

/** Inputs for the account-scoped {@link getManagedSettings} query. */
export declare interface GetManagedSettingsInput {
    /**
     * The account (host + login) to resolve server-managed policy for. When
     * omitted, only device MDM policy is resolved — the server layer is skipped.
     * That is still useful before the user has signed in (e.g. an IDE gating its
     * UI right after startup).
     */
    authInfo?: AuthInfo;
    /**
     * Convenience: resolve {@link authInfo} from a bearer token (+ optional
     * {@link host}) when the caller only holds a token. Ignored when `authInfo`
     * is supplied.
     */
    token?: string;
    /** GitHub host used to resolve {@link token}. Defaults to the configured host. */
    host?: string;
    /** Abort signal forwarded to the server fetch. */
    signal?: AbortSignal;
}

/** Represents the GitHub CLI authentication information. */
declare type GhCliAuthInfo = {
    readonly type: "gh-cli";
    readonly host: string;
    readonly login: string;
    readonly token: string;
    readonly copilotUser?: CopilotUserResponse;
};

/** Authentication-info variant for GitHub CLI credentials, carrying host, login, and the `gh auth token` value. */
declare interface GhCliAuthInfo_2 {
    /** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
    copilotUser?: CopilotUserResponse;
    /** Authentication host. */
    host: string;
    /** User login as reported by `gh auth status`. */
    login: string;
    /** The token returned by `gh auth token`. Treat as a secret. */
    token: string;
    /** Authentication via the `gh` CLI's saved credentials. */
    type: "gh-cli";
}

/** Options controlling what the built-in GitHub MCP server exposes. */
declare interface GitHubMcpConfigOptions {
    /** When true, use the read-write `/mcp` endpoint and expose all tools via `X-MCP-Toolsets: all`. */
    enableAllTools?: boolean;
    /** Extra toolset names to request via the `X-MCP-Toolsets` header (e.g., `["all"]`). */
    additionalToolsets?: string[];
    /** Extra tool names to request via `X-MCP-Tools` (overrides the default list when non-empty). */
    additionalTools?: string[];
    /**
     * When true, exclude MCP tools that have `gh` CLI equivalents.
     * Only the tools in `CLI_KEPT_GITHUB_MCP_TOOLS` will be exposed.
     */
    excludeGhReplaceableTools?: boolean;
    /**
     * When true, send the `X-MCP-Insiders` header to enable insiders mode on the GitHub MCP server.
     * This is only a build selector: on its own it does not change the endpoint or the exposed tools.
     */
    enableInsidersMode?: boolean;
    /**
     * When true, form-backed write tools execute directly instead of opening an
     * MCP App form. Only meaningful when MCP Apps are enabled for the session.
     */
    disableFormDeferral?: boolean;
    /**
     * When true, enable FIDES information flow control on the GitHub MCP server:
     * sends the `X-MCP-Features: ifc_labels` header (so the server attaches IFC
     * `_meta` labels to tool responses) and uses the read-write endpoint. The
     * native builder adds `search_repositories` plus the consequential write
     * sinks the IFC engine needs to observe; the actual tool list stays
     * server-side and is merged by the built-in GitHub MCP config. Separate from
     * the insiders build selector.
     * Callers are responsible for gating this option on `IFeatureFlagService.isFidesIfcEnabled()` before setting it.
     */
    enableFidesIfc?: boolean;
    /**
     * Value for the `Copilot-Integration-Id` header sent on the built-in
     * github-mcp handshake. The Copilot API gateway resolves the integration
     * for per-session-token callers from this header; without a registered id
     * it rejects the handshake with `400 unknown Copilot-Integration-Id`.
     * Omitted (or empty) lets the gateway default the value.
     */
    copilotIntegrationId?: string;
}

/** Per-session configuration for the built-in GitHub MCP server */
export declare interface GitHubMcpToolConfig {
    /** Additional GitHub MCP tools requested by the session */
    additionalTools?: string[];
    /** Additional GitHub MCP toolsets requested by the session */
    additionalToolsets?: string[];
    /** Whether to use the read-write endpoint and request all toolsets */
    enableAllTools?: boolean;
    /** Whether to request the GitHub MCP insiders build */
    enableInsidersMode?: boolean;
}

/** Public per-session configuration for the built-in GitHub MCP server. */
declare interface GitHubMcpToolConfig_2 {
    /** When true, use the read-write `/mcp` endpoint and expose all tools via `X-MCP-Toolsets: all`. */
    enableAllTools?: boolean;
    /** Extra toolset names to request via the `X-MCP-Toolsets` header (e.g., `["all"]`). */
    additionalToolsets?: string[];
    /** Extra tool names to request via `X-MCP-Tools` (overrides the default list when non-empty). */
    additionalTools?: string[];
    /** When true, send the `X-MCP-Insiders` header to enable insiders mode on the GitHub MCP server. */
    enableInsidersMode?: boolean;
    /**
     * When true, form-backed GitHub MCP tools execute directly instead of
     * opening an MCP App form. Requires MCP Apps to be enabled for the session.
     */
    disableFormDeferral?: boolean;
}

/** Pointer to a GitHub repository. */
export declare interface GitHubRepoRef {
    /** Numeric GitHub repository id */
    id?: number;
    /** Repository name (without owner) */
    name: string;
    /** Repository owner login (user or organization) */
    owner: string;
}

/** Pointer to a GitHub repository. */
declare interface GitHubRepoRef_2 {
    /** Numeric GitHub repository id */
    id?: number;
    /** Repository name (without owner) */
    name: string;
    /** Repository owner login (user or organization) */
    owner: string;
}

/** Pending external tool call request ID, with the tool result or an error describing why it failed. */
declare interface HandlePendingToolCallRequest {
    /** Error message if the tool call failed */
    error?: string;
    /** Request ID of the pending tool call */
    requestId: string;
    /** Tool call result (string or expanded result object) */
    result?: ExternalToolResult;
}

/** Indicates whether the external tool call result was handled successfully. */
declare interface HandlePendingToolCallResult {
    /** Whether the tool call result was handled successfully */
    success: boolean;
}

/** Session handoff metadata including source, context, and repository information */
export declare interface HandoffData {
    /** Additional context information for the handoff */
    context?: string;
    /** ISO 8601 timestamp when the handoff occurred */
    handoffTime: string;
    /** GitHub host URL for the source session (e.g., https://github.com or https://tenant.ghe.com) */
    host?: string;
    /** Session ID of the remote session being handed off */
    remoteSessionId?: string;
    /** Repository context for the handed-off session */
    repository?: HandoffRepository;
    /** Origin type of the session being handed off */
    sourceType: HandoffSourceType;
    /** Summary of the work done in the source session */
    summary?: string;
}

/** Session event "session.handoff". Session handoff metadata including source, context, and repository information */
declare interface HandoffEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session handoff metadata including source, context, and repository information */
    data: HandoffData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.handoff". */
    type: "session.handoff";
}
export { HandoffEvent }
export { HandoffEvent as SessionHandoffEvent }

/** Repository context for the handed-off session */
export declare interface HandoffRepository {
    /** Git branch name, if applicable */
    branch?: string;
    /** Repository name */
    name: string;
    /** Repository owner (user or organization) */
    owner: string;
}

/** Origin type of the session being handed off */
export declare type HandoffSourceType = "remote" | "local";

/** Single HTTP header entry as a name/value pair. */
export declare interface HeaderEntry {
    /** HTTP response header name as observed by the runtime. */
    name: string;
    /** HTTP response header value as observed by the runtime. */
    value: string;
}

declare type HeadersRefreshCallback = (request: HeadersRefreshRequest) => Promise<Record<string, string> | undefined> | Record<string, string> | undefined;

declare interface HeadersRefreshParams {
    serverName: string;
    serverUrl: string;
    ttlMs?: number;
}

declare type HeadersRefreshReason = "startup" | "ttl-expired" | "auth-failed";

declare interface HeadersRefreshRequest {
    serverName: string;
    serverUrl: string;
    reason: HeadersRefreshReason;
}

export declare const HELP_VISIBLE_MODELS: readonly ("claude-opus-4.8" | "claude-sonnet-4.5" | "claude-opus-4.5" | "claude-sonnet-4.6" | "claude-sonnet-5" | "claude-opus-4.6" | "claude-opus-4.7" | "claude-opus-5" | "claude-opus-4.8-fast" | "claude-fable-5" | "claude-haiku-4.5" | "gpt-5.3-codex" | "gpt-5.4" | "gpt-5.5" | "gpt-5.6-sol" | "gpt-5.6-luna" | "gpt-5.6-terra" | "mai-code-1-flash-picker" | "gpt-5.4-mini" | "gemini-3.1-pro-preview" | "gemini-3.7-flash" | "gemini-3.6-flash" | "gemini-3.5-flash" | "grok-4.5" | "kimi-k2.7-code" | "kimi-k3" | "gpt-5-mini" | "exec-agent-a" | "exec-agent-b" | "exec-agent-c" | "copilot-search-a" | "copilot-search-b" | "copilot-search-c")[];

export declare const HIDDEN_MODELS: ReadonlySet<string>;

/** Indicates whether an in-progress manual compaction was aborted. */
declare interface HistoryAbortManualCompactionResult {
    /** Whether an in-progress manual compaction was aborted. False when no manual compaction was running, when its abort controller was already aborted, or when the session is remote. */
    aborted: boolean;
}

/** Indicates whether an in-progress background compaction was cancelled. */
declare interface HistoryCancelBackgroundCompactionResult {
    /** Whether an in-progress background compaction was cancelled. False when no compaction was running, when the session is remote, or when the underlying processor was unavailable. */
    cancelled: boolean;
}

/** Parameters for clearing the conversation and seeding the window that replaces it. */
declare interface HistoryClearContextRequest {
    /** First user message of the fresh context window. Required: a cleared window holding only system and developer messages is not a conversation a model can answer, so every clear seeds the window it creates. Delivered by the enclosing turn driver once the agentic loop exits, which is why the call must be made from inside a tool handler. */
    prompt: string;
}

/** What a successful clear removed. A clear that could not be applied rejects instead of reporting a count. */
declare interface HistoryClearContextResult {
    /** Number of non-system, non-developer messages that were removed from the conversation. Zero only when the window already held no conversation. */
    messagesCleared: number;
}

/** Post-compaction context window usage breakdown */
declare interface HistoryCompactContextWindow {
    /** Token count from non-system messages (user, assistant, tool) */
    conversationTokens?: number;
    /** Current total tokens in the context window (system + conversation + tool definitions) */
    currentTokens: number;
    /** Current number of messages in the conversation */
    messagesLength: number;
    /** Token count from system message(s) */
    systemTokens?: number;
    /** Maximum token count for the model's context window */
    tokenLimit: number;
    /** Token count from tool definitions */
    toolDefinitionsTokens?: number;
}

/** Optional compaction parameters. */
declare type HistoryCompactRequest = {
    customInstructions?: string;
    tokenLimit?: number;
    trigger?: "manual" | "model_switch";
};

/** Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. */
declare interface HistoryCompactResult {
    /** Post-compaction context window usage breakdown */
    contextWindow?: HistoryCompactContextWindow;
    /** Number of messages removed during compaction */
    messagesRemoved: number;
    /** Whether compaction completed successfully */
    success: boolean;
    /** Summary text produced by compaction. Omitted when compaction did not produce a summary (e.g. failure path). */
    summaryContent?: string;
    /** Number of tokens freed by compaction */
    tokensRemoved: number;
}

/** Reason a captured file was not restored. */
declare type HistoryFileRestoreSkipReason = "user-modified" | "skipped-capture";

/** Rewind points and file-change-tracking availability for the session. */
declare interface HistoryListRewindPointsResult {
    /** Whether this session captured file changes from its first turn. */
    fileChangeTrackingEnabled: boolean;
    /** Root user turns in chronological order. Empty when `unavailableReason` is set. */
    points: HistoryRewindPoint[];
    /** Why the listed points could not be produced, when applicable; the points list is empty whenever it is set. `unsupported-remote-session` is permanent for the session and comes with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the file-change captures cannot be read while work that may still mutate them is in flight; the same request succeeds once the session settles, so a client that wants points should retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an untracked local session still lists conversation-only points and reports that through `fileChangeTrackingEnabled: false`. */
    unavailableReason?: HistoryRewindUnavailableReason;
}

/** Event boundary to preview for conversation-and-files rewind. */
declare interface HistoryPreviewRewindRequest {
    /** ID of the user.message event that begins the discarded suffix. */
    eventId: string;
}

/** Files and aggregate changes for a prospective rewind. */
declare interface HistoryPreviewRewindResult {
    /** Whether file restore is available for this session. This is authoritative: switch on it and read `reason` only when it is false. */
    available: boolean;
    /** Number of unique files in the preview. */
    fileCount: number;
    /** Files ordered by path. */
    files: HistoryRewindFilePreview[];
    /** Why file restore is unavailable, when applicable. Populated only when `available` is false and never set when `available` is true. */
    reason?: HistoryRewindUnavailableReason;
}

/** Aggregate file change represented by a rewind preview. */
declare type HistoryRewindChangeType = "created" | "deleted" | "modified";

/** A file that a conversation-and-files rewind would restore. */
declare interface HistoryRewindFilePreview {
    /** Aggregate change made across the discarded turns. */
    changeType: HistoryRewindChangeType;
    /** Lines added across the discarded turns. */
    linesAdded: number;
    /** Lines removed across the discarded turns. */
    linesRemoved: number;
    /** Absolute path of the captured file. */
    path: string;
}

/** Scope of a rewind operation. */
declare type HistoryRewindMode = "conversation" | "conversation-and-files";

/** Outcome of a rewind request. */
declare type HistoryRewindOutcome = "success" | "session-busy" | "file-change-tracking-disabled" | "unsupported-remote-session" | "files-rolled-back" | "rollback-incomplete" | "truncation-failed" | "checkpoint-cleanup-failed" | "snapshot-prune-failed";

/** A root user turn that the session can rewind to. */
declare interface HistoryRewindPoint {
    /** Whether at least one file in this turn or a later turn can be restored. */
    canRestoreFiles: boolean;
    /** ID of the user.message event that begins the discarded suffix. */
    eventId: string;
    /** Number of unique files in this turn and all later turns that have captured changes. */
    fileCount: number;
    /** Whether this turn was an automatically injected autopilot continuation. */
    isAutopilotContinuation: boolean;
    /** Lines added by this turn's captured file changes. */
    linesAdded: number;
    /** Lines removed by this turn's captured file changes. */
    linesRemoved: number;
    /** ISO timestamp of the user turn. */
    timestamp: string;
    /** Whether this turn itself captured any file changes. */
    turnChangedFiles: boolean;
    /** User-visible message text for the turn. */
    userMessage: string;
}

/** Boundary and mode for rewinding session history. */
declare interface HistoryRewindRequest {
    /** ID of the user.message event that begins the discarded suffix. */
    eventId: string;
    /** Whether to rewind only conversation history or also restore captured files. */
    mode: HistoryRewindMode;
}

/** Structured outcome of a rewind request. */
declare interface HistoryRewindResult {
    /** Failure detail. Set only for the failure and partial-failure outcomes (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`). */
    error?: string;
    /** Number of persisted events removed by conversation truncation. Present only when truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`) and for `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. */
    eventsRemoved?: number;
    /** Overall rewind outcome. This discriminates the result: it governs which of the remaining fields are populated, so consumers must switch on it before reading `eventsRemoved`, `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that populate it. */
    outcome: HistoryRewindOutcome;
    /** Absolute paths restored to their captured preimages. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. */
    restoredFiles: string[];
    /** Captured files intentionally left unchanged. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. */
    skippedFiles: HistorySkippedFileRestore[];
}

/** Reason a rewind read (rewind points, file-restore preview, or session diff) could not be answered from the session's file-change captures. */
declare type HistoryRewindUnavailableReason = "file-change-tracking-disabled" | "session-busy" | "unsupported-remote-session";

/** A captured file that rewind intentionally left unchanged. */
declare interface HistorySkippedFileRestore {
    /** Absolute path of the skipped file. */
    path: string;
    /** Reason the file was not restored. */
    reason: HistoryFileRestoreSkipReason;
}

/** Markdown summary of the conversation context (empty when not available). */
declare interface HistorySummarizeForHandoffResult {
    /** Markdown summary of the conversation context produced by an LLM. Empty string when there are no messages or when the session does not support local summarization. */
    summary: string;
}

/** Identifier of the event to truncate to; this event and all later events are removed. */
declare interface HistoryTruncateRequest {
    /** Event ID to truncate to. This event and all events after it are removed from the session. */
    eventId: string;
}

/** Number of events that were removed by the truncation. */
declare interface HistoryTruncateResult {
    /** Failure detail when checkpointCleanupFailed is true. */
    checkpointCleanupError?: string;
    /** True when conversation truncation succeeded but post-truncation workspace checkpoint cleanup failed. History is already truncated; callers may still prune snapshots but should report a checkpoint-cleanup rather than a truncation failure. */
    checkpointCleanupFailed?: boolean;
    /** Number of events that were removed */
    eventsRemoved: number;
}

/** Represents the HMAC-based authentication information. */
declare type HMACAuthInfo = {
    readonly type: "hmac";
    readonly host: "https://github.com";
    readonly hmac: string;
    readonly copilotUser?: CopilotUserResponse;
};

/** Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub host and HMAC secret. */
declare interface HMACAuthInfo_2 {
    /** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
    copilotUser?: CopilotUserResponse;
    /** HMAC secret used to sign requests. */
    hmac: string;
    /** Authentication host. HMAC auth always targets the public GitHub host. */
    host: "https://github.com";
    /** HMAC-based authentication used by GitHub-internal services. */
    type: "hmac";
}

/** Hook invocation completion details including output, success status, and error information */
export declare interface HookEndData {
    /** Error details when the hook failed */
    error?: HookEndError;
    /** Identifier matching the corresponding hook.start event */
    hookInvocationId: string;
    /** Type of hook that was invoked (e.g., "preToolUse", "postToolUse", "sessionStart") */
    hookType: string;
    /** Output data produced by the hook */
    output?: unknown;
    /** Whether the hook completed successfully */
    success: boolean;
}

/** Error details when the hook failed */
export declare interface HookEndError {
    /** Human-readable error message */
    message: string;
    /** Source label of the hook that errored (e.g. the plugin it was loaded from), when known */
    source?: string;
    /** Error stack trace, when available */
    stack?: string;
}

/** Session event "hook.end". Hook invocation completion details including output, success status, and error information */
export declare interface HookEndEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Hook invocation completion details including output, success status, and error information */
    data: HookEndData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "hook.end". */
    type: "hook.end";
}

declare type HookLifecycleEnd = {
    hookInvocationId: string;
    hookType: string;
    output?: unknown;
    success: boolean;
    error?: {
        message: string;
        stack?: string;
        source?: string;
    };
};

declare type HookLifecycleStart = {
    hookInvocationId: string;
    hookType: string;
    input?: unknown;
};

/**
 * A permission request triggered by a preToolUse hook returning `permissionDecision: "ask"`.
 * Dispatched directly to the CLI and never flows through the permission service.
 */
declare type HookPermissionRequest = {
    readonly kind: "hook";
    /** The tool call ID associated with this hook-gated prompt, when available */
    readonly toolCallId?: string;
    /** The name of the tool the hook is gating */
    readonly toolName: string;
    /** The tool call arguments */
    readonly toolArgs?: unknown;
    /** Optional message from the hook explaining why confirmation is needed */
    readonly hookMessage?: string;
    readonly autoApproval?: AutoApproval;
};

/** Ephemeral progress update from a running hook process */
export declare interface HookProgressData {
    /** Human-readable progress message from the hook process */
    message: string;
    /** When true, this status message replaces the previous temporary one instead of accumulating */
    temporary?: boolean;
}

/** Session event "hook.progress". Ephemeral progress update from a running hook process */
export declare interface HookProgressEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Ephemeral progress update from a running hook process */
    data: HookProgressData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "hook.progress". */
    type: "hook.progress";
}

/** Hook invocation start details including type and input data */
export declare interface HookStartData {
    /** Unique identifier for this hook invocation */
    hookInvocationId: string;
    /** Type of hook being invoked (e.g., "preToolUse", "postToolUse", "sessionStart") */
    hookType: string;
    /** Input data passed to the hook */
    input?: unknown;
}

/** Session event "hook.start". Hook invocation start details including type and input data */
export declare interface HookStartEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Hook invocation start details including type and input data */
    data: HookStartData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "hook.start". */
    type: "hook.start";
}

/**
 * The hook-output fields that replace content the session schema declares as a
 * required string. Naming them keeps a call site from reporting the wrong field
 * to an operator who is trying to find the offending hook.
 */
declare type HookStringField = "modifiedPrompt" | "modifiedTransformedPrompt";

declare class HostDelegatingOAuthClientProvider implements OAuthClientProvider {
    private readonly options;
    private readonly handle;
    private readonly finalizerToken;
    constructor(options: HostDelegatingOAuthClientProviderOptions);
    get nativeHandle(): number;
    get redirectUrl(): undefined;
    get clientMetadata(): OAuthClientMetadata;
    clientInformation(): OAuthClientInformationMixed | undefined;
    tokens(): OAuthTokens | undefined;
    saveTokens(tokens: OAuthTokens): void;
    applyToken(token: McpOAuthHostTokenResult): void;
    currentHostToken(): McpOAuthHostTokenResult | undefined;
    redirectToAuthorization(_authorizationUrl: URL): Promise<void>;
    saveCodeVerifier(codeVerifier: string): void;
    codeVerifier(): string;
    invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): void;
    requestReplacementToken(request: HostDelegatingOAuthRequest): Promise<McpOAuthHostTokenResult>;
}

declare interface HostDelegatingOAuthClientProviderOptions {
    initialToken?: McpOAuthHostTokenResult;
    context: McpOAuthRequestContext;
    requestToken: (request: HostDelegatingOAuthRequest) => Promise<McpOAuthHostTokenResult | undefined>;
}

declare interface HostDelegatingOAuthRequest {
    reason: McpOAuthRequestReason;
    wwwAuthenticateParams?: McpOAuthRequestContext["wwwAuthenticateParams"];
    resourceMetadata?: string;
    httpResponse?: McpOAuthRequestContext["httpResponse"];
}

declare interface HydroTelemetryOptions {
    clientName?: string;
    assignmentContext?: TelemetryAssignmentContext;
    sendRestrictedTelemetry?: boolean;
    /** Forward the restricted event to opted-in hosts without a primary Hydro write. */
    hostOnly?: boolean;
    /** Session-scoped restricted eligibility for host-only compatibility events. */
    hostOnlyRestrictedTelemetry?: boolean;
    /** Raw SDK session ID for the host notification envelope. Never written to Hydro. */
    forwardingSessionId?: string;
}

/**
 * A way for the runtime agent to callback to something with progress, results, errors, etc.
 */
declare interface IAgentCallback {
    progress(content: AgentCallbackProgressEvent, opts?: AgentCallbackProgressOptions): Promise<void | AgentCallbackProgressResponse>;
    partialResult(result: AgentCallbackPartialResultEvent): Promise<void>;
    commentReply(reply: AgentCallbackCommentReplyEvent): Promise<void>;
    checkQuota?(content: AgentCallbackCheckQuotaEvent): Promise<void | AgentCallbackCheckQuotaResponse>;
    result(result: AgentCallbackResultEvent): Promise<void>;
    error(error: AgentCallbackErrorEvent): Promise<void>;
    dispose?(): void;
    emitNamespacedProgress?(namespace: string, kind: string, content: string): Promise<void>;
}

/** Payload indicating the session is idle with no background agents or attached shell commands in flight */
export declare interface IdleData {
    /** True when the preceding agentic loop was cancelled via abort signal */
    aborted?: boolean;
}

/** Session event "session.idle". Payload indicating the session is idle with no background agents or attached shell commands in flight */
declare interface IdleEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload indicating the session is idle with no background agents or attached shell commands in flight */
    data: IdleData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.idle". */
    type: "session.idle";
}
export { IdleEvent }
export { IdleEvent as SessionIdleEvent }

export declare type IFeatureFlagService = Omit<FeatureFlagService, "destroy" | "dispose" | "resetExpResponse" | "resetInstance">;

declare interface ImageContent_2 extends BaseContentBlock {
    type: "image";
    data: string;
    mimeType: string;
}

/**
 * This event is temporary until we extract vision support from being internal to getCompletionWithTools.
 */
declare type ImageProcessingEvent = {
    kind: "image_processing";
    turn: number;
    imageProcessingMetrics: ImageProcessingMetrics;
};

declare type ImageProcessingMetrics = ({
    imagesExtractedCount: number;
    base64ImagesCount: number;
    imagesRemovedDueToSize: number;
    imagesRemovedDueToDimensions: number;
    imagesResized: number;
    imagesResolvedFromGitHubMCPCount: number;
    allImagesSendToLlm?: number;
} & Record<string, number>) | Record<string, never>;

/**
 * The inbound message that triggered an agent turn.
 * Captured from the AgentMessage delivered via write_agent or steering.
 */
declare interface InboundMessageInfo {
    /** Agent ID of the sender, if sent by another agent (undefined for steering messages) */
    fromAgentId?: string;
    /** The message content */
    content: string;
}

/**
 * Public inbox entry shape, forwarded from the native store's
 * {@link StoredInboxEntryDto} without any hand-written persistence.
 */
declare type InboxEntry = StoredInboxEntryDto;

/**
 * Configuration for infinite sessions with automatic context compaction and workspace persistence.
 * When enabled, sessions automatically manage context window limits through background compaction
 * and persist state to a workspace directory.
 */
declare interface InfiniteSessionConfig {
    /**
     * Whether infinite sessions are enabled.
     * @default true
     */
    enabled?: boolean;
    /**
     * Context utilization threshold (0.0-1.0) at which background compaction starts.
     * Compaction runs asynchronously, allowing the session to continue processing.
     * @default 0.80
     */
    backgroundCompactionThreshold?: number;
    /**
     * Context utilization threshold (0.0-1.0) at which the session blocks until compaction completes.
     * This prevents context overflow when compaction hasn't finished in time.
     * @default 0.95
     */
    bufferExhaustionThreshold?: number;
}

/** Informational message for timeline display with categorization */
export declare interface InfoData {
    /** Category of informational message (e.g., "notification", "timing", "context_window", "mcp", "snapshot", "configuration", "authentication", "model") */
    infoType: string;
    /** Human-readable informational message for display in the timeline */
    message: string;
    /** Optional actionable tip displayed with this message */
    tip?: string;
    /** Optional URL associated with this message that the user can open in a browser */
    url?: string;
}

/** Session event "session.info". Informational message for timeline display with categorization */
declare interface InfoEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Informational message for timeline display with categorization */
    data: InfoData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.info". */
    type: "session.info";
}
export { InfoEvent }
export { InfoEvent as SessionInfoEvent }

declare class InProcMCPTransport extends MCPTransport<ClientInfo> {
    constructor(settings: RuntimeSettings_2, logger: RunnerLoggerContract_3, cacheProviderTools?: boolean);
    protected loadDescriptors(clientInfo: ClientInfo): Promise<RustMcpToolDescriptor[]>;
    refreshProvider(clientInfo: ClientInfo): Promise<Tool[]>;
    invokeTool(toolId: string, toolParams: Record<string, unknown>, filterMode?: ContentFilterMode, toolCallId?: string): Promise<ToolResultExpanded>;
    protected invokeDescriptorTool(toolId: string, toolParams: Record<string, unknown>, filterMode: ContentFilterMode, toolCallId?: string): Promise<ToolResultExpanded>;
    private invokeToolWithErrorMode;
    private loadClient;
    private callHostTool;
}

/** Installed plugin record from global state, with marketplace, version, install time, enabled state, cache path, and source. */
declare interface InstalledPlugin {
    /** Path where the plugin is cached locally */
    cache_path?: string;
    /** Whether the plugin is currently enabled */
    enabled: boolean;
    /** Installation timestamp */
    installed_at: string;
    /** Marketplace the plugin came from (empty string for direct repo installs) */
    marketplace: string;
    /** Plugin name */
    name: string;
    /** Source for direct repo installs (when marketplace is empty) */
    source?: InstalledPluginSource;
    /** Per-plugin source fingerprint (a SHA-256 hash of the plugin's catalog source spec plus its resolved source subtree — NOT a Git commit SHA) captured at marketplace install/update time. Auto-update compares it against the freshly recomputed fingerprint to detect a content change that does not bump the version. Absent for pre-existing installs and for direct (non-marketplace) installs. */
    source_sha?: string;
    /** Version installed (if available) */
    version?: string;
}

/** Information about an installed plugin tracked in global state. */
declare interface InstalledPluginInfo {
    /** Opaque, stable hash identifying a direct (non-marketplace) install source. Present only for direct repo / URL / local installs; absent for marketplace plugins. Same source yields the same id; distinct sources never collide. */
    directSourceId?: string;
    /** Whether the plugin is currently enabled for new sessions */
    enabled: boolean;
    /** Marketplace the plugin came from. Empty string ("") for direct repo / URL / local installs. */
    marketplace: string;
    /** Plugin name */
    name: string;
    /** Installed version (when reported by the plugin manifest) */
    version?: string;
}

/** Source for direct repo installs (when marketplace is empty) */
declare type InstalledPluginSource = string | InstalledPluginSourceGitHub | InstalledPluginSourceUrl | InstalledPluginSourceLocal;

/** Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or full commit SHA, and optional subpath. */
declare interface InstalledPluginSourceGitHub {
    path?: string;
    ref?: string;
    repo: string;
    /** Optional full 40-character hexadecimal commit SHA. */
    sha?: string;
    /** Constant value. Always "github". */
    source: "github";
}

/** Source descriptor for a direct local plugin install, with a local filesystem path. */
declare interface InstalledPluginSourceLocal {
    path: string;
    /** Constant value. Always "local". */
    source: "local";
}

/** Source descriptor for a direct URL plugin install, with URL, optional ref or full commit SHA, and optional subpath. */
declare interface InstalledPluginSourceUrl {
    path?: string;
    ref?: string;
    /** Optional full 40-character hexadecimal commit SHA. */
    sha?: string;
    /** Constant value. Always "url". */
    source: "url";
    url: string;
}

/** Canonical file or directory where custom instructions can be discovered or created, with location, kind, preference, and project path. */
declare interface InstructionDiscoveryPath {
    /** Whether the target is a single file or a directory of instruction files */
    kind: InstructionDiscoveryPathKind;
    /** Which tier this target belongs to */
    location: InstructionDiscoveryPathLocation;
    /** Absolute path of the file or directory (may not exist on disk yet) */
    path: string;
    /** Whether this is the canonical target to create new instructions in its tier. At most one entry per tier is preferred. */
    preferredForCreation: boolean;
    /** The input project path this target was derived from (only for repository targets) */
    projectPath?: string;
}

/** Whether the target is a single file or a directory of instruction files */
declare type InstructionDiscoveryPathKind = "file" | "directory";

/** Canonical files and directories where custom instructions can be created so the runtime will recognize them. */
declare interface InstructionDiscoveryPathList {
    /** Canonical instruction create/discovery files and directories, in priority order */
    paths: InstructionDiscoveryPath[];
}

/** Which tier this target belongs to */
declare type InstructionDiscoveryPathLocation = "user" | "repository" | "working-directory" | "plugin";

/** Optional project paths to include in instruction discovery. */
declare interface InstructionsDiscoverRequest {
    /** When true, omit the host's instruction sources (user/home-level files and plugin rules), leaving only repository and working-directory sources. For multitenant deployments. */
    excludeHostInstructions?: boolean;
    /** Optional list of project directory paths to scan for repository/working-directory instruction sources. When omitted or empty, only user-level and plugin instruction sources are returned (no project scan). */
    projectPaths?: string[];
}

/** Optional project paths to include when enumerating instruction discovery targets. */
declare interface InstructionsGetDiscoveryPathsRequest {
    /** When true, omit the host's user-level instruction targets, leaving only repository targets. For multitenant deployments (mirrors `discover`'s `excludeHostInstructions`). */
    excludeHostInstructions?: boolean;
    /** Optional list of project directory paths. When omitted or empty, only the user-level targets are returned. */
    projectPaths?: string[];
}

/** Instruction sources loaded for the session, in merge order. */
declare interface InstructionsGetSourcesResult {
    /** Instruction sources for the session */
    sources: InstructionSource[];
}

/** Loaded instruction source for a session, including path, content, category, location, applicability, and optional description. */
declare interface InstructionSource {
    /** Glob pattern(s) from frontmatter — when set, this instruction applies only to matching files */
    applyTo?: string[];
    /** Raw content of the instruction file */
    content: string;
    /** When true, this source starts disabled and must be toggled on by the user */
    defaultDisabled?: boolean;
    /** Short description (body after frontmatter) for use in instruction tables */
    description?: string;
    /** Unique identifier for this source (used for toggling) */
    id: string;
    /** Human-readable label */
    label: string;
    /** Where this source lives — used for UI grouping */
    location: InstructionSourceLocation;
    /** The project path this source was discovered from. Only set by sessionless discovery for repository, working-directory, and project-scoped plugin sources, where it disambiguates sources across multiple workspace roots. The session-scoped getSources leaves it unset. */
    projectPath?: string;
    /** File path relative to repo or absolute for home */
    sourcePath: string;
    /** Category of instruction source — used for merge logic */
    type: InstructionSourceType;
}

/** Source of an indexed instruction entry. */
declare type InstructionSource_2 = "mcp-server" | "skill";

/** Where this source lives — used for UI grouping */
declare type InstructionSourceLocation = "user" | "repository" | "working-directory" | "plugin";

/** Category of instruction source — used for merge logic */
declare type InstructionSourceType = "home" | "repo" | "model" | "vscode" | "nested-agents" | "child-instructions" | "plugin";

/** Interaction type for CAPI telemetry, sent as X-Interaction-Type header. */
declare type InteractionType = 
/** Main agent loop processing a user message */
"conversation-agent"
/** Sub-agent invoked by the task tool (explore, code-review, custom agents) */
| "conversation-subagent"
/** MCP sampling request executed on behalf of an MCP server */
| "conversation-sampling"
/** Background operations (session naming, sentiment analysis) */
| "conversation-background"
/** Conversation compaction requests */
| "conversation-compaction"
/** First billable request in a user-initiated turn (set by PremiumRequestProcessor) */
| "conversation-user";

declare class InteractiveShellToolContext {
    private readonly config;
    private readonly options;
    private readonly shellConfig;
    private readonly taskRegistry;
    private readonly generation;
    readonly native: ShellDriverContextHandle;
    private readonly managerHandle;
    private currentLocation;
    private onCommandComplete?;
    private disposed;
    private terminallyDisposed;
    constructor(config: ToolConfig, _inTests?: boolean, _sessionFactory?: unknown, options?: {
        supportsPowerShell7Syntax?: boolean;
        asyncOnlyShell?: boolean;
    });
    getShellTool(overrides?: {
        notifyOnComplete?: boolean;
    }): Tool;
    get isDisposed(): boolean;
    getReadShellTool(overrides?: {
        notifyOnComplete?: boolean;
    }): Tool;
    getStopShellTool(compactTaskToolPrompt?: boolean): Tool;
    getListShellsTool(overrides?: {
        notifyOnComplete?: boolean;
    }): Tool;
    updateLocation(location: string): void;
    getAssessmentWorkingDirectory(): string;
    /**
     * The facts that decide whether a leading `cd` into the working directory
     * is redundant, for surfaces that must render the command before the shell
     * driver has run. Built from the same sources the driver is given, so the
     * two agree on what will actually be executed.
     */
    getCdRewriteFacts(): {
        hasInitScripts: boolean;
        envJson: string;
    };
    setOnCommandCompleteCallback(callback: ShellCommandCompletionCallback | undefined): void;
    readShellForNotification(shellId: string): Promise<ToolResultExpanded>;
    isCompletionNotificationCurrent(shellId: string, startedAt?: number): boolean;
    consumeCompletionNotification(shellId: string, startedAt?: number): boolean;
    getTrackedAttachedTasks(): ShellManagerTrackedTask[];
    canPromoteShellToBackground(taskId: string): boolean;
    promoteShellToBackground(taskId: string): boolean;
    getShellTaskProgress(taskId: string): ShellManagerTaskProgress | null;
    cancelShellTask(taskId: string): Promise<boolean>;
    refreshDetachedShells(): Promise<void>;
    removeShellTask(taskId: string): boolean;
    killRunningAttachedShells(): void;
    killAllAttachedShells(): void;
    hasRunningAttachedCommands(): boolean;
    hasCommandsAwaitingNotification(excludeShellId?: string): boolean;
    shutdownIdleSessions(): number;
    waitForActiveShells(): Promise<void>;
    shutdown(force?: boolean): Promise<TelemetryEvent>;
    shutdownAll(): Promise<void>;
    disposeShellManager(terminal?: boolean): void;
    getEffectiveShellConfig(shellId: string): ShellConfig;
    private prepared;
    private run;
    private descriptorOptions;
    private nativeSessionFacts;
    private shell;
    private getReplacementContext;
    private throwIfUsedAfterUnexpectedDispose;
    private current;
    private consumeNotification;
    private completeCommand;
    private publishPartialOutput;
    private emitSandboxTelemetry;
    private stopDescription;
}

/** Parameters for interrupting the main agent turn. */
declare interface InterruptMainTurnRequest {
    /** When true, the user's queued prompts are preserved and run as the next turn once the interrupted turn unwinds; when false (the default), the queue is cleared like a plain abort. */
    flushQueued?: boolean;
}

/** Result of interrupting the main agent turn. */
declare interface InterruptMainTurnResult {
    /** Whether an in-flight main agent turn was interrupted. False when the main loop was not processing. */
    interrupted: boolean;
}

export declare type InvokedSkillInfo = {
    name: string;
    path: string;
    content: string;
    allowedTools?: readonly string[];
    invokedAtTurn: number;
};

declare interface IOnRequestErrorProcessor extends IToJson {
    /**
     * Called before an error is rethrown by the client. The processor may modify
     * the error in place.
     */
    preErrorThrow(error: unknown): Promise<void>;
    /**
     * Called when a request to the model fails. The processor should not modify
     * the error.
     */
    onRequestError(context: OnRequestErrorContext): Promise<OnRequestErrorResult | void>;
}

declare interface IOnStreamingChunkProcessor extends IToJson {
    /**
     * Called when a streaming chunk is received.
     */
    onStreamingChunk(context: StreamingChunkContext): void;
}

declare interface IPostRequestProcessor extends IToJson {
    /**
     * Called after a successful request to the model, before the model_call_success event.
     * Processors can inspect the response and throw an error to trigger retry logic
     * via onRequestError processors.
     *
     * - Any {@link Event}s emitted by this method will be re-emitted by the completion with tools call.
     * - To trigger a retry, throw an error that an {@link IOnRequestErrorProcessor} can handle.
     */
    postRequest(context: PostRequestContext): AsyncGenerator<Event_2, PostRequestResult | void>;
}

declare interface IPostToolExecutionProcessor extends IToJson {
    /**
     * Called after a tool has been executed. Processors may normalize the tool
     * result in-place (for example to resize binary attachments) before it is
     * serialized into conversation history.
     */
    postToolExecution(context: PostToolExecutionContext): Promise<void>;
}

declare interface IPreRequestProcessor extends IToJson {
    /**
     * Called before a request (including retries of requests) is made to the model.
     *
     * - Any {@link Event}s emitted by this method will be re-emitted by the completion with tools call.
     */
    preRequest?(context: PreRequestContext): AsyncGenerator<Event_2>;
    /**
     * Native pre-request state owned by this processor. The Rust orchestrator
     * runs these processors in-place in the pre-request pipeline, preserving
     * relative ordering with JS processors while avoiding a JS bridge leaf for
     * the native-owned work.
     */
    nativePreRequestProcessorConfig?(): NativePreRequestProcessorConfig;
    /**
     * Native request-error state owned by this processor. The Rust orchestrator
     * updates this directly after request failures; there is no JS
     * `onRequestError` lifecycle hook.
     */
    nativeOnRequestErrorProcessorConfig?(): NativeOnRequestErrorProcessorConfig;
}

declare interface IPreToolsExecutionProcessor extends IToJson {
    /**
     * Called before any tool calls are executed.
     */
    preToolsExecution(context: PreToolsExecutionContext): Promise<PreToolsExecutionResult>;
}

/**
 * Factories require both rollout enablement ({@link AGENT_FACTORIES_FEATURE_FLAG})
 * and a non-PRU (usage-/token-based) billing model. Validation of the
 * `token_based_billing` flag on the Copilot user response runs in the Rust
 * runtime; this is a thin shim that serializes the (already-typed) inputs
 * across the napi boundary.
 */
export declare function isAgentFactoriesEnabled(featureFlags: FeatureFlags | undefined, copilotUser: CopilotUserResponse | undefined): boolean;

/** Returns true when {@link modelId} is the auto-mode virtual id. */
export declare function isAutoModel(modelId: string | undefined | null): boolean;

/**
 * Returns true when the parent session is using auto mode.
 * Requires both the explicit `autoMode` flag and a `capiSessionToken`.
 */
export declare function isAutoModeSession(settings: RuntimeSettings_2): boolean;

export declare const isFeatureFlag: (flag: string) => flag is FeatureFlag;

/** Narrows a {@link PassivePolicy} to its active object form. */
export declare function isPassive(passive: PassivePolicy | undefined): passive is {
    type: "drop" | "wait-for-next-turn";
};

export declare function isSessionsSidebarTabEnabled(featureFlags: FeatureFlags | undefined): boolean;

/**
 * Something which must have an implementation of `toJSON()`. This can be used
 * for classes whose instances will likely be used with `JSON.stringify()` to avoid
 * any issues with stringification such as circular references or non-enumerable properties.
 *
 * More information on `toJSON()`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#:~:text=If%20the%20value%20has%20a%20toJSON()%20method%2C%20it%27s%20responsible%20to%20define%20what%20data%20will%20be%20serialized.
 */
declare interface IToJson {
    toJSON(): string;
}

declare interface JsonObject {
    [key: string]: unknown;
    description?: string;
    id?: string;
    model?: string;
    name?: string;
    parameters?: JsonObject;
    strict?: boolean | null;
    type?: string;
}

declare interface JSONRPCErrorObject {
    code: number;
    message: string;
    data?: unknown;
}

declare interface JSONRPCErrorResponse {
    jsonrpc: "2.0";
    id?: RequestId;
    error: JSONRPCErrorObject;
}

declare type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse;

declare interface JSONRPCNotification<TParams extends JSONRPCParams = JSONRPCParams> {
    jsonrpc: "2.0";
    method: string;
    params?: TParams;
}

declare interface JSONRPCParams {
    _meta?: RequestMeta;
    [key: string]: unknown;
}

declare interface JSONRPCRequest<TParams extends JSONRPCParams = JSONRPCParams> {
    jsonrpc: "2.0";
    id: RequestId;
    method: string;
    params?: TParams;
}

declare type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse;

declare interface JSONRPCResultResponse<TResult extends Record<string, unknown> = Record<string, unknown>> {
    jsonrpc: "2.0";
    id: RequestId;
    result: TResult;
}

declare interface KnownFeatureFlagProperties {
    AUTO_APPROVAL?: boolean;
    AUTOPILOT_COMPLETION_REVIEWER?: boolean;
    AUTOPILOT_COMPLETION_REVIEWER_PLAIN_AUTOPILOT?: boolean;
    AUTOPILOT_COMPLETION_REVIEWER_STEERING?: boolean;
    AUTOPILOT_OBJECTIVES?: boolean;
    ENABLE_REASONING_SUMMARIES?: boolean;
    FORGE_AGENT_ENABLED?: boolean;
    WORKTREE_DEFAULT_BRANCH?: boolean;
}

declare type LargeOutputOptions = {
    maxOutputSizeBytes: number;
    sessionFs?: SessionFs;
    outputDir?: string;
    enabled?: boolean;
    grepToolName?: string;
    contentKind?: string;
};

/**
 * Configuration for handling large tool outputs.
 */
declare interface LargeToolOutputConfig {
    /**
     * Whether large output handling is enabled. Default is true.
     */
    enabled?: boolean;
    /**
     * Maximum size in bytes before output is written to a temp file. Default is 20KB.
     */
    maxSizeBytes?: number;
    /**
     * Directory to write temp files to. Default is os.tmpdir().
     */
    outputDir?: string;
}

/** Repository+branch-scoped dynamic context board configuration. */
declare type LaunchCheckDynamicContextConfig = {
    store: SessionStore;
    repository: string;
    branch: string;
};

/**
 * Minimal tool shape returned by lenient listing, compatible with all call
 * sites. Preserves `_meta` and arbitrary custom annotation properties (e.g.
 * `displayVerbatim`) that rmcp's typed `ToolAnnotations` struct would otherwise
 * strip. The Rust engine captures raw tools/list responses before rmcp's typed
 * deserialization so these fields round-trip verbatim across transports.
 */
declare interface LenientToolInfo {
    name: string;
    title?: string;
    description?: string;
    inputSchema: unknown;
    outputSchema?: unknown;
    annotations?: unknown;
    execution?: unknown;
    _meta?: unknown;
    [key: string]: unknown;
}

declare interface ListedAgentTask {
    task: AgentTaskEntry;
    relation?: AgentRelation;
}

export declare function loadFeatureFlagsFromConfig(config: UserSettings, featureFlags: FeatureFlags): FeatureFlags;

export declare function loadFeatureFlagsFromEnv(featureFlags: FeatureFlags): FeatureFlags;

/**
 * Source location of a local skill, determines priority order.
 * - project: .github/skills/, .agents/skills/, or .claude/skills/ in current working directory (highest priority)
 * - inherited: .github/skills/, .agents/skills/, or .claude/skills/ in parent directories (monorepo support)
 * - personal-copilot: ~/.copilot/skills/
 * - personal-agents: ~/.agents/skills/
 * - plugin: From an installed plugin
 * - custom: Added via COPILOT_SKILLS_DIRS env var or config
 * - builtin: Bundled with the runtime (lowest priority, can be overridden by any other source)
 */
declare const LOCAL_SKILL_SOURCES: readonly ["project", "inherited", "personal-copilot", "personal-agents", "plugin", "custom", "builtin"];

export declare class LocalFeatureFlagService extends FeatureFlagService {
    constructor(options?: Partial<FeatureFlagInitOptions>);
}

/** Result of a capped local session-store query. */
declare interface LocalQueryResult {
    rows: Record<string, unknown>[];
    truncated: boolean;
}

export declare class LocalSession extends Session<LocalSessionMetadata> {
    readonly isRemote: false;
    private disposing;
    private rewindOperationActive;
    private rewindOperationWaiters;
    private activeShellOperations;
    private shellOperationWaiters;
    private nativeCallbackRuntime?;
    private readonly callbackRuntimeSink;
    private callback;
    private legacyQueueItemId;
    private legacyQueueMessageId;
    private lastQueueMutationRevision;
    private pendingBatchedSystemNotificationBatch?;
    private readonly pendingBackgroundNotificationTasks;
    private backgroundTaskNotificationGeneration;
    private backgroundTaskNotificationPayloadsEnabled;
    private pendingMessageDelivery;
    currentRunInteractionId: string | undefined;
    private lastLogicalInteractionId;
    private hmacNoUserInteractionId;
    private activeAbortToolRequests;
    private _cachedTools;
    private cachedToolConfig?;
    private pendingNativeSendCount;
    private readonly pendingNativeSendDrainWaiters;
    protected getCurrentSettingsForHandle(): RuntimeSettings_2;
    protected get cachedSettings(): RuntimeSettings_2 | undefined;
    protected set cachedSettings(value: RuntimeSettings_2 | undefined);
    /**
     * Resolve the executor RuntimeSettings a sidekick launch should run with,
     * reflecting the session's *current* working directory, credentials, and
     * model. The per-turn settings cache is populated by `buildSettingsAndTools`
     * and is cleared on a `/cd` working-directory rebind, so a sidekick launched
     * from a `session.context_changed` event can otherwise race ahead of the
     * next model turn and observe an empty cache (github/agents#1471). When the
     * cache is warm we reuse it; otherwise we derive settings live from the
     * cwd-current base plus a freshly minted auth token and the live session
     * model, so the launch is never skipped or sized against stale context.
     */
    private getCurrentExecutorSettings;
    protected clearCachedAutoModeSessionTokenFromSettings(): void;
    protected getToolConfig(): ToolConfig | undefined;
    protected invalidateAgentToolConfig(): void;
    protected invalidateRubberDuckAvailability(): void;
    private queueDeferredToolHintIfNeeded;
    private _retainedClient;
    private _activeClient;
    private modelClientLifecycleDisposed;
    private readonly disposedModelClients;
    private readonly clientsPendingDisposal;
    protected shouldPublishMcpLoadSucceeded(): boolean;
    private readonly steeringInterrupts;
    private readonly pendingSteeringInterruptOrders;
    private pendingUntrackedSteeringInterruptMessages;
    private pendingSteeringInterrupt;
    private pendingSteeringInterruptDispatched;
    private pendingSyncTaskPromotion;
    private promotingSyncTasksToBackground;
    private compactionProcessor;
    /** Rate limiter for memory-pressure emergency compactions (issue #13535). */
    private readonly emergencyCompactionGovernor;
    private compactionProcessorPendingDisposal;
    readonly sidekickAgentManager: SidekickAgentManager;
    private invalidateModelBoundRuntimeCaches;
    protected onUsageMetricsUpdated(event: SessionEvent): void;
    protected inheritResponseLimitsForSubagent(session: Session): void;
    private reconcileResponseLimitsAfterUsage;
    private emitAbortCancellation;
    /**
     * Get background tasks from the sidekick agent registry.
     * Returns only agent tasks (sidekick agents don't have shell entries).
     */
    getSidekickBackgroundTasks(): BackgroundTask[];
    get hasActiveWork(): boolean;
    protected get blocksSubagentStart(): boolean;
    tryBeginRewindOperation(): boolean;
    protected tryStartShellOperation(): boolean;
    protected endShellOperation(): void;
    private waitForShellOperations;
    endRewindOperation(): void;
    private waitForRewindOperation;
    private hasRunningAgentsInTree;
    get hasPendingNativeSend(): boolean;
    /**
     * Extends the base behavior with a re-evaluation of the deferred
     * `session.idle` event. Every background-task-change pulse already funnels
     * through here (taskRegistry change, sidekick change), so this is the
     * single choke point that drains the deferral when work quiesces.
     *
     * In particular, `interactiveShellTool.setCommandCompleteCallback` schedules
     * `taskRegistry.notifyChange()` via `queueMicrotask` on every attached
     * shell command completion regardless of notification opt-in, which lands
     * here and lets non-notifying shells unblock idle.
     *
     * `emitDeferredSessionIdleIfReady` is a no-op when no deferral is pending
     * (or work is still in progress), so calling it on every change is cheap.
     */
    protected notifyBackgroundTaskChange(): void;
    private disposeClient;
    private disposeRetainedClient;
    mcpHostCache: McpHostCache;
    /** Per-session telemetry sender, supplied at construction. */
    protected sessionTelemetry?: DisposableTelemetrySender;
    private _disposePromise;
    /** Tear down per-session resources and clear the telemetry sender. */
    dispose(): Promise<void>;
    private _performDispose;
    /** Set the dynamic context config so the context_board tool can be registered even when the board is empty. */
    setDynamicContextConfig(config: {
        store: SessionStore;
        repository: string;
        branch: string;
    }): void;
    /** Read accessor for propagating to subagent sessions (see createSubagentSession). */
    getDynamicContextConfig(): {
        store: SessionStore;
        repository: string;
        branch: string;
    } | null;
    private manualCompactionAbortController;
    /**
     * Creates a new Session instance.
     *
     * In practice, use SessionManager.createSession() to create sessions and SessionManager.getSession() / SessionManager.getLastSession() to retrieve existing sessions.
     *
     * @param options - Configuration options for the session including model provider, tools, hooks, environment settings, and metadata (sessionId, startTime, modifiedTime). If metadata is not provided, new values are generated.
     */
    constructor(coreServices: CoreServices, options?: SessionOptions);
    /**
     * Set auto-generated session name from the first user message content.
     * Only sets the name if the workspace doesn't already have one.
     */
    private updateWorkspaceSummary;
    /**
     * Initialize workspace - load existing or create new.
     * Workspaces are always created when infinite sessions are enabled.
     */
    private initializeWorkspace;
    /**
     * Update the workspace context based on current workspace state.
     * This context is used in system prompts to inform the agent about workspace files.
     */
    private updateWorkspaceContext;
    /**
     * Updates session options after creation.
     * This method allows selectively updating configuration options without recreating the session.
     * Only the provided options will be updated; omitted options remain unchanged.
     *
     * @param options - Partial session options to update
     *
     * @example
     * ```typescript
     * // Update multiple options at once
     * session.updateOptions({
     *   logger: fileLogger,
     *   mcpServers: mcpConfig,
     *   customAgents: loadedAgents
     * });
     *
     * // Or use capability APIs for focused updates
     * await session.gitHubAuth.setCredentials({ credentials: newAuthInfo });
     * await session.model.switchTo({ modelId: newModel });
     * ```
     */
    updateOptions(options: Partial<UpdatableSessionOptions>, behavior?: UpdateOptionsBehavior): void;
    protected emitSessionLimitsTerminalError(message: string): void;
    protected emitSessionLimitsTerminalWarning(message: string): void;
    private emitSessionLimitsUsageCheckpointIfNeeded;
    private reconfigureNativeCallbackRuntime;
    private updateNativeCallbackFileSinks;
    /** After compaction, reset the embedding dedup set so instructions can be re-injected. */
    protected onCompactionApplied(): Promise<void>;
    getMetadata(): LocalSessionMetadata;
    /**
     * Update workspace metadata (cwd, repo, branch) for this session.
     * Called by session managers on session create/resume.
     */
    updateWorkspaceMetadata(context: WorkspaceContext, name?: string): Promise<void>;
    /**
     * Get the current workspace, if any.
     */
    getWorkspace(): Workspace | null;
    /**
     * Check if workspace features are enabled.
     */
    isWorkspaceEnabled(): boolean;
    /**
     * Get the workspace path for this session.
     * Returns null if workspace features are not enabled.
     * Returns the path even if workspace.yaml doesn't exist yet (for prompt context).
     */
    getWorkspacePath(): string | null;
    /**
     * Get the number of checkpoints (compaction summaries) in the workspace.
     */
    getCheckpointCount(): number;
    /**
     * Update the session's summary (AI-generated name).
     * Updates both in-memory workspace and persists to disk.
     * Will not overwrite a manually set name.
     */
    updateSessionSummary(summary: string): Promise<void>;
    /**
     * Rename the session (set custom name).
     * Updates both in-memory workspace and persists to disk.
     * Emits session.title_changed event so UI can update.
     */
    renameSession(name: string): Promise<void>;
    /**
     * List checkpoints with their titles for context injection.
     */
    listCheckpointTitles(): Promise<{
        number: number;
        title: string;
        filename: string;
    }[]>;
    /**
     * Read a specific checkpoint by number.
     */
    readCheckpoint(checkpointNumber: number): Promise<string | null>;
    /**
     * Check if a plan.md file exists in the workspace.
     */
    hasPlan(): Promise<boolean>;
    getPlanPath(): string | null;
    /**
     * Read the plan.md content from the workspace.
     * Returns null if workspace is not enabled or plan doesn't exist.
     */
    readPlan(): Promise<string | null>;
    /**
     * Get plan.md content for post-compaction message.
     * Returns null if workspace is not enabled or plan doesn't exist.
     */
    private getPlanContentForCompaction;
    protected maybeEmitStaticContextWarning(event: StaticContextBudgetEvent): void;
    protected handleStaticContextBlockedEvent(event: CompactionStaticContextBlockedEvent_2): void;
    private emitStaticContextPressureTelemetry;
    /**
     * Consecutive reviewer-derived `continue` decisions for the active objective,
     * keyed by objective id. Sampled into the completion reviewer so the native
     * decision can fail open once the rejection budget is exhausted instead of
     * looping forever (the reviewer's `continue` bypasses the autopilot
     * continue/no-progress stops). Reset whenever the objective era changes (a
     * pause, a candidate/turn mismatch, or any non-reviewer-derived decision). A
     * pause/resume that keeps the same objective id can carry a stale count
     * forward; that only makes the decision fail open *sooner*, which is the safe
     * direction, so it is left as a benign approximation rather than threading
     * resume detection through here.
     */
    private autopilotCompletionRejectionStreak?;
    private completionRejectionCountFor;
    /**
     * Advance or reset the rejection streak from the reviewer decision. Only a
     * reviewer-derived `continue` (an actual reviewer rejection) counts toward the
     * budget; every other outcome -- PASS/blocked/budget-exhausted accept, or a
     * host-side non-reviewer continue -- ends the streak.
     */
    private recordCompletionRejectionOutcome;
    private evaluateTaskCompletion;
    /**
     * Objective-scoped completion evaluation. Returns `{ kind: "no-active-objective" }`
     * when there is no active objective, so the caller may fall through to the
     * plain-autopilot (non-objective) path. Otherwise returns `{ kind: "resolved" }`
     * with the authoritative decision for this objective-present turn — which the caller
     * must honor without falling through. `decision` is `undefined` when the objective is
     * active but the objective reviewer is off (e.g. only the plain-autopilot experiment
     * is enabled): the plain-autopilot experiment must not change objective sessions, so
     * we leave legacy completion handling untouched rather than review or stamp.
     * `objectiveReviewerEnabled` is `base reviewer || steering`; when `steeringEnabled`,
     * the reviewer's ground data is the objective text unified with later steering.
     */
    private evaluateObjectiveTaskCompletion;
    /**
     * Plain-autopilot (non-objective) completion evaluation, gated behind the
     * plain-autopilot experiment (the router only reaches this in autopilot mode
     * with that flag on). Verifies the `task_complete` summary against the task's
     * opening request — plus later steering when `steeringEnabled` — using the same
     * independent reviewer as objective mode, then strips the synthetic objective
     * identifiers so downstream revalidation and `session.task_complete` treat it as
     * a plain completion (no objective to pause/resume). Returns `undefined` (legacy
     * handling) when there is no accumulated ground data.
     */
    private evaluateNonObjectiveTaskCompletion;
    private getAutopilotObjectiveContentForCompaction;
    /**
     * Write plan content to the workspace plan.md file.
     */
    writePlan(content: string): Promise<void>;
    /**
     * Delete the workspace plan.md file.
     */
    deletePlan(): Promise<void>;
    readAutopilotObjective(): Promise<string | null>;
    writeAutopilotObjective(content: string): Promise<"create" | "update">;
    /**
     * List files in the workspace files directory.
     */
    listWorkspaceFiles(): Promise<string[]>;
    /**
     * Read a file from the workspace files directory.
     */
    readWorkspaceFile(filePath: string): Promise<string>;
    /**
     * Write a file to the workspace files directory.
     */
    writeWorkspaceFile(filePath: string, content: string): Promise<void>;
    /**
     * Project the LSP language servers currently tracked for this session (their
     * `read_agent` agent ids, server ids, and readiness/status) for the per-turn
     * `<lsp_servers>` user-message reminder. The reminder string itself is shaped
     * natively in `prompt_cli_user`; this only surfaces the live projection so the
     * (growing) server log is not serialized across the napi boundary every turn.
     *
     * Returns an empty list when no servers are tracked, so the native reminder
     * only appears once at least one LSP server has started (e.g. via warmup or
     * first `lsp` tool use). It is projected each turn (rather than baked into the
     * static system prompt) because the set of servers and their readiness changes
     * over the session.
     */
    getLspServiceReminders(): LspServiceReminderInput[];
    getLspServicesReminderMessage(): string | null;
    /**
     * Mark plan as recently updated (resets the reminder timer).
     * Called when plan.md is detected to be written.
     */
    markPlanUpdated(): void;
    /**
     * Handle a subagent_session_boundary event by emitting the appropriate
     * subagent lifecycle session event (started/completed/failed).
     */
    private handleSubagentBoundary;
    /**
     * Ensure workspace exists for this session.
     * Creates workspace.yaml and directory structure if needed.
     */
    ensureWorkspace(context?: WorkspaceContext): Promise<Workspace>;
    /**
     * Persist a compaction summary as a checkpoint.
     * Called automatically when compaction completes.
     * Returns the checkpoint number and path after the file is created.
     */
    private persistCompactionCheckpoint;
    /**
     * Truncate workspace checkpoints to align with the current session history.
     * Used after rollback to remove compaction checkpoints created after the rollback point.
     */
    truncateWorkspaceCheckpoints(keepCount: number): Promise<void>;
    /**
     * Sends a message to the session and executes the agentic loop.
     * Messages can be queued or sent immediately during an ongoing turn.
     *
     * @param options - Send options including prompt, attachments, and mode
     * @param options.prompt - The prompt text to send
     * @param options.attachments - Optional file/directory attachments
     * @param options.mode - "enqueue" (default) adds to queue and processes when ready, "immediate" injects during current turn
     * @returns A Promise that resolves when the message has been queued or processed
     *
     * @example
     * ```typescript
     * // Send a message (default enqueue mode)
     * session.send({
     *   prompt: "What files are in this directory?",
     *   attachments: [{ type: "directory", path: "/path/to/dir" }]
     * });
     *
     * // Send immediate message during processing
     * session.send({
     *   prompt: "Continue with that approach",
     *   mode: "immediate"
     * });
     * ```
     */
    send(options: SendOptions): Promise<void>;
    /**
     * Apply plan-mode and agent-mode adjustments to a send options object.
     *
     * - Derives `agentMode` from the session's current mode when not interactive.
     * - In plan mode, auto-prefixes the prompt with `[[PLAN]]` (keeping the
     *   original text as `displayPrompt`), except for `system`-sourced messages.
     *
     * Returns a new options object; the input is not mutated.
     */
    private applyPlanAndModeAdjustments;
    /**
     * Append zero or more user messages to the conversation and run exactly one
     * agent turn (a single model submission) over the resulting history.
     *
     * This is the multi-message sibling of {@link send}: rather than a single
     * message, it accepts an ordered list. All provided messages are appended to
     * history — each becoming its own `user.message` timeline entry, in order —
     * before one model request is made. An empty list runs a single turn over the
     * existing history without appending a new user message (the model responds to
     * the conversation as-is).
     *
     * The per-turn context preamble (capabilities, plan/model/cwd reminders, etc.)
     * is applied to the final message of the batch. The empty case preserves
     * existing history exactly, so user-message notices remain pending until the
     * next user-authored turn.
     *
     * @param items - The user messages to append, in order. May be empty.
     * @param turnOptions - Turn-level delivery options (`mode`, `prepend`, `requestHeaders`).
     * @returns A Promise that resolves when the batch has been queued or processed.
     */
    sendMessages(items: SendOptions[], turnOptions?: {
        mode?: "enqueue" | "immediate";
        prepend?: boolean;
        requestHeaders?: Record<string, string>;
    }): Promise<void>;
    /**
     * Discovers instruction files near the accessed file path, walking
     * from its directory up to the repo root. Returns newly discovered
     * sources without performing side effects (notifications, telemetry).
     */
    protected discoverInstructionsForFile(filePath: string, _triggerTool: string): Promise<RepoInstructionSource[]>;
    /**
     * Whether a queued or about-to-start background-agent completion/idle system
     * notification is now redundant because a `read_agent` tool result has
     * already communicated that state to the reader. Evaluated at injection time
     * (right before the notification would be added to a model request), by which
     * point any concurrent blocking read has returned and recorded the
     * communicated state via {@link TaskRegistry.recordReadCommunicatedState}.
     *
     * This closes the race the `activeBlockingReads` counter + queue `consume`
     * cannot cover: a completion/idle notification queued or delivered as a new
     * turn AFTER the read returned (e.g. sent via `send()` while the parent was
     * idle, which cannot be removed once its turn has started).
     */
    isRedundantAgentNotification(options: SendOptions): boolean;
    /**
     * Send a system notification to the agent.
     *
     * Mid-turn: the event is emitted directly and Rust's immediate-prompt
     * pre-request stage includes the resulting chat message in the current
     * model call. Passive
     * messages ride along the same way; their `PassivePolicy` only matters
     * at the post-loop salvage point if the loop exits before a preRequest
     * drains them.
     *
     * Idle behavior depends on `options.passive`:
     *   - omitted / `false`: routes through `send()` → agenticLoop, which
     *     emits the event and starts a new turn.
     *   - `{ type: "wait-for-next-turn" }`: buffered in the immediate queue
     *     without waking the loop; the next user-driven turn's preRequest
     *     drains it alongside that turn's prompt.
     *   - `{ type: "drop" }`: silently discarded. The caller is responsible
     *     for any durable storage (e.g., the Inbox table) if it wants the
     *     message to resurface later.
     *
     * System notifications are hidden from the timeline, non-billable, and
     * excluded from session snapshots.
     */
    sendSystemNotification(message: string, kind: SystemNotification | undefined, options?: {
        passive?: PassivePolicy;
        agentNotificationTurnCount?: number;
    }): void;
    private sendBatchedSystemNotification;
    private hasRunningNotificationTask;
    private addPendingBatchedSystemNotification;
    private flushPendingBatchedSystemNotifications;
    private clearPendingBatchedSystemNotifications;
    private flushReadyPendingBatchedSystemNotifications;
    private fireSystemNotificationSideEffects;
    private deliverSystemNotifications;
    emitSystemNotificationDelivery(content: string, kind: SystemNotification, delivery?: SendOptions["notificationDelivery"]): number;
    /**
     * Live background-notification delivery callbacks keyed by a serializable id.
     * The native session queue stores SendOptions as plain JSON, which strips the
     * `notificationDelivery` closures (isStillValid/onDelivered). We stash the
     * live callbacks here and thread a `notificationDeliveryId` string through the
     * options so the delivery can be re-hydrated when the queued turn runs.
     */
    private readonly pendingNotificationDeliveries;
    /** Registers live delivery callbacks and returns their serializable handle. */
    private registerNotificationDelivery;
    /**
     * Resolves the live delivery for these options without consuming it. Prefers
     * the registry entry (native round-trip path) and falls back to any live
     * closures still attached to the options (pure in-process paths).
     */
    private peekNotificationDelivery;
    /** Drops a delivery's registry entry once it has been delivered (or discarded). */
    private releaseNotificationDelivery;
    private emitBackgroundNotificationSyntheticRead;
    private immediatePromptRunState;
    private consumePendingSystemNotifications;
    private queuePostToolUseFailureContext;
    private runPostToolUseFailureHooks;
    private processToolExecutionResult;
    /**
     * Derive the model-facing (`contentForLlm`) and detailed (`detailedContent`)
     * strings from a finalized tool result, applying the same error/success
     * precedence `processToolExecutionResult` uses. Extracted so a late
     * revalidation of an autopilot completion decision can rebuild both
     * consistently instead of duplicating (and drifting from) that precedence.
     */
    private deriveToolResultContent;
    /**
     * Revalidate autopilot completion eligibility for a `task_complete` result
     * immediately before it is turned into model-facing content or emitted.
     *
     * The completion reviewer samples its inputs (including the session abort state)
     * when it is invoked, but several `await`s follow before the result is consumed
     * — the native pre/post-reviewer calls, the reviewer sub-agent, and tool-result
     * processing. Two races can invalidate the decision in that window:
     *
     * - A genuine session cancellation (any abort reason other than `"suspend"`) can
     *   land after a `completed` was already decided; recording it would mark the
     *   objective done despite the user cancelling, so it is downgraded to `blocked`.
     * - A pause/resume can supersede the turn that produced the decision: the same
     *   objective may still be active but no longer carry a matching completion
     *   candidate (resumed under a new eligibility token, or eligibility momentarily
     *   absent), making a completed/blocked decision stale — downgraded to `continue`.
     *
     * Downgrading the *whole* result here (model-facing text, session log, and
     * decision) — rather than only the `session.task_complete` payload — keeps the
     * model, `tool.execution_complete`, and `session.task_complete` consistent, so a
     * stale outcome cannot be delivered to the model or persisted while the semantic
     * event says something else. The decision logic is the pure, unit-tested
     * `revalidateCompletionEligibility`; this method only samples the live session
     * state it needs and applies the rewrite.
     */
    private revalidateAutopilotCompletionEligibility;
    /** Fires the permission_prompt notification hook once a permission prompt is actually shown. */
    notifyPermissionPrompt(message: string): void;
    /**
     * Fires the deferred `notification` hook for a background-agent completion/
     * idle notification at injection time, once the notification has passed the
     * redundancy check and is actually being delivered. Called from the two
     * injection sites (`ImmediatePromptProcessor.preRequest` and
     * `processQueuedItems`). A redundant, suppressed notification never reaches
     * these sites, so its hook — and any hook-injected `additionalContext` —
     * never fires. No-ops for any options without a deferred hook message.
     */
    fireDeferredNotificationHook(options: SendOptions): void;
    /**
     * Core logic for adding an item to the queue.
     *
     * @param item - The queued item (either a command or message)
     * @param prepend - If true, adds to the front of the queue (for priority messages)
     */
    private addItemToQueue;
    consumePendingMessageDelivery(options: SendOptions): UserMessageDelivery | undefined;
    private setPendingMessageDelivery;
    private shouldUseStableHmacNoUserInteractionId;
    private getModelRequestInteractionId;
    private addImmediateMessage;
    private addImmediateMessagesIfProcessing;
    private readonly registerSteeringInterrupt;
    private interruptSteerableToolWaits;
    private promoteSyncTasksToBackground;
    private clearPendingSteeringInterrupt;
    private canRemovePendingSteeringInterruptOrder;
    private reconcilePendingSteeringInterruptOrders;
    private invokeSteeringInterrupt;
    /**
     * Native port of `ImmediatePromptProcessor.preRequest`: partition and inject
     * this turn's ready immediate prompts. Rust owns the partition + event/chat
     * projection (returned as `events` / `requestMessages`), but two pieces of
     * the original JS `preRequest` stay in the host because their backing state
     * still lives in TypeScript:
     *
     *   - **Redundant-notification suppression.** A background-agent
     *     completion/idle notification whose state a `read_agent` result already
     *     communicated to the reader (tracked in the JS `TaskRegistry`'s
     *     communicated-read-state map) is dropped at injection time — the
     *     `pending_messages.modified` marker still fires, but the notification
     *     event and its request message are skipped, matching the JS `continue`.
     *   - **Deferred notification hook.** A surviving notification fires its
     *     deferred hook now (a no-op for non-notification messages).
     *
     * The Rust plan exposes the parallel `readyOptions` (raw send options per
     * ready item) and `messageCounts` (request messages contributed per item) so
     * the host can run those per-item checks and skip a suppressed item's
     * messages without losing index alignment.
     */
    private runImmediatePromptPreRequest;
    get immediatePromptProcessor(): {
        addMessage: (options: SendOptions) => void;
        prependMessages: (options: SendOptions[]) => void;
        getQueue: () => SendOptions[];
        preRequest: (context: PreRequestContext) => AsyncGenerator<Event_2>;
    };
    private prependImmediateMessages;
    protected enqueueResumePendingWake(): void;
    /**
     * Enqueue a slash command to be executed after the current agentic work completes.
     * Commands are processed in FIFO order alongside user messages.
     *
     * If the session is not currently processing, this will also kick off queue processing.
     * This ensures that commands transferred from another session (e.g., after /clear)
     * actually get executed even if there are no messages to trigger processing.
     *
     * @param command - The full command string including the slash, e.g., "/compact" or "/model gpt-4"
     */
    enqueueCommand(command: string): Promise<void>;
    /**
     * Enqueue a user message item to be processed later.
     * This is a utility for creating properly typed message queue items.
     * @param options - The send options for the message
     * @param prepend - If true, adds to the front of the queue (for priority messages)
     */
    private enqueueUserMessage;
    /**
     * Enqueue a batch of user messages to be appended and processed together in a
     * single agent turn. An empty batch enqueues a turn over the existing history.
     *
     * @param items - The user messages for the batch, in order. May be empty.
     * @param prepend - If true, adds the batch to the front of the queue.
     */
    private enqueueMessages;
    /**
     * Process the item queue, handling both messages and commands in FIFO order.
     */
    private processQueue;
    private legacyItemQueue;
    get itemQueue(): QueuedItem[];
    interruptMainTurn(options?: {
        flushQueued?: boolean;
    }): Promise<{
        interrupted: boolean;
    }>;
    cancelAllBackgroundAgents(): number;
    /**
     * Shared abort path for both `abort()` and `abortForSchema()`.
     *
     * Applies in-process cancellation synchronously so a caller that aborts
     * from within a session event handler (e.g. on "assistant.message") is
     * observed by the still-running agentic loop on this same tick. This
     * mirrors the legacy synchronous cancelProcessing() behavior; without it
     * the abort would only take effect once the async native round-trip's
     * `cancel_processing` host effect lands, which is after the current turn's
     * post-stream abort check has already run — dropping the cancellation.
     * Crucially, `cancelProcessing()` (i.e. `this.abortController?.abort(...)`)
     * is also what interrupts a turn that is currently blocked inside a
     * synchronous tool call (e.g. a long-running bash command); the native
     * abort round-trip alone no-ops in that state — it targets the queue-drain
     * loop, not the live agentic turn, so it resolves `success: false` and the
     * tool keeps running.
     *
     * Returns the native abort result unchanged so callers can distinguish a
     * genuine abort from the race-to-idle no-op (`success: false`).
     */
    private abortInProcessAndNative;
    abort(params?: {
        reason?: AbortReason;
    }): Promise<void>;
    abortForSchema(params: {
        reason?: AbortReason;
    }): Promise<{
        success: boolean;
        error?: string;
    }>;
    /**
     * Drain queued prompts/commands so an MCP user.abort fully stops the session.
     * Mirrors the user-rejected-tool path: clears both the immediate steering
     * queue and the main item queue so no pending user-visible work survives.
     */
    protected onUserAbort(): void;
    /**
     * Suspend the session so it can be resumed later.
     *
     * Unlike abort(), suspend() preserves persisted permission state in the JSONL
     * so that orphaned tool calls can be properly classified on resume. The abort
     * signal carries reason "suspend" to distinguish it from a user-initiated abort
     * (which emits an "abort" event and marks orphans as interrupted).
     *
     * After the agentic loop unwinds, all buffered events are flushed to disk so
     * the caller can safely tear down the session / kill the process.
     */
    suspend(): Promise<void>;
    /**
     * Shared abort + cleanup logic for abort() and suspend().
     *
     * Note: subagents are hard-cancelled here, not checkpointed. On resume they
     * appear as orphaned local tool calls classified "interrupted". Adding
     * subagent resume would be additive: persist a `subagent.suspended` event
     * before cancelling, add a corresponding orphan state in
     * `classifyOrphanedToolCalls`, and re-launch from the checkpointed
     * conversation in `resolveResumeOrphans`.
     */
    private cancelProcessing;
    /**
     * Apply a cancellation recorded during the queue-processing setup window
     * (see the runtime's `record_setup_window_abort`,
     * github/copilot-agent-runtime#13025) to the per-turn AbortController that was
     * just created, and mark the setup window closed for this run. Restores the
     * runtime `pending_abort_reason` captured when the cancellation arrived (the
     * message branch clears it just before this call) so the emitted abort event
     * reports the original cause. Must be called at every per-turn controller
     * creation site so the window is closed even when nothing was deferred; a
     * no-op in that case.
     */
    private applyDeferredSetupAbort;
    /**
     * Cancel agent tasks in the main task registry.
     *
     * This complements sidekickAgentManager.cancelAll() which only covers
     * the sidekick registry. Agents launched by the Task tool and MCP tasks
     * live in this.taskRegistry and must be cancelled separately.
     *
     * Ordinary turn cancellation preserves idle multi-turn agents so they can
     * still receive follow-up messages. Session suspension and teardown pass
     * includeIdle=true because those parked executor loops cannot survive the
     * session lifecycle boundary.
     *
     * Idempotent: already-cancelled tasks are skipped by TaskRegistry.cancel().
     */
    private cancelActiveAgents;
    private supportsSystemNotifications;
    queueFactoryCompletionNotification(record: FactoryCompletionNotificationRecord | Promise<FactoryCompletionNotificationRecord>, lifecycle: FactoryCompletionNotificationLifecycle, fallback: FactoryCompletionNotificationFallback): void;
    invalidateFactoryCompletionNotification(runId: string): void;
    private sendFactoryCompletionNotification;
    private sendBackgroundAgentCompletionNotification;
    /**
     * Sends a notification to the model when a multi-turn background agent
     * finishes a turn and enters idle state (waiting for write_agent messages).
     */
    private sendBackgroundAgentIdleNotification;
    private buildShellCompletionSyntheticRead;
    /**
     * Sends a notification to the agent when a background shell command completes.
     */
    private sendBackgroundShellCompletionNotification;
    private isDetachedShellCompletionNotificationCurrent;
    private consumeDetachedShellCompletionNotification;
    /**
     * Sends a notification to the agent when a detached shell completes.
     */
    private sendDetachedShellCompletionNotification;
    ensureMcpLoaded(): Promise<void>;
    protected ensureMcpServerConnected(serverName: string): Promise<void>;
    runNativeSessionHostEffect(effect: string, params: Record<string, unknown>, caller?: NativeSessionHostEffectCaller): Promise<unknown>;
    /**
     * Run the native queue drain on a later tick. The drain re-validates its own
     * admission (pause, in-flight ownership, live turn) when it runs, so a
     * scheduled drain that lands while a turn is still live defers itself.
     *
     * The detached drain is also the sole driver of the reservation a send placed.
     * If it rejects (e.g. a transient failure before or during
     * `begin_queue_processing`) and we merely swallow the error, the first message
     * vanishes with no `session.start` / `user.message` / model call ever
     * following.
     *
     * Recover with a single bounded retry: the retry's `begin_queue_processing`
     * re-claims and drains any still-queued work, or cleanly no-ops if the queue
     * is already empty. We deliberately do NOT clear the reservation flag directly
     * — it is an unowned shared boolean, so poking it could stomp a newer send's
     * reservation (downgrading an in-gap immediate message from steering to a
     * queued turn); letting `begin_queue_processing` reconcile the flag is
     * race-free. If the retry also fails we surface the error and stop — the next
     * real send self-heals via the runtime's `processing_loop_active`
     * fall-through.
     */
    private scheduleProcessQueue;
    /**
     * Clear the native live-turn flag at the turn's idle boundary. A queue drain
     * the runtime deferred because this turn was live resumes here — queued-lane
     * work starts its own turn instead of entering the turn that just ended.
     */
    private endNativeTurn;
    private runNativeQueuedCommand;
    private runNativeResumePendingTurn;
    /**
     * Post-turn finalization for a context-clear seed captured mid-turn:
     * enqueue it (prepended, so it runs ahead of any other queued items in the
     * fresh window) once the agentic loop has exited. Called by BOTH turn
     * drivers, since a clear can run inside a resume-pending continuation too;
     * finalizing only after message turns would strand the seed until an
     * unrelated later turn. An aborted turn drops the seed instead - the user
     * cancelled the operation mid-flight.
     */
    private finalizePendingClearContextMessage;
    /**
     * Cancel any in-progress background compaction before clearing context, so
     * a stale compaction result cannot overwrite the cleared state and leave
     * orphaned tool_result blocks behind.
     */
    clearContextMessages(initialMessage: string): Promise<{
        messagesCleared: number;
    }>;
    private runNativeMessageTurn;
    private handleNativeRateLimitedTurn;
    /**
     * Handle a content-refusal fallback annotation raised by the runtime's
     * `finish_message_turn`. The CAPI Anthropic seam detected that the active
     * model declined the request (`stop_reason: "refusal"` →
     * `finish_reason: "content_filter"`) with the `ANTHROPIC_REFUSAL_FALLBACK`
     * feature enabled and a concrete `refusalFallbackModel` configured, then
     * **re-issued the refused request directly to the fallback model at the
     * seam** and served that answer as this turn's response.
     *
     * This handler makes the fallback visible (it is intentionally *not* a silent
     * swap): it emits a `session.info` notice naming both models and the billed
     * attempt, plus a durable `session.model_change` event
     * (`cause: "refusal_fallback"`). That event makes the fallback the active model
     * for the rest of this session and restores it when this session is resumed,
     * without changing the user's default model for new sessions. The seam already
     * recovered the refused turn, so this handler does not re-run it or call
     * `applyModelChange`, which would repeat picker validation and fail in pinned
     * sessions where the fallback is not in the picker catalog. Fallback repricing
     * credits the refused attempt back at the seam, so the notice does not mention
     * usage.
     */
    private handleNativeRefusalFallbackTurn;
    /**
     * Check if the session is currently in a state where it can be aborted.
     * Returns true if there's an active abort controller that hasn't been aborted yet.
     * This is important for queued operations where the CLI may not have direct access
     * to the abort controller (e.g., when messages are processed from the queue).
     */
    isAbortable(): boolean;
    get isProcessing(): boolean;
    set isProcessing(value: boolean);
    get inheritedShellContext(): boolean;
    set inheritedShellContext(value: boolean);
    get idleDeferredByBackgroundWork(): boolean;
    set idleDeferredByBackgroundWork(value: boolean);
    get idleDeferredAborted(): boolean;
    set idleDeferredAborted(value: boolean);
    private getDeferredSessionIdleState;
    /**
     * Override setSelectedModel to enqueue the change when the session is mid-turn.
     * The model change will be applied after the current turn completes, in queue order.
     */
    setSelectedModel(model: string, reasoningEffort?: ReasoningEffort, modelCapabilitiesOverrides?: ModelCapabilitiesOverride, reasoningSummary?: ReasoningSummary_2, contextTier?: ContextTier_3, verbosity?: Verbosity_2, deferIfModelChangeQueued?: boolean): Promise<ModelSwitchOutcome>;
    /**
     * Check whether there is any active background work that should defer
     * `session.idle`.
     *
     * "Active background work" today means either:
     *   - A multi-turn agent in the main task registry with status `"running"`.
     *   - An attached shell session with a command currently in progress.
     *
     * Both are work the session is awaiting on the user's behalf; neither
     * should be allowed to silently flip the session to idle. Used by the
     * idle-deferral path: `hasActiveWork`, `emitDeferredSessionIdleIfReady`,
     * and the post-loop idle decision in native queue processing. That path
     * pairs with `notifyBackgroundTaskChange()` (overridden on `LocalSession`)
     * to re-evaluate and drain the deferral when work quiesces, so it is
     * safe to include sources that have no synchronous completion-notification
     * turn — `interactiveShellTool` already pokes
     * `taskRegistry.notifyChange()` via `queueMicrotask` on every shell
     * command completion (see `setCommandCompleteCallback`).
     *
     * Intentionally NOT included:
     *   - Agents with status `"idle"` (multi-turn agents parked waiting for
     *     `write_agent`) — they are user-driven; gating idle on them would
     *     freeze the UI until the agent was explicitly killed.
     *   - Detached shells — by design they outlive the session (servers,
     *     daemons) and would otherwise pin idle forever.
     *   - Sidekick agents in `SidekickAgentManager.taskRegistry` — separate
     *     registry.
     *   - Attached shells when this session's shell context is inherited
     *     from a parent (subagents). Shells live in the parent's shell
     *     context; their completion only pulses the parent's task
     *     registry, so a subagent would never see the drain. Subagents
     *     gate idle on their own work only.
     *
     * NOTE: Other call sites (queue-draining via `enqueue`/`enqueueItem`
     * and the post-item break in `runAgenticLoop`) want a stricter predicate
     * that only includes background work whose completion fires a
     * notification turn capable of waking the queue and flushing pending
     * events. Those use `hasNotifyingBackgroundWork()` below; broadening
     * them to all attached shells would strand queued messages behind
     * never-completing attached commands (e.g., a `tail -f` or REPL that
     * quiesced and returned control to the agent while the underlying
     * process keeps running). The `suspend()` drain is stricter still
     * (`hasRunningAgents()` only) because suspend deliberately preserves
     * attached shells across the resume boundary.
     */
    private hasActiveBackgroundWork;
    /**
     * Whether any multi-turn agent in the main task registry is currently
     * in status `"running"`. Excludes `"idle"` (parked waiting for
     * `write_agent`) and sidekick agents (separate registry).
     *
     * Shared building block for `hasActiveBackgroundWork()`,
     * `hasNotifyingBackgroundWork()`, and `waitForNotificationTurnsToDrain()`.
     * The last of those needs the agent check in isolation: it must not
     * unconditionally gate on attached shells because `suspend()`
     * deliberately preserves shells (including notifying ones) across the
     * resume boundary. The `waitForPendingBackgroundTasks()` caller opts
     * back into waiting for notifying shells via the drain's
     * `includeNotifyingShells` parameter, since prompt-mode exit should
     * cover notifying work spawned recursively by completion turns.
     */
    private hasRunningAgents;
    private hasPendingBackgroundNotificationDelivery;
    private hasQueuedBackgroundCompletionNotification;
    /**
     * Stricter sibling of `hasActiveBackgroundWork()` that only counts
     * background work whose completion fires a notification turn capable of
     * waking the queue:
     *   - A multi-turn agent in the main task registry with status `"running"`.
     *   - An attached shell session with a command in progress AND
     *     `notifyOnComplete: true` (the opt-in that sends a synthetic
     *     completion notification when the command finishes).
     *
     * Excludes attached shells without `notifyOnComplete`: those return to
     * the agent on output quiescence while the underlying process keeps
     * running, with no synchronous wake-up signal. Deferring queue draining
     * on them risks stranding messages indefinitely (e.g., the user keeps
     * a REPL alive).
     *
     * Use this predicate for paths that depend on a completion notification
     * to make progress — not for the idle-deferral path (which is drained
     * directly by `notifyBackgroundTaskChange()`) and not as the only
     * suspend-drain gate (since suspend preserves attached shells,
     * including notifying ones, across the resume boundary).
     *
     * Same subagent exclusion as `hasActiveBackgroundWork()`: when this
     * session's shell context is inherited from a parent, the shells live
     * in the parent and their completion only pulses the parent's task
     * registry. Subagents must not gate on parent-owned shells.
     */
    private hasNotifyingBackgroundWork;
    private trackBackgroundNotificationTask;
    private isBackgroundTaskNotificationPayloadsEnabled;
    private emitSessionIdle;
    private emitDeferredSessionIdleIfReady;
    private drainDeferredSessionIdleIfReady;
    /**
     * Wait until the session is no longer processing messages and no
     * multi-turn agents in this session are still running. Optionally
     * (when `includeNotifyingShells: true`) also waits for any attached
     * shells with `notifyOnComplete: true` whose commands are in progress;
     * those shells will fire a synthetic completion notification turn on
     * completion, and the loop will catch that turn via `isProcessing`.
     *
     * Attached shells are otherwise NOT waited on regardless of
     * `notifyOnComplete`:
     *
     *   - `suspend()` preserves attached shells (notifying and non-notifying)
     *     across the resume boundary, so waiting on either would block tear-
     *     down behind a never-completing REPL, `tail -f`, or long-running
     *     build.
     *   - `waitForPendingBackgroundTasks()` calls `waitForActiveShells()`
     *     before reaching this drain, so any shells that existed at call
     *     time have already settled. But the notification turns spawned
     *     by those completions may launch new notifying background shells
     *     (e.g., LLM kicks off `npm test` after `npm run build` finishes),
     *     and prompt-mode exit should wait for those too. Pass
     *     `includeNotifyingShells: true` from that call site so the loop
     *     iterates over recursively-spawned notifying work.
     *
     * What we DO need to wait on at both call sites is the agentic loop
     * itself unwinding (`isProcessing`) and any in-flight notification
     * turn it spawns to complete — including the synthetic completion
     * turns that just-finished notifying shells enqueued via `send()`.
     * `isProcessing` covers those turns once they reach `processQueue`.
     */
    /**
     * Wait until all in-flight native `send()` calls have drained (i.e.
     * `pendingNativeSendCount` returns to zero). Used by an immediate
     * system-notification send that arrives while another native send is in
     * flight but no turn is yet processing: the notification must start its own
     * turn only after the in-flight send settles, rather than steer into an
     * unrelated turn. The `send()` finally block wakes these waiters when the
     * count hits zero.
     */
    private waitForPendingNativeSendsToDrain;
    private waitForNotificationTurnsToDrain;
    private waitForBackgroundNotificationFormattingToSettle;
    private finalizeBackgroundNotifications;
    /**
     * Synchronous because the UI consumes the queued display-prompt list on
     * every render and remote sessions don't currently support steering or
     * queuing. If/when remote steering is added, this and its peers will need
     * to become async (and the UI consumers updated to match).
     */
    private getNativeQueueSnapshot;
    getPendingSteeringMessagesDisplayPrompt(): ReadonlyArray<string>;
    getPendingQueuedMessagesDisplayPrompt(): ReadonlyArray<string>;
    /**
     * Get pending queued items for UI display.
     * Returns both messages and commands with their display text.
     */
    getPendingQueuedItems(): ReadonlyArray<PendingQueuedItem>;
    /**
     * Clear all pending steering and queued items (messages and commands).
     * Used internally when the agentic loop is aborted (e.g., user rejected a tool permission).
     */
    clearPendingItems(): void;
    private applyNativeQueueMutationResult;
    private applyNativeQueueMutationDelta;
    private reconcileNativeQueueMirrorItem;
    private replaceSerializableSendOptions;
    /**
     * Remove the most recently added user-facing pending item from across both
     * the immediate steering queue and the queued-items queue. System items
     * are skipped because they're hidden from the UI and removing them would
     * surprise the user.
     *
     * Native queue state tracks insertion order so items are removed strictly
     * in LIFO order regardless of which queue they entered.
     *
     * A queued `messages` batch is shown as one pending entry per non-system
     * message (see {@link getPendingQueuedItems}), so it is peeled the same
     * way: each call drops only the most-recent non-system message from the
     * batch, and the whole queue item is removed once it holds no more
     * user-facing messages. This keeps LIFO removal aligned with the UI
     * instead of discarding an entire batch on the first peel.
     *
     * @returns true if an item was removed, false when there are no
     *   user-facing pending items left or the latest steering message already
     *   interrupted an active tool wait and must be delivered.
     */
    removeMostRecentPendingItem(): boolean;
    /**
     * Compacts the conversation history into a single summary message.
     * This method is used by the /compact slash command for manual compaction.
     * Uses the same system message and tools as the core agent loop for consistency.
     *
     * @param customInstructions - Optional user-provided instructions to focus the compaction summary
     * @param trigger - What initiated this compaction. Persisted on the compaction events only when provided; omit when the initiator is unknown (the events then persist unattributed).
     * @param tokenLimit - Context window token limit this compaction targets. Overrides the limit resolved from the compacting model on both compaction events; pass it only when the target window is not the compacting model's own (e.g. a model switch compacts on the outgoing model but targets the incoming model's smaller window).
     * @returns Promise that resolves with compaction results
     * @throws Error if compaction fails or prerequisites aren't met
     */
    compactHistory(customInstructions?: string, trigger?: ClientCompactionTrigger, tokenLimit?: number): Promise<CompactionResult>;
    /**
     * Check V8 heap pressure and take corrective action when memory is high.
     *
     * Called at natural checkpoints (turn boundaries, tool completion) where
     * the session can safely pause to reclaim memory. The escalation order,
     * rate limiting, and minimum-benefit gating live in
     * {@link runMemoryPressureResponse}; this method supplies the
     * session-specific operations.
     */
    private respondToMemoryPressure;
    /**
     * Handle background compaction completion callback.
     * This is called immediately when background compaction finishes, allowing the session
     * to emit events and update state without waiting for the next preRequest call.
     */
    private handleCompactionComplete;
    /**
     * Cancels any in-progress background compaction.
     *
     * This should be called when the session state is being rolled back (e.g., Esc Esc),
     * to prevent the compaction result from being applied after the rollback.
     *
     * Returns true if a background compaction was actually in flight and was
     * cancelled; false if there was no compaction to cancel.
     */
    cancelBackgroundCompaction(): boolean;
    abortManualCompaction(): boolean;
    /**
     * Initialize MCP host if configured
     */
    private initializeMcpHost;
    private initializeMcpHostWithVersionSnapshot;
    protected handleMcpServerStateChanged(): void;
    /**
     * Creates the session-scoped generic search tool for the current permitted
     * catalog. The returned state is mutable so refreshes can replace the catalog
     * without replacing the tool callback.
     */
    private createGenericClientToolSearchState;
    /**
     * Applies the common per-turn tool preparation used by both eager metadata
     * initialization and real model requests. Keeping deferral here ensures
     * `/context` reports the same MCP/tool-search state the model will see.
     */
    private prepareToolsForModelRequest;
    private applyPreparedToolPlan;
    private applyToolDeferralPlan;
    /**
     * Get connected IDE info if available.
     * Returns undefined if no IDE is connected.
     */
    private getConnectedIdeInfo;
    private wireMcpHostForToolExecution;
    /**
     * Refreshes `rawMcpToolsForSubagentInheritance` from the local host, just
     * before a subagent inherits it. Must run under the lifecycle mutex (see
     * {@link createSubagentSessionWithFreshMcpInheritance}). Falls back to an
     * empty snapshot on no host or a failed `getTools()`; publishes only if
     * the host is still the one we started with.
     */
    private refreshMcpToolsForSubagentInheritance;
    private createSubagentSessionWithFreshMcpInheritance;
    /**
     * Initializes the session and validates tool filter configuration.
     * This method should be called after the session is fully configured (auth, model, MCP servers)
     * but before the first message is sent. It eagerly builds and caches the tool definitions and system message
     * so they are available for features like /context that need them before the first message.
     * It will also emit warnings for any unknown tool names specified in availableTools or excludedTools.
     *
     * @returns Promise that resolves when initialization and validation is complete
     */
    initializeAndValidateTools(): Promise<void>;
    protected getOrCreateShellConfig(): ShellConfig;
    /**
     * Whether the given model issues requests on the OpenAI Responses API (vs chat completions).
     * Provider-native web search is only ever attached by the Responses request builder, so a
     * completions session must be treated as NOT having native web search: otherwise the
     * client-side web search tool would be stripped with no hosted replacement. BYOK providers
     * carry an explicit `wireApi` (defaulting to completions); CAPI sessions derive the effective
     * route from the resolved model's advertised `supported_endpoints` (the same signal CAPI
     * auto-dispatch uses), NOT the static catalog preference table, which lags newly-advertised
     * models (e.g. `gpt-5.5`/`gpt-5.6`) and would otherwise disable hosted search on CAPI for
     * exactly the models the feature targets. The lookup uses the include-hidden
     * {@link unfilteredModelListCache} (falling back to the picker-only {@link modelListCache}) so
     * a hidden or Auto-resolved model that isn't in the picker subset still resolves to the wire
     * the request will actually be dispatched on.
     */
    private modelUsesResponsesApi;
    /**
     * Whether provider-native ("hosted") web search is actually active for this session: the model
     * config must advertise the `webSearch` capability, the model must run on the Responses API
     * (the only path that attaches the hosted tool), the `copilot_cli_native_web_search` ExP
     * flag must be enabled, AND {@link planNativeWebSearchGate} must confirm the user's own
     * web-search controls would have permitted the client-side `web_search` tool in this turn.
     * This is the single source of truth for both attaching the hosted `web_search` tool to the
     * request and for stripping the client-side MCP web search tool via
     * {@link handleWebSearchTooling}. Gating both on the same decision keeps the flag-off (control)
     * arm and non-Responses sessions behaving exactly as before: the client web search tool is
     * preserved. Conditions are ordered cheap-to-expensive, and the gate is the FINAL conjunct so
     * the ExP flag is always resolved (and its exposure logged) before the gate can decline —
     * without that ordering the flight's telemetry denominator would not be computable.
     */
    private isNativeWebSearchActive;
    /**
     * Whether this session has hooks registered on the tool-call events
     * (`preToolUse`, `preMcpToolCall`, or `permissionRequest`).
     *
     * Hooks are the mechanism for observing and controlling tool calls. Hosted
     * web search is a tool call that can be neither observed nor controlled: it
     * executes inside the model provider and never reaches hook interception. So
     * a session that has opted into tool-call hooks has opted into a model that
     * hosted search silently breaks, whatever any individual hook would have
     * decided.
     *
     * Deliberately keyed on PRESENCE only. No matcher is read and no subject is
     * passed: a matcher naming a tool says the hook targets it, not that it
     * denies it, since hooks allow, add context and rewrite arguments just as
     * often as they deny. Inferring "the user meant to block web search" from a
     * matcher pattern would be a guess, and the gate does not guess. The events
     * are the whole signal, which is why hooks on unrelated events
     * (`sessionStart`, `preCompact`) do not suppress.
     *
     * The three events are not an ad-hoc list. They are exactly the set the
     * runtime itself classifies as authorization-affecting: `EventSchema::AuthMatcher`
     * in `hooks/config.rs` is assigned to these and only these, and the same triple
     * is what `enforce_auth_hook_https` refuses to let run over plaintext HTTP.
     * `permissionRequest` earns its place independently of the other two, because it
     * runs BEFORE the permission service rather than after it and can refuse a call
     * outright (a `behavior` of "deny", or a command hook exiting 2), so a session
     * can gate tool calls entirely through it. Keep this set in step with
     * `EventSchema::AuthMatcher` if the runtime ever grows a fourth.
     *
     * A session with no hook processor reports no presence, which is accurate: no
     * processor means no hooks can run at all. The disposed branch beside it is a
     * guard for an UNREACHABLE state, not an accurate answer for a reachable one —
     * `replaceNativeHookProcessor` disposes the outgoing processor and repoints
     * this field at the live one, so `nativeHookProcessor.isDisposed` is false at
     * every `buildSettingsAndTools()`. Do not widen it on the strength of "a
     * disposed processor runs no hooks": a disposed pipeline fail-CLOSES and
     * rejects every pending tool call, so if that state were ever reachable here
     * the client-side tool would have been denied and this should deny too.
     */
    private nativeWebSearchHookPresence;
    /**
     * Shared method to build settings and initialize tools.
     * Used by both initializeAndValidateTools() and runAgenticLoop().
     *
     * @param problemStatement - Optional problem statement for settings (used by runAgenticLoop)
     * @param opts.eagerInitialization - Set by the eager `initializeAndValidateTools()` pass so
     * web-search normalization runs against the flag-off counterfactual. Deliberately a NAMED
     * option rather than a sixth positional flag: the ordering invariant below is load-bearing,
     * and a positional flag would silently land in the wrong slot if a parameter were ever
     * inserted before it, reopening the feedback loop with no test failing. See the
     * {@link handleWebSearchTooling} call below for why the two passes must agree.
     * @returns Settings and tools, or undefined if initialization failed
     */
    private buildSettingsAndTools;
    private resolveIsDynamicRetrievalMcpEnabled;
    /**
     * When true, dynamic retrieval uses the Blackbird (metis-1024) embedding model.
     * When false, it uses the Copilot text-embedding model. Reads the
     * `DYNAMIC_INSTRUCTIONS_RETRIEVAL_BLACKBIRD` feature flag, which the native
     * settings/tools planner sets from the experiment arm.
     */
    private resolveIsDynamicRetrievalBlackbirdEnabled;
    /**
     * Resolves whether tool search is enabled for the given model. An explicit
     * {@link SessionToolSearchOptions.enabled} override wins over the feature-flag /
     * experiment decision in both directions: `true` forces tool search on for any
     * model that supports it, `false` forces it off.
     */
    private resolveToolSearchEnabled;
    /**
     * Determine whether embedding retrieval should be enabled for this turn,
     * and pre-load the data that each enabled index type will embed.
     *
     * Returns an object with:
     * - enabled: true if any index type is active
     * - indexTypes: Set of InstructionSource types to index (consumed by createSkillTool for terse descriptions)
     * - entriesJson: Rust-shaped serialized index data so initEmbeddingRetrieval can index without re-fetching
     *
     * Thresholds:
     *   - "skill": enabled when skills > 25
     *   - "mcp-server": enabled when deferred MCP instructions exist
     *
     * If neither condition is met, returns { enabled: false } with empty collections.
     * Logs and emits telemetry for each decision so operators can diagnose.
     */
    private shouldEnableEmbeddingRetrieval;
    /**
     * Build or rebuild the embedding-based instruction retrieval index.
     *
     * Uses the pre-loaded data from `shouldEnableEmbeddingRetrieval` to avoid
     * redundant skill loading and MCP instruction fetching. Skips the rebuild
     * when the index is already up-to-date or another rebuild is in progress.
     */
    private initEmbeddingRetrieval;
    private buildEmbeddingRetrievalCapiCreateInput;
    protected isToolEnabled(tool: ToolMetadata): boolean;
    private mergeInheritedMcpTools;
    /**
     * Resolves the callback used by the `createToolSearchTool` shim when a
     * tool-search override is configured. Routes execution to the client using the
     * override's own tool name (the model still sees `tool_search_tool`).
     * Returns undefined when no override is configured.
     */
    protected resolveToolSearchCallbackOverride(): Tool["callback"] | undefined;
    /**
     * Builds the client-side tool-search descriptor from an SDK-supplied
     * tool-search override (an external definition named `tool_search_tool`
     * flagged `overridesBuiltInTool`). Forwarded to the client so the hosted
     * OpenAI `tool_search` entry advertises the consumer's schema instead of the
     * built-in descriptor.
     */
    protected getToolSearchToolDefinition(): {
        description?: string;
        title?: string;
        input_schema?: ToolInputSchema;
    } | undefined;
    /**
     * Validates external tool name clashes with built-in tools and returns the set of
     * built-in tool names that should be removed because they are explicitly overridden.
     * Throws if an external tool clashes with a built-in tool without setting overridesBuiltInTool.
     */
    protected validateExternalToolOverrides(builtInNames: Set<string>): Set<string>;
    /**
     * Builds the callback that routes an external tool's execution back to the
     * host/SDK client over the protocol (permission check, then
     * `requestExternalTool`). Reused both for regular external tools and for an
     * SDK-supplied tool-search override.
     */
    private createExternalToolCallback;
    /** Build Tool[] from the current externalToolDefinitions. */
    private buildExternalTools;
    /**
     * Validates tool filter configuration and emits info about disabled tools and warnings for unknown tool names.
     */
    private validateToolFilters;
    /**
     * Filters tools based on the selected custom agent and defaultAgentExcludedTools, if any.
     *
     * defaultAgentExcludedTools only applies when no custom agent is selected.
     * Custom agents define their own tool lists and are not affected by defaultAgentExcludedTools.
     *
     * @param allTools - All available tools
     * @returns Filtered tools based on selected custom agent and default agent exclusion restrictions
     */
    protected filterToolsForSelectedAgent<T extends ToolMetadata>(allTools: T[]): T[];
    private invokeCallbacks;
    /**
     * Route this (subagent) session's own callback events to the parent session's
     * callback in addition to its own, stamped with this subagent's `agentId`.
     *
     * The event-log sink (configured via `COPILOT_EVENTS_LOG_DIRECTORY`) is
     * stateful and owned by the root session's callback runtime; subagents do not
     * configure their own sink, so without this bridge their `invokeCallbacks`
     * events never reach the event log. Forwarding to the parent — which itself
     * may forward to its parent — ensures they land in the root's log, attributed
     * to the originating agent.
     */
    bridgeCallbacksToParentSession(parent: LocalSession, agentId: string): void;
    /** Emit model_resolution_info telemetry once per session. */
    private emitModelResolutionInfo;
    protected getModelListForHostEffect(options?: {
        skipCache?: boolean;
    }): Promise<{
        list: Model[];
        modelPriceCategories?: Array<{
            id: string;
            priceCategory: string;
        }>;
        quotaSnapshots?: Record<string, unknown>;
        resolvedAuthLogin?: string;
    }>;
    private getModelList;
    private getModelListResult;
    /**
     * Adds the CoCoA cloud-agent identity's concrete non-reserved pin back into the CAPI-only list to cache.
     *
     * For every other client the input list is returned unchanged. The one exception is the
     * CoCoA cloud-agent identity: its concrete pin (e.g. Sonnet 4.6 on a Free/auto-only plan)
     * may be picker-disabled and therefore absent from the picker subset that
     * `resolveAndValidateModel` runs against, so the pin would be silently redirected to Auto
     * (empty picker) or rejected at the first prompt. Add back just that one pinned model from
     * the unfiltered list, matching the create-time preflight in `validateModelForAuth`.
     *
     * We deliberately do NOT swap in the whole unfiltered list: `categorize_models` does not
     * filter on `model_picker_enabled`, so every picker-disabled model would then leak into
     * default resolution and into `buildAvailableModelInfo` (subagent choices). The pinned model
     * is appended (not prepended) so it never displaces the preferred default for an unpinned
     * session. Every other client keeps the picker subset unchanged.
     */
    private selectCapiModelListForCache;
    protected getAvailableModelsForAgentValidation(): Promise<Model[] | undefined>;
    /**
     * Prior user messages for this session (oldest-to-newest) used to build the
     * multi-turn router context. `originalUserMessages` contains clean human
     * text rather than the transformed XML/tool/file context in `_chatMessages`,
     * and excludes source-tagged runtime injections. Source-free messages that
     * precede the primary request in the same batch have not been persisted yet,
     * so append them here in order. The session manager invokes this only for v2
     * treatment and trims it to the latest resolved `historyMessageCount`.
     */
    private collectPriorUserMessages;
    /**
     * Resolves and validates the selected model, returning the model ID and provider configuration.
     * Throws if an explicitly-selected model is not available.
     */
    private resolveAndValidateModel;
    /**
     * Creates a client instance with current session configuration.
     * Extracted from runAgenticLoop to allow reuse for standalone LLM calls.
     *
     * @returns Promise that resolves to a configured client and settings
     * @throws Error if session was not created with authentication info or custom provider
     */
    private getClient;
    /**
     * Mint an Auto v2 token for one ancillary request (compaction, MCP sampling,
     * a side question, the auto-approval judge) that has no prompt of its own.
     *
     * `/auto` requires a prompt and has no renew-this-model operation, so this
     * routes on the conversation's latest user message — with the preceding ones
     * as context, exactly as a turn does. The resulting resolution is
     * **non-committing**: the session keeps the model and multi-turn schedule its
     * turns run on, so a background compaction can never steer the next user
     * turn. It also publishes no notification and advances no schedule.
     *
     * Returns `undefined` when the session has no Auto v2 state of its own (the
     * native side owns that check), when there is no prior user message to route
     * on, or when the `/auto` call fails — in each case the caller degrades to
     * the legacy hop.
     */
    private resolveAncillaryAutoV2;
    /**
     * `401` recovery for an ancillary client running on a session-scoped Auto v2
     * token (see {@link resolveAndValidateModel}). Such a token is not managed by
     * the agentic loop's renewal path, so it can expire or be revoked partway
     * through the one long request these callers make — and without a handler a
     * `401` only earns a bounded fast retry that replays the same dead token.
     *
     * Recovers with another non-committing v2 resolution, so the replacement
     * token is an Auto v2 one like the session's turns use. Falls back to the
     * legacy hop only when that fails, matching how a failed v2 resolution
     * degrades everywhere else rather than turning a broken `/auto` into a failed
     * compaction.
     */
    private recoverAncillaryAutoV2Token;
    /** Catalog metadata for a mid-request model swap, preferring the include-hidden CAPI list. */
    private ancillaryModelInfoJson;
    /**
     * Generates a summarized version of the conversation context suitable for delegation.
     * Uses an LLM to create a concise summary of the existing conversation that fits
     * within size constraints (20k characters).
     *
     * @returns Promise that resolves to a markdown summary of the session context
     * @throws Error if session was not created with authentication info or if summarization fails
     */
    getContextSummary(): Promise<string>;
    /**
     * Executes a sampling inference request on behalf of an MCP server.
     * Uses the sampling client pattern for proper CAPI correlation, billing, and
     * usage telemetry. No boundary events are emitted — sampling has its own UI.
     *
     * @param samplingRequest - Pre-extracted system prompt and user prompt strings
     * @returns Promise resolving to the sampling agent result
     */
    executeSamplingInference(samplingRequest: SamplingInferenceRequest, abortSignal?: AbortSignal): Promise<McpSamplingAgentResult>;
    protected requestAutoApprovalFromModel(rawPermissionRequest: PermissionRequest_2, promptRequest: PermissionPromptRequest_2): Promise<AutoApprovalModelOutput>;
    /**
     * Resolves the model client used for the auto-approval safety judge. When an
     * explicit judge model was configured (e.g. the CLI passing a dedicated,
     * capable safety-review model via `permissions.setAllowAll({ mode: "auto", model })`), a
     * dedicated client for that model is built; if that model can't be resolved
     * (e.g. unavailable to this session), it falls back to the session's active
     * model so the advisory still runs. With no override, the cached session
     * client (or a freshly built one) is used, matching prior behavior.
     *
     * Building the override client uses `commitSelection: false` so validating
     * and constructing the judge client never mutates the session's selected
     * model (the main coding model stays put even for a valid judge override).
     */
    private getAutoApprovalJudgeClient;
    /**
     * Resolves and serializes the definition(s) associated with a permission
     * request so the auto-approval judge sees the concrete tool schema and
     * description inline in its prompt. Returns a JSON string of
     * `{ name, description, input_schema }` object(s) when the tool can be
     * identified, or `undefined` when it cannot (e.g. built-in shell/write/read
     * requests with no matching agent-facing tool), in which case no tool-
     * definition block is added to the prompt.
     */
    private buildAutoApprovalJudgeToolDefinitions;
    private resolveAutoApprovalToolName;
    /**
     * Makes an ephemeral model call using the current conversation context.
     * The question and response are NOT added to conversation history.
     * No tools are provided — the model answers from context alone.
     *
     * @param question - The user's side question
     * @param onChunk - Callback invoked with each streaming text chunk
     * @param abortSignal - Optional signal to cancel the request
     * @returns The full response text
     */
    ephemeralQuery(question: string, onChunk: (text: string) => void, abortSignal?: AbortSignal): Promise<string>;
    /**
     * Executes the full agentic loop for a given prompt.
     * This method orchestrates the complete AI agent workflow including:
     * - Running hooks (userPromptSubmitted, userPromptTransformed, sessionStart, preToolUse, postToolUse, sessionEnd)
     * - Building and sending the prompt to the language model
     * - Processing model responses and tool calls
     * - Executing tools and feeding results back to the model
     * - Emitting events throughout the process
     *
     * This is the core method that powers the `send()` functionality.
     * Most users should call `send()` instead, which handles queuing and mode selection.
     *
     * @param prompt - The user's prompt/instruction text
     * @param attachments - Optional array of file or directory attachments to include with the prompt
     * @param precedingMessages - Additional user messages to append (in order) BEFORE the
     *   primary `prompt` message, so that a batch of user messages is appended to history and
     *   processed as a single turn. Each is emitted as its own `user.message` timeline entry.
     *   The per-turn context preamble is applied only to the primary (final) message.
     * @returns An outcome indicating how the agentic loop ended (normal, rate limited, etc.)
     * @throws Error if the session was not created with authentication info/custom provider or model
     */
    private runAgenticLoop;
    /**
     * Waits for all pending background tasks (agents and shell commands) to complete.
     * Applies an overall timeout to prevent the CLI from hanging indefinitely.
     *
     * Default timeout is 10 minutes. Override with COPILOT_TASK_WAIT_TIMEOUT_SECONDS.
     */
    waitForPendingBackgroundTasks(): Promise<void>;
    /**
     * Creates an IAgentCallback bridge that forwards progress events from an agent
     * execution back to the session. Behavior varies by agent type the bridge is created for.
     */
    createAgentCallbackBridge(options: {
        agentId: string;
        agentType: "subagent";
        taskRegistry: TaskRegistry;
        interactionId?: string;
        isByokExecutor?: boolean;
    } | {
        agentId: string;
        agentType: "sampling";
        isByokExecutor?: boolean;
    }): IAgentCallback;
}

export declare interface LocalSessionMetadata extends SessionMetadata {
    readonly isRemote: false;
    readonly mcTaskId?: string;
    readonly isDetached?: boolean;
}

/** Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. */
declare interface LocalSessionMetadataValue {
    /** Runtime client name that created/last resumed this session */
    clientName?: string;
    /** Pre-resolved working-directory context for session startup. */
    context?: SessionContext_2;
    /** True for detached maintenance sessions that should be hidden from normal resume lists. */
    isDetached?: boolean;
    /** Always false for local sessions. */
    isRemote: false;
    /** GitHub task ID, when this local session is bound to one. Only present for local sessions exported to remote control. */
    mcTaskId?: string;
    /** Last-modified time of the session's persisted state, as ISO 8601 */
    modifiedTime: string;
    /** Optional human-friendly name set via /rename */
    name?: string;
    /** Stable session identifier */
    sessionId: string;
    /** Session creation time as an ISO 8601 timestamp */
    startTime: string;
    /** Short summary of the session, when one has been derived */
    summary?: string;
}

/**
 * A local skill loaded from the filesystem.
 */
declare interface LocalSkill extends SkillBase {
    /** The source location type of this skill. */
    source: LocalSkillSource;
    /** Absolute path to the SKILL.md file. */
    filePath: string;
    /** Absolute path to the skill's base directory. */
    baseDir: string;
    /** The full raw content of SKILL.md or command file. */
    content: string;
}

declare type LocalSkillSource = (typeof LOCAL_SKILL_SOURCES)[number];

/** Basic logging interface */
export declare interface Logger {
    info(message: string): void;
    debug(message: string): void;
    warning(message: string): void;
    error(message: string): void;
}

/** The global logger instance used throughout the application */
export declare const logger: QueuingProxyLogger;

export declare type LogLevel = keyof Logger;

/** Message text, optional severity level, persistence flag, optional follow-up URL, and optional tip. */
declare interface LogRequest {
    /** When true, the message is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Log severity level. Determines how the message is displayed in the timeline. Defaults to "info". */
    level?: SessionLogLevel;
    /** Human-readable message */
    message: string;
    /** Optional actionable tip displayed alongside the message. Only honored on `level: "info"`. */
    tip?: string;
    /** Domain category for this log entry (e.g., "mcp", "subscription", "policy", "model"). Maps to `infoType`/`warningType`/`errorType` on the emitted event. Defaults to "notification". */
    type?: string;
    /** Optional URL the user can open in their browser for more details */
    url?: string;
}

/** Identifier of the session event that was emitted for the log message. */
declare interface LogResult {
    /** The unique identifier of the emitted session event */
    eventId: string;
}

/** Interface for an implementer of writing log messages asynchronously. */
export declare interface LogWriter {
    /** Write a log message at the given level.
     * @returns A promise that resolves when all pending writes are complete
     */
    writeLog(level: LogLevel, message: string): Promise<void>;
    /** @returns the current file path or other identifier if not writing to a file. */
    outputPath(): string;
    /** Drain any writes the implementation buffers outside of {@link writeLog}.
     *
     * The native file logger accepts records from the runtime's own `tracing`
     * subscriber as well as from {@link writeLog}, so awaiting the last
     * `writeLog` promise alone does not prove the file is complete.
     */
    flush?(): Promise<void>;
    /** Enqueue a log record without waiting for it to reach the sink.
     *
     * {@link writeLog} both enqueues and flushes, and its enqueue half only runs
     * once the returned promise is first driven — so two overlapping calls can
     * reach the sink out of order. Implementations that can enqueue synchronously
     * expose this instead; it is only used alongside {@link flush}, which keeps
     * `writeLog`'s per-record durability barrier.
     */
    write?(level: LogLevel, message: string): void;
}

/** Parameters for (re)loading the merged LSP configuration set. */
declare interface LspInitializeRequest {
    /** Force re-initialization even when LSP configs were already loaded for the working directory. */
    force?: boolean;
    /** Git root used as the boundary when traversing for project-level LSP configs (supports monorepos). */
    gitRoot?: string;
    /** Working directory used to load project-level LSP configs. Defaults to the session working directory when omitted. */
    workingDirectory?: string;
}

declare type LspServiceReminderInput = {
    id: string;
    serviceId: string;
    ready: boolean;
    status: BackgroundTaskStatus;
    phase?: string;
    percentage?: number;
    error?: string;
};

/**
 * The enterprise-managed MCP allow/deny policy composed across managed sources
 * (server + device), in the shape the MCP host / Rust engine consume.
 *
 * `allowedLists` carries one allowlist per source that declares one, applied as
 * an allowlist-intersection (a server must be admitted by EVERY list); an empty
 * `allowedLists` imposes no allow restriction. `denied` is the union of every
 * source's deny entries (deny-wins).
 */
declare interface ManagedMcpPolicy {
    allowedLists: ManagedMcpServerMatcher[][];
    denied: ManagedMcpServerMatcher[];
}

/**
 * A single enterprise-managed MCP allow/deny entry (managed settings only),
 * aligned with Claude Code's `allowedMcpServers` / `deniedMcpServers` schema.
 * Exactly one field is present per entry:
 *
 * - `serverUrl` — matches a remote (HTTP/SSE) server by URL, supporting `*`
 *   wildcards (scheme/host case-insensitive, path case-sensitive; `${VAR}`
 *   references expand before matching).
 * - `serverCommand` — matches a stdio server by its exact `[command, ...args]`.
 * - `serverName` — matches any server by its assigned label (literal, no
 *   wildcards).
 */
declare type ManagedMcpServerMatcher = {
    serverUrl: string;
} | {
    serverCommand: string[];
} | {
    serverName: string;
};

/**
 * Enterprise permission policy. Rule strings use the runtime's managed
 * permission syntax and are validated by the Rust permission-rule parser.
 */
declare interface ManagedPermissionsSettings {
    /** Disables bypass/allow-all permission modes while set to `"disable"`. */
    disableBypassPermissionsMode?: string;
    /** Matching requests are blocked. Highest decision precedence. */
    deny?: string[];
    /** Matching requests require interactive approval, even if another rule allows them. */
    ask?: string[];
    /** Matching requests are approved only when every declared source allowlist admits them and no deny/ask matches. */
    allow?: string[];
    [key: string]: unknown;
}

/**
 * The enterprise managed-settings `permissions` slice, forwarded verbatim to the
 * permission engine which interprets it (e.g. `disableBypassPermissionsMode`).
 * Kept as an open record so new managed permission settings flow through without
 * changes to this layer — interpretation lives in the engine, not here.
 */
declare type ManagedPermissionsSlice = Readonly<Record<string, unknown>>;

declare type ManagedRemoteControlMode = "enabled" | "disabled" | "requireSSO";

declare interface ManagedRemoteControlSettings {
    mode: ManagedRemoteControlMode;
    githubDotComOrganizations?: string[];
    githubEnterpriseCloudDomains?: string[];
}

/**
 * First-class enterprise-managed settings type — the parsed managed subset of
 * {@link UserSettings}. Parsing/validation is performed by the native (Rust)
 * `settingsParseManagedSettings`, so this is a plain structural alias of
 * {@link ManagedSettingsResponse} rather than a second (Zod) schema to keep in
 * sync. Shared by both delivery paths: self-fetch (`fetchManagedSettings`) and
 * device MDM (`loadMdmManagedSettings`).
 */
declare type ManagedSettings = ManagedSettingsResponse;

/** The category of runtime action that enterprise managed settings governed (blocked or capped) */
export declare type ManagedSettingsEnforcedAction = "bypass_permissions_blocked";

/** Runtime enforcement of enterprise managed settings: fires when the session blocks or caps a runtime action because enterprise policy governs it, so SDK clients can explain *why* an action was governed. Unlike `session.managed_settings_resolved` (which reports *what* is managed), this reports a concrete governed action — e.g. a user or host tried to turn on a bypass-permissions escalation while policy disables it. Emitted live (not persisted to the session event log) on user/host-initiated attempts only, never for silent policy application. Marked experimental while the managed-settings surface stabilizes. */
export declare interface ManagedSettingsEnforcedData {
    /** The category of runtime action that managed policy governed. */
    action: ManagedSettingsEnforcedAction;
    /** For a `bypass_permissions_blocked` action, which permission-escalation primitive was refused. Absent for actions without a specific escalation primitive. */
    escalation?: ManagedSettingsEnforcedEscalation;
    /** Whether the enforcement was forced by fail-closed handling (managed policy could not be determined) rather than an explicit managed setting. When true, `setting` still names the restriction that was applied. */
    failClosed: boolean;
    /** A human-readable explanation of why the action was governed, suitable for surfacing to the user. */
    message: string;
    /** The managed setting key responsible for the enforcement (e.g. `permissions.disableBypassPermissionsMode`). */
    setting: string;
}

/** For a `bypass_permissions_blocked` action, which permission-escalation primitive was refused */
export declare type ManagedSettingsEnforcedEscalation = "allow_all" | "approve_all" | "auto_approval" | "unrestricted_paths" | "unrestricted_urls";

/** Session event "session.managed_settings_enforced". Runtime enforcement of enterprise managed settings: fires when the session blocks or caps a runtime action because enterprise policy governs it, so SDK clients can explain *why* an action was governed. Unlike `session.managed_settings_resolved` (which reports *what* is managed), this reports a concrete governed action — e.g. a user or host tried to turn on a bypass-permissions escalation while policy disables it. Emitted live (not persisted to the session event log) on user/host-initiated attempts only, never for silent policy application. Marked experimental while the managed-settings surface stabilizes. */
export declare interface ManagedSettingsEnforcedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Runtime enforcement of enterprise managed settings: fires when the session blocks or caps a runtime action because enterprise policy governs it, so SDK clients can explain *why* an action was governed. Unlike `session.managed_settings_resolved` (which reports *what* is managed), this reports a concrete governed action — e.g. a user or host tried to turn on a bypass-permissions escalation while policy disables it. Emitted live (not persisted to the session event log) on user/host-initiated attempts only, never for silent policy application. Marked experimental while the managed-settings surface stabilizes. */
    data: ManagedSettingsEnforcedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.managed_settings_enforced". */
    type: "session.managed_settings_enforced";
}

/** Validated device-managed settings discovered before a session exists. */
declare interface ManagedSettingsReadResult {
    /** Discovery or validation error text when managed settings could not be read safely. */
    errorMessage?: string;
    /** Validated, canonical managed-settings JSON. Omitted when no managed settings were discovered or when discovered settings failed validation. */
    settingsJson?: unknown;
}

/** Enterprise managed-settings resolution: the effective managed settings the session applied and which channels contributed, so SDK clients can show users what is enterprise-managed. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted. Device values take precedence over server values per ordinary key, while permissions compose restrictively across device, server, and SDK-client layers. The account-scoped `getManagedSettings()` API does not include session-local client injection. Marked experimental while the managed-settings surface stabilizes. */
export declare interface ManagedSettingsResolvedData {
    /** Whether enterprise policy disables bypass-permissions ("yolo") mode for this session. Deny-wins across layers, and forced on when `failClosed` is true. */
    bypassPermissionsDisabled: boolean;
    /** Whether a session-local permissions layer injected by the SDK host was present */
    clientManaged?: boolean;
    /** Whether an actual device MDM/plist/registry/file managed-settings layer was present */
    deviceManaged: boolean;
    /** Whether managed policy could not be determined (e.g. a failed server fetch) and the session fell back to the fail-closed restriction. When true, restrictions such as disabling bypass-permissions are enforced even though `settings` may be absent. */
    failClosed: boolean;
    /** The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. */
    managedKeys: string[];
    /** Whether at least two managed sources supplied permission allowlists, so enforcement intersects them and the flattened settings payload omits `permissions.allow`. */
    permissionsAllowIntersected?: boolean;
    /** Whether the server (account/org) managed-settings layer was present */
    serverManaged: boolean;
    /** The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. */
    settings?: unknown;
    /** Channel summary: `server`, `device`, or `client` when exactly one channel contributed; `mixed` when multiple channels contributed; otherwise `none`. Consult the per-channel booleans for exact provenance. */
    source: ManagedSettingsResolvedSource;
}

/** Session event "session.managed_settings_resolved". Enterprise managed-settings resolution: the effective managed settings the session applied and which channels contributed, so SDK clients can show users what is enterprise-managed. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted. Device values take precedence over server values per ordinary key, while permissions compose restrictively across device, server, and SDK-client layers. The account-scoped `getManagedSettings()` API does not include session-local client injection. Marked experimental while the managed-settings surface stabilizes. */
export declare interface ManagedSettingsResolvedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Enterprise managed-settings resolution: the effective managed settings the session applied and which channels contributed, so SDK clients can show users what is enterprise-managed. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted. Device values take precedence over server values per ordinary key, while permissions compose restrictively across device, server, and SDK-client layers. The account-scoped `getManagedSettings()` API does not include session-local client injection. Marked experimental while the managed-settings surface stabilizes. */
    data: ManagedSettingsResolvedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.managed_settings_resolved". */
    type: "session.managed_settings_resolved";
}

/** Summary of which managed-settings channels contributed to the effective session policy. Use the per-channel booleans for exact provenance. */
export declare type ManagedSettingsResolvedSource = "server" | "device" | "client" | "mixed" | "none";

/** Response shape for managed settings — the subset of UserSettings fetched from the server. */
declare type ManagedSettingsResponse = Pick<UserSettings, "model" | "enabledPlugins" | "extraKnownMarketplaces" | "permissions" | "remoteControl" | "shellShortcut" | "forceRemoteSettingsRefresh" | "strictKnownMarketplaces" | "telemetry" | "allowedMcpServers" | "deniedMcpServers" | "sandbox">;

/**
 * Enterprise-mandated OpenTelemetry configuration delivered via managed
 * settings. Admin-only and non-overridable by users; the managed values take
 * precedence over environment variables. Fields omitted here fall back to the
 * standard `OTEL_*` / `COPILOT_OTEL_*` environment-variable configuration.
 *
 * v1 only supports the OTLP/HTTP exporter for transport. Header values are
 * literal strings (no secret interpolation yet).
 *
 * The shape is validated in the native (Rust) managed-settings layer; this
 * interface is the TypeScript source of truth for the type.
 */
declare interface ManagedTelemetrySettings {
    /** Enables OTel emission; users cannot disable export when true. */
    enabled?: boolean;
    /** OTLP collector endpoint (⇄ OTEL_EXPORTER_OTLP_ENDPOINT). */
    endpoint?: string;
    /**
     * OTLP transport protocol used for all exported telemetry. Equivalent to the
     * OTEL_EXPORTER_OTLP_PROTOCOL environment variable; the managed value takes
     * precedence over any user-provided value. Recognized values are "http/json"
     * and "http/protobuf" ("grpc" is accepted for forward compatibility but is
     * not implemented in this version and falls back to the default protocol).
     */
    protocol?: string;
    /** Auth/routing headers (⇄ OTEL_EXPORTER_OTLP_HEADERS). Never logged. */
    headers?: Record<string, string>;
    /** Extra OTel resource attributes (⇄ OTEL_RESOURCE_ATTRIBUTES). */
    resourceAttributes?: Record<string, string>;
    /** Capture sensitive content (prompts/responses/tool args). Defaults false. */
    captureContent?: boolean;
    /** Prevents users from enabling content capture themselves. */
    lockCaptureContent?: boolean;
    /** Overrides the OTel service.name resource attribute (⇄ OTEL_SERVICE_NAME). */
    serviceName?: string;
}

/** Result of registering a new marketplace. */
declare interface MarketplaceAddResult {
    /** Final name of the marketplace as resolved from its manifest */
    name: string;
}

/** Plugins advertised by the marketplace. */
declare interface MarketplaceBrowseResult {
    /** Plugins advertised by the marketplace */
    plugins: MarketplacePluginInfo[];
}

/** Registered marketplace summary. */
declare interface MarketplaceInfo {
    /** True when this is a default marketplace shipped with the runtime. Defaults are not removable. */
    isDefault?: boolean;
    /** Marketplace name (matches the @marketplace suffix in plugin specs) */
    name: string;
    /** Human-readable description of where the marketplace data is fetched from (e.g. "GitHub: owner/repo"). */
    source: string;
}

/** All registered marketplaces, including built-in defaults. */
declare interface MarketplaceListResult {
    /** Registered marketplaces */
    marketplaces: MarketplaceInfo[];
}

/** Plugin entry advertised by a marketplace. */
declare interface MarketplacePluginInfo {
    /** Short description from the marketplace catalog, when present */
    description?: string;
    /** Plugin name as listed in the marketplace catalog */
    name: string;
}

/** Per-marketplace refresh result, including marketplace name, success flag, and optional failure error. */
declare interface MarketplaceRefreshEntry {
    /** Error message (failure only) */
    error?: string;
    /** Marketplace name that was refreshed */
    name: string;
    /** Whether the refresh succeeded */
    success: boolean;
}

/** Result of refreshing one or more marketplace catalogs. */
declare interface MarketplaceRefreshResult {
    /** Per-marketplace refresh results in deterministic order. */
    results: MarketplaceRefreshEntry[];
}

/** Outcome of the remove attempt, including dependent-plugin info when applicable. */
declare interface MarketplaceRemoveResult {
    /** Names of installed plugins that prevented removal. Populated only when `removed=false`. */
    dependentPlugins?: string[];
    /** True when the marketplace was actually removed. False when removal was skipped because the marketplace has dependent plugins and `force` was not set. */
    removed: boolean;
}

export declare const MAX_CONSECUTIVE_AGENT_STOP_BLOCKS: number;

/** MCP server allowed by policy, with server name and optional PII-free explanatory note. */
declare interface McpAllowedServer {
    /** Allowed server name */
    name: string;
    /** PII-free note explaining why the server was allowed */
    redactedNote?: string;
}

/**
 * A non-default server that passed an {@link McpConfigFilter}.
 */
declare interface McpAllowedServer_2 {
    /** The config key / name of the server. */
    name: string;
    /** PII-free note about why the server was allowed (e.g. "Found in registry <hash>"). */
    redactedNote?: string;
}

/** MCP server, tool name, and arguments to invoke from an MCP App view. */
declare interface McpAppsCallToolRequest {
    /** Tool arguments */
    arguments?: Record<string, unknown>;
    /** **Required.** Server whose ui:// view issued the request. Per SEP-1865 ('callable by the app from this server only'), the call is rejected when this differs from `serverName`, and rejected outright when missing. */
    originServerName: string;
    /** MCP server hosting the tool */
    serverName: string;
    /** MCP tool name */
    toolName: string;
}

/** Capability negotiation snapshot */
declare interface McpAppsDiagnoseCapability {
    /** Whether the runtime advertises `extensions.io.modelcontextprotocol/ui` to MCP servers */
    advertised: boolean;
    /** Whether the MCP_APPS feature flag (or COPILOT_MCP_APPS env override) is on */
    featureFlagEnabled: boolean;
    /** Whether the session has the `mcp-apps` capability */
    sessionHasMcpApps: boolean;
}

/** MCP server to diagnose MCP Apps wiring for. */
declare interface McpAppsDiagnoseRequest {
    /** MCP server to probe */
    serverName: string;
}

/** Diagnostic snapshot of MCP Apps wiring for the named server. */
declare interface McpAppsDiagnoseResult {
    /** Capability negotiation snapshot */
    capability: McpAppsDiagnoseCapability;
    /** What the server returned for this session */
    server: McpAppsDiagnoseServer;
}

/** What the server returned for this session */
declare interface McpAppsDiagnoseServer {
    /** Whether the named server is currently connected */
    connected: boolean;
    /** Up to 5 tool names with `_meta.ui` for quick inspection */
    sampleToolNames: string[];
    /** Total tools returned by the server's tools/list */
    toolCount: number;
    /** Tools whose `_meta.ui` is populated (resourceUri and/or visibility set) */
    toolsWithUiMeta: number;
}

/** Current host context advertised to MCP App guests. */
declare interface McpAppsHostContext {
    /** Current host context */
    context: McpAppsHostContextDetails;
}

/** Current host context */
declare interface McpAppsHostContextDetails {
    /** Display modes the host supports */
    availableDisplayModes?: McpAppsHostContextDetailsAvailableDisplayMode[];
    /** Current display mode (SEP-1865) */
    displayMode?: McpAppsHostContextDetailsDisplayMode;
    /** BCP-47 locale, e.g. 'en-US' */
    locale?: string;
    /** Platform type for responsive design */
    platform?: McpAppsHostContextDetailsPlatform;
    /** UI theme preference per SEP-1865 */
    theme?: McpAppsHostContextDetailsTheme;
    /** IANA timezone, e.g. 'America/New_York' */
    timeZone?: string;
    /** Host application identifier */
    userAgent?: string;
    [key: string]: unknown;
}

/** Allowed values for the `McpAppsHostContextDetailsAvailableDisplayMode` enumeration. */
declare type McpAppsHostContextDetailsAvailableDisplayMode = "inline" | "fullscreen" | "pip";

/** Current display mode (SEP-1865) */
declare type McpAppsHostContextDetailsDisplayMode = "inline" | "fullscreen" | "pip";

/** Platform type for responsive design */
declare type McpAppsHostContextDetailsPlatform = "web" | "desktop" | "mobile";

/** UI theme preference per SEP-1865 */
declare type McpAppsHostContextDetailsTheme = "light" | "dark";

/** MCP server to list app-callable tools for. */
declare interface McpAppsListToolsRequest {
    /** **Required.** Server whose ui:// view issued the request. Per SEP-1865 ('callable by the app from this server only'), the call is rejected when this differs from `serverName`, and rejected outright when missing. */
    originServerName: string;
    /** MCP server hosting the app */
    serverName: string;
}

/** App-callable tools from the named MCP server. */
declare interface McpAppsListToolsResult {
    /** App-callable tools from the server */
    tools: Record<string, unknown>[];
}

/** MCP server and resource URI to fetch. */
declare interface McpAppsReadResourceRequest {
    /** Name of the MCP server hosting the resource */
    serverName: string;
    /** Resource URI (typically ui://...) */
    uri: string;
}

/** Resource contents returned by the MCP server. */
declare interface McpAppsReadResourceResult {
    /** Resource contents returned by the server */
    contents: McpAppsResourceContent[];
}

/** MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource metadata. */
declare interface McpAppsResourceContent {
    /** Resource-level metadata (CSP, permissions, etc.) */
    _meta?: Record<string, unknown>;
    /** Base64-encoded binary content */
    blob?: string;
    /** MIME type of the content */
    mimeType?: string;
    /** Text content (e.g. HTML) */
    text?: string;
    /** The resource URI (typically ui://...) */
    uri: string;
}

/** Host context advertised to MCP App guests */
declare interface McpAppsSetHostContextDetails {
    /** Display modes the host supports */
    availableDisplayModes?: McpAppsSetHostContextDetailsAvailableDisplayMode[];
    /** Current display mode (SEP-1865) */
    displayMode?: McpAppsSetHostContextDetailsDisplayMode;
    /** BCP-47 locale, e.g. 'en-US' */
    locale?: string;
    /** Platform type for responsive design */
    platform?: McpAppsSetHostContextDetailsPlatform;
    /** UI theme preference per SEP-1865 */
    theme?: McpAppsSetHostContextDetailsTheme;
    /** IANA timezone, e.g. 'America/New_York' */
    timeZone?: string;
    /** Host application identifier */
    userAgent?: string;
    [key: string]: unknown;
}

/** Allowed values for the `McpAppsSetHostContextDetailsAvailableDisplayMode` enumeration. */
declare type McpAppsSetHostContextDetailsAvailableDisplayMode = "inline" | "fullscreen" | "pip";

/** Current display mode (SEP-1865) */
declare type McpAppsSetHostContextDetailsDisplayMode = "inline" | "fullscreen" | "pip";

/** Platform type for responsive design */
declare type McpAppsSetHostContextDetailsPlatform = "web" | "desktop" | "mobile";

/** UI theme preference per SEP-1865 */
declare type McpAppsSetHostContextDetailsTheme = "light" | "dark";

/** Host context to advertise to MCP App guests. */
declare interface McpAppsSetHostContextRequest {
    /** Host context advertised to MCP App guests */
    context: McpAppsSetHostContextDetails;
}

/** MCP App view called a tool on a connected MCP server (SEP-1865) */
export declare interface McpAppToolCallCompleteData {
    /** Arguments passed to the tool by the app view, if any */
    arguments?: Record<string, unknown>;
    /** Wall-clock duration of the underlying tools/call in milliseconds */
    durationMs: number;
    /** Set when the underlying tools/call threw an error before returning a CallToolResult */
    error?: McpAppToolCallCompleteError;
    /** Standard MCP CallToolResult returned by the server. Present whether or not the call set isError. */
    result?: Record<string, unknown>;
    /** Name of the MCP server hosting the tool */
    serverName: string;
    /** True when the call completed without throwing AND the MCP CallToolResult did not set isError */
    success: boolean;
    /** The tool's `_meta.ui` block at the time of the call, so consumers can decide whether to forward the result to the model without re-listing tools. */
    toolMeta?: McpAppToolCallCompleteToolMeta;
    /** MCP tool name that was invoked */
    toolName: string;
}

/** Set when the underlying tools/call threw an error before returning a CallToolResult */
export declare interface McpAppToolCallCompleteError {
    /** Human-readable error message */
    message: string;
}

/** Session event "mcp_app.tool_call_complete". MCP App view called a tool on a connected MCP server (SEP-1865) */
export declare interface McpAppToolCallCompleteEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** MCP App view called a tool on a connected MCP server (SEP-1865) */
    data: McpAppToolCallCompleteData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp_app.tool_call_complete". */
    type: "mcp_app.tool_call_complete";
}

/** The tool's `_meta.ui` block at the time of the call, so consumers can decide whether to forward the result to the model without re-listing tools. */
export declare interface McpAppToolCallCompleteToolMeta {
    /** MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. */
    ui?: McpAppToolCallCompleteToolMetaUI;
    [key: string]: unknown;
}

/** MCP App tool `_meta.ui` resource URI and SEP-1865 visibility captured with an `mcp_app.tool_call_complete` result. */
export declare interface McpAppToolCallCompleteToolMetaUI {
    /** `ui://` URI declared by the tool's `_meta.ui.resourceUri` */
    resourceUri?: string;
    /** Tool visibility per SEP-1865 (typically a subset of `["model","app"]`) */
    visibility?: string[];
    [key: string]: unknown;
}

/** The requestId previously passed to executeSampling that should be cancelled. */
declare interface McpCancelSamplingExecutionParams {
    /** The requestId previously passed to executeSampling that should be cancelled */
    requestId: string;
}

/** Indicates whether an in-flight sampling execution with the given requestId was found and cancelled. */
declare interface McpCancelSamplingExecutionResult {
    /** True if an in-flight execution with the given requestId was found and signalled to cancel. False when no such execution is in flight (already completed, never started, or cancelled by another caller). */
    cancelled: boolean;
}

/**
 * Client registration info from dynamic registration (RFC 7591) or static configuration
 */
declare interface MCPClientRegistration {
    serverUrl: string;
    authorizationServerUrl: string;
    clientId: string;
    clientSecret?: string;
    /** The redirect URI used during client registration. Required for re-authentication. */
    redirectUri?: string;
    /** The resource URL (RFC 8707) for this server, used in token requests. */
    resourceUrl?: string;
    issuedAt?: number;
    expiresAt?: number;
    /**
     * When true, indicates this is a statically configured client (not dynamically registered).
     * Static clients should not attempt re-registration if authentication fails.
     */
    isStatic?: boolean;
    /**
     * When true, the callback server uses HTTPS with a self-signed certificate.
     * This is set when the OAuth provider requires HTTPS redirect URIs and the
     * initial HTTP registration attempt failed.
     */
    httpsRedirect?: boolean;
}

/** MCP server name and configuration to add to user configuration. */
declare interface McpConfigAddRequest {
    /** MCP server configuration (stdio process or remote HTTP/SSE) */
    config: McpServerConfig;
    /** Unique name for the MCP server */
    name: string;
}

/** MCP server names to disable for new sessions. */
declare interface McpConfigDisableRequest {
    /** Names of MCP servers to disable. Each server is added to the persisted disabled list so new sessions skip it. Already-disabled names are ignored. Active sessions keep their current connections until they end. */
    names: string[];
}

/** MCP server names to enable for new sessions. */
declare interface McpConfigEnableRequest {
    /** Names of MCP servers to enable. Each server is removed from the persisted disabled list so new sessions spawn it. Unknown or already-enabled names are ignored. */
    names: string[];
}

/**
 * A filter that transforms MCP server configurations before servers are started.
 * Receives the full parsed config and returns the filtered config together with
 * information about any servers that were removed and why.
 * Runs during server startup, after default server injection and 3P policy filtering,
 * but before disabled-server filtering.
 */
declare interface McpConfigFilter {
    filter(config: MCPServersConfig): Promise<McpConfigFilterResult>;
}

/**
 * The result of applying an {@link McpConfigFilter}.
 */
declare interface McpConfigFilterResult {
    /** The (potentially reduced) server configuration to continue with. */
    config: MCPServersConfig;
    /** Servers that were removed by the filter, each with a display reason. */
    filteredServers: McpFilteredServer_2[];
    /** Non-default servers that passed the filter. */
    allowedServers?: McpAllowedServer_2[];
}

/** User-configured MCP servers, keyed by server name. */
declare interface McpConfigList {
    /** All MCP servers from user config, keyed by name */
    servers: Record<string, McpServerConfig>;
}

/** MCP server name to remove from user configuration. */
declare interface McpConfigRemoveRequest {
    /** Name of the MCP server to remove */
    name: string;
}

/** MCP server name and replacement configuration to write to user configuration. */
declare interface McpConfigUpdateRequest {
    /** MCP server configuration (stdio process or remote HTTP/SSE) */
    config: McpServerConfig;
    /** Name of the MCP server to update */
    name: string;
}

/** Opaque auth info used to configure GitHub MCP. */
declare interface McpConfigureGitHubRequest {
    /** Opaque runtime auth info for GitHub MCP configuration. Marked internal: an in-process runtime shape (configureGitHubMcp is a no-op over the wire). */
    authInfo: unknown;
}

/** Result of configuring GitHub MCP. */
declare interface McpConfigureGitHubResult {
    /** Whether GitHub MCP configuration changed. */
    changed: boolean;
}

/** Name of the MCP server to disable for the session. */
declare interface McpDisableRequest {
    /** Name of the MCP server to disable */
    serverName: string;
}

/** Optional working directory used as context for MCP server discovery. */
declare interface McpDiscoverRequest {
    /** Working directory used as context for discovery (e.g., plugin resolution) */
    workingDirectory?: string;
}

/** MCP servers discovered from user, workspace, plugin, and built-in sources. */
declare interface McpDiscoverResult {
    /** MCP servers discovered from all sources */
    servers: DiscoveredMcpServer[];
}

/** Name of the MCP server to enable for the session. */
declare interface McpEnableRequest {
    /** Name of the MCP server to enable */
    serverName: string;
}

/** Identifiers and raw MCP CreateMessageRequest params used to run a sampling inference. */
declare interface McpExecuteSamplingParams {
    /** The original MCP JSON-RPC request ID (string or number). Used by the runtime to correlate the inference with the originating MCP request for telemetry; this is distinct from `requestId` (which is the schema-level cancellation handle). */
    mcpRequestId: unknown;
    /** Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. */
    request: McpExecuteSamplingRequest;
    /** Caller-provided unique identifier for this sampling execution. Use this same ID with cancelSamplingExecution to cancel the in-flight call. Must be unique within the session for the lifetime of the call. */
    requestId: string;
    /** Name of the MCP server that initiated the sampling request */
    serverName: string;
}

/** Raw MCP CreateMessageRequest params, as received in the `sampling.requested` event. Treated as opaque at the schema layer; the runtime converts the embedded MCP messages into the OpenAI chat-completion shape internally. */
declare interface McpExecuteSamplingRequest {
    [key: string]: unknown;
}

/** MCP CreateMessageResult payload (with optional 'tools' extension), present when action='success'. Treated as opaque at the schema layer; consumers should construct/consume it per the MCP CreateMessageResult shape. */
declare interface McpExecuteSamplingResult {
    [key: string]: unknown;
}

/** MCP server filtered by policy, with name, reason, and optional redacted reason. */
declare interface McpFilteredServer {
    /**
     * Deprecated. This field is no longer populated.
     * @deprecated
     */
    enterpriseName?: string;
    /** Filtered server name */
    name: string;
    /** Human-readable filter reason */
    reason: string;
    /** PII-free filter reason */
    redactedReason?: string;
}

/**
 * A server that was filtered out by an {@link McpConfigFilter}, along with
 * a human-readable reason suitable for display to the user.
 */
declare interface McpFilteredServer_2 {
    /** The config key / name of the server that was filtered out. */
    name: string;
    /** Human-readable explanation of why the server was filtered out. */
    reason: string;
    /** PII-free version of {@link reason} with URLs and names hashed. Safe for non-restricted telemetry. */
    redactedReason?: string;
}

/** Host response: supply dynamic headers or decline this refresh. */
declare type McpHeadersHandlePendingHeadersRefreshRequest = {
    headers: Record<string, string>;
    kind: "headers";
    [key: string]: unknown;
} | {
    kind: "none";
    [key: string]: unknown;
};

/** MCP headers refresh request id and the host response. */
declare interface McpHeadersHandlePendingHeadersRefreshRequestRequest {
    /** Headers refresh request identifier from mcp.headers_refresh_required */
    requestId: string;
    /** Host response: supply dynamic headers or decline this refresh. */
    result: McpHeadersHandlePendingHeadersRefreshRequest;
}

/** Indicates whether the pending MCP headers refresh response was accepted. */
declare interface McpHeadersHandlePendingHeadersRefreshRequestResult {
    /** Whether the response was accepted. False if the request was unknown, timed out, or already resolved. */
    success: boolean;
}

/** MCP headers refresh request completion notification */
export declare interface McpHeadersRefreshCompletedData {
    /** How the pending MCP headers refresh request resolved. */
    outcome: McpHeadersRefreshCompletedOutcome;
    /** Request ID of the resolved headers refresh request */
    requestId: string;
}

/** Session event "mcp.headers_refresh_completed". MCP headers refresh request completion notification */
export declare interface McpHeadersRefreshCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** MCP headers refresh request completion notification */
    data: McpHeadersRefreshCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp.headers_refresh_completed". */
    type: "mcp.headers_refresh_completed";
}

/** How the pending MCP headers refresh request resolved. */
export declare type McpHeadersRefreshCompletedOutcome = "headers" | "none" | "timeout";

/**
 * Per-session cache for SDK-host-provided dynamic MCP request headers.
 *
 * All cached/refresh/reuse policy decisions (TTL expiry, refresh reason,
 * invalidation generations, single-flight eligibility) are owned by the Rust
 * `HeadersRefreshManager`. This class is a thin shim that additionally owns the
 * three JavaScript-object-model concerns that cannot cross the napi/JSON
 * boundary while callers are still TypeScript:
 *   1. object identity of cached header records (so `===` reference checks by
 *      still-JS callers keep working across a cache hit),
 *   2. sharing the *same* in-flight Promise between concurrent callers, and
 *   3. rejecting non-string header values (e.g. `undefined`) that
 *      `JSON.stringify` would silently drop before Rust ever sees them.
 * Once callers are Rust these concerns disappear and this shim can be deleted.
 */
declare class McpHeadersRefreshManager {
    private readonly callback;
    private readonly handle;
    private readonly finalizerToken;
    /** Shared in-flight refresh promises, keyed by cache key, for single-flight parity. */
    private readonly inflightRefreshes;
    /** Last resolved header record per cache key, preserved for reference-identity parity. */
    private readonly resolvedHeaders;
    constructor(callback: HeadersRefreshCallback);
    getHeaders(params: HeadersRefreshParams): Promise<Record<string, string> | undefined>;
    refreshAfterAuthFailure(params: AuthFailedHeadersRefreshParams): Promise<Record<string, string> | undefined>;
    invalidate(serverName: string): void;
    private begin;
    private refreshCore;
    /**
     * Return the previously resolved header record for a cache hit when its
     * contents still match Rust's authoritative cache, preserving reference
     * identity for still-JS callers; otherwise fall back to Rust's payload.
     */
    private resolveCached;
    private storeResolved;
}

/** Dynamic headers refresh request for a remote MCP server */
export declare interface McpHeadersRefreshRequiredData {
    /** Why dynamic headers are being requested. */
    reason: McpHeadersRefreshRequiredReason;
    /** Unique identifier for this headers refresh request; used to respond via session.mcp.headers.handlePendingHeadersRefreshRequest() */
    requestId: string;
    /** Display name of the remote MCP server requesting headers */
    serverName: string;
    /** URL of the remote MCP server requesting headers */
    serverUrl: string;
}

/** Session event "mcp.headers_refresh_required". Dynamic headers refresh request for a remote MCP server */
export declare interface McpHeadersRefreshRequiredEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Dynamic headers refresh request for a remote MCP server */
    data: McpHeadersRefreshRequiredData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp.headers_refresh_required". */
    type: "mcp.headers_refresh_required";
}

/** Why dynamic headers are being requested. */
export declare type McpHeadersRefreshRequiredReason = "startup" | "ttl-expired" | "auth-failed";

/**
 * Manages the lifecycle of MCP (Model Context Protocol) servers and provides access to their tools.
 */
declare class McpHost {
    protected registry: MCPRegistry;
    private configAdapter;
    private readonly nativeHost;
    protected config: MCPServersConfig;
    private startServersPromise?;
    protected transport: InProcMCPTransport | null;
    private readonly hostStateHandle;
    private readonly hostStateFinalizerToken;
    private progressCallback?;
    private traceContextResolver?;
    private mcpToolCallInterceptor?;
    private fidesIfcEnabled?;
    private taskRegistry?;
    private transportPermissions;
    private mcp3pEnabled;
    private configFilter;
    private managedAllowedMcpServerLists?;
    private managedDeniedMcpServers?;
    private trustedDefaultServerNames;
    private elicitationHandler?;
    protected statusCallback?: ServerStatusCallback;
    protected logger: RunnerLoggerContract_3;
    protected onOAuthRequired?: McpHostOptions["onOAuthRequired"];
    private readonly cancelPendingOAuthRequests?;
    private readonly setupTelemetryCallback?;
    protected headersRefreshManager?: McpHeadersRefreshManager;
    protected settings?: McpHostSettingsContext;
    /**
     * Per-host MCP Apps opt-in flag, mirrored from the constructor option.
     * Used to thread the per-session capability into the {@link MCPTransport}
     * when one is lazily constructed on first tool listing/invocation, so the
     * transport preserves `_meta.ui` and fetches `ui://` resources without
     * relying solely on the global feature flag.
     */
    protected mcpAppsEnabled: boolean;
    private serverStateChangedCallback?;
    private serverStatusChangedCallback?;
    private listChangedCallback?;
    /** All snapshot and live-list lifecycle state, grouped by MCP server name. */
    private readonly serverToolStates;
    /** Optional disk cache; omitted for hosts whose deployment path owns tool listing elsewhere. */
    private readonly toolSnapshotCache?;
    /** Constructor-started disk load, awaited before an effective connected server consumes it. */
    private readonly toolSnapshotCacheLoadPromise?;
    /** Reusable loaded snapshots keyed by definition identity and kept current after live writes. */
    private persistedToolSnapshots?;
    /** In-flight tool-refresh promises; awaited by `awaitPendingToolsChanges` (#7432). */
    private pendingToolsChanges;
    private pendingServerStarts;
    /** Native-host-owned server names; registry entries for these are request-only session views. */
    private readonly nativeServerNames;
    /** Native servers intentionally stopped but still configured for a later restart. */
    private readonly stoppedNativeServerNames;
    /**
     * Server names registered via {@link registerExternalClient} (e.g. the IDE
     * bridge). The caller owns the client/transport lifecycle, so when the
     * enterprise managed policy later denies one of these it must be *unregistered*
     * (removed from this host's view) rather than stopped — stopping would close a
     * client/transport this host does not own.
     */
    private readonly externalServerNames;
    /**
     * External server names registered as trusted first-party bridges (the IDE
     * connection). Exempt from the enterprise managed allow/deny policy on both
     * registration and a later live tightening, mirroring the trusted-name set
     * used for built-in defaults, so an enterprise allowlist does not require
     * listing the first-party editor bridge and a deny does not tear it down.
     */
    private readonly trustedExternalServerNames;
    /**
     * Server names that were dynamically started as trusted first-party defaults
     * (via `startServer(..., trustedFirstPartyStart=true)`, e.g. the built-in
     * GitHub MCP server through configureGitHubMcp). Retained so a later live
     * managed-policy tightening keeps exempting them — the per-call
     * `trustedFirstPartyStart` flag is not part of the persisted config, so
     * without this snapshot enforceManagedMcpPolicy would re-evaluate a running
     * first-party default without its exemption and remove it.
     */
    private readonly trustedDynamicStartServerNames;
    /**
     * Configs of servers removed by a mid-session enterprise managed-policy
     * tightening ({@link setManagedMcpPolicy}), retained so that if the policy
     * later relaxes (e.g. the SDK hourly refresh) the server can be restarted.
     * Without this, deleting the entry from {@link config} — whose `mcpServers`
     * map may be shared with the owning session — would make a temporary
     * restriction permanent. External registrations are NOT retained here (their
     * lifecycle is owned by the caller, which re-registers them).
     */
    private readonly policyRemovedConfigs;
    /**
     * Monotonic generation for {@link setManagedMcpPolicy}. Callers fire policy
     * updates without awaiting, so overlapping updates are serialized on
     * {@link managedMcpPolicyUpdateChain} and each enforcement pass bails if a
     * newer generation has superseded it — preventing a stale (e.g. more
     * restrictive) plan from acting after a newer relaxed one.
     */
    private managedMcpPolicyGeneration;
    /** Serializes overlapping managed-policy enforcement passes. */
    private managedMcpPolicyUpdateChain;
    private readonly nativeEffectiveConfigs;
    private readonly oauthProviders;
    private readonly oauthChallengeParams;
    private readonly oauthAbortControllers;
    private readonly authRetryPendingCounts;
    private readonly authRetryLastAttempts;
    private readonly serverConfigurationVersions;
    private readonly serverConfigurationChains;
    private readonly serverStopVersions;
    private readonly getWorkingDir?;
    private readonly startupConcurrency;
    private disposed;
    /**
     * Single-flight chain for `applySandboxConfig` so concurrent sandbox toggles
     * serialize on a single restart pipeline instead of interleaving stops/starts.
     */
    private sandboxApplyChain;
    /**
     * Resolves once the current sandbox remote-proxy URL has been folded (the
     * stored keychain/env password reference resolved to the secret) onto
     * {@link runtimeConfigContext} and this session's OAuth proxy has been set.
     * Deferred from the constructor because the resolution is async; awaited by
     * {@link startServers} so every connect sees the resolved proxy. Refreshed
     * by {@link applySandboxConfig} on each sandbox change.
     */
    private sandboxRemoteProxyReady;
    /**
     * Why the sandbox denies remote MCP egress, or `undefined` when allowed. Set
     * by {@link resolveSandboxRemoteProxy}, enforced by
     * {@link assertRemoteMcpEgressAllowed}.
     */
    private sandboxRemoteEgressDeniedReason?;
    /**
     * Effective sandbox config backing {@link assertRemoteMcpEgressAllowed}'s
     * per-endpoint classification. Kept alongside the session-wide decision so a
     * policy change is picked up by the same resolution.
     */
    private sandboxConfigForEgress?;
    /**
     * Monotonic id for the latest {@link resolveSandboxRemoteProxy} call. The
     * async lookup commits only when it is still the latest and the host has not
     * been disposed, so an older constructor lookup cannot clobber a newer
     * {@link applySandboxConfig} value, and a lookup finishing after
     * {@link dispose} cannot resurrect the cleared per-session proxy entry.
     */
    private sandboxProxyResolveGeneration;
    private throwIfIntentionallyStopped;
    private emitListChanged;
    private beginServerConfigurationOperation;
    private currentServerStopVersion;
    private stopServerOperations;
    private beginServerStop;
    private runCancellableOAuthOperation;
    private isCurrentServerOperation;
    private publishConnectedNativeServer;
    private withServerConfigurationLock;
    waitForServerConfigurationIdle(serverName: string): Promise<void>;
    /** Per-server custom agent info that is needed for accessing custom agent information
     *  throughout the lifetime of the MCP host w/o having to pass it around explicitly.
     *  It allows for either a shared host (CLI, legacy) or a host per-custom agent (new) flow.
     */
    protected serverCustomAgents: Map<string, CustomAgentInfo>;
    private readonly runtimeConfigContext;
    constructor(options: McpHostOptions);
    private handleNativeHostEvent;
    private configureAndConnectServer;
    private configureAndConnectServerUnlocked;
    /**
     * Grades a reconnect helper that already resolved. The helpers resolve
     * without throwing even when a supersede check short-circuited them before
     * a session existed, so their resolution alone must never be read as
     * success.
     */
    private outcomeFromLiveSession;
    /**
     * Triages a connect attempt that finished with no live session. Every such
     * path we know of is the caller asking us to stop: an intentional
     * disconnect or a disable landed mid-attempt. Those are cancellations -
     * warning about them would blame the user for their own action - and the
     * canceller owns the terminal status.
     *
     * The `failed` branch is NOT dead code and must not be removed: it is the
     * safety net for any path that reaches here without one of those two
     * markers set, including one we have not found yet. Without it such a
     * server sits in `starting` forever and hangs the env-loading gate.
     */
    private classifyDisconnected;
    /**
     * Builds the one-shot terminal-status reporter for a single connect attempt.
     *
     * Every `starting` must be answered by exactly one terminal status: emit
     * none and consumers that wait for MCP startup to settle (the CLI
     * env-loading gate) wait forever; emit two and their bookkeeping is wrong.
     * Shared by the batch and single-server paths so a future change to the
     * classification cannot fix one and leave the other stranded.
     *
     * `resolveStatusCallback` is called per report rather than captured so the
     * host's current callback is used, matching the pre-extraction behavior.
     */
    private createFailureReporter;
    private prepareNativeRuntimeConfig;
    private configureAndConnectWithAuthRecovery;
    private connectWithOAuthInBackground;
    /**
     * Sets a callback that is invoked whenever an OIDC token is added to the
     * internal token cache (e.g., during prefetch or on-demand resolution).
     * This allows external consumers (like MCPServer) to react to new tokens
     * for cross-process secret filtering.
     */
    setOnTokenAdded(callback: (value: string) => void): void;
    /** Refreshes tools after a server notification or a deferred initial connection. */
    private handleToolsRefresh;
    /** Register a callback invoked when server state changes (enable, disable, tools changed). */
    setOnServerStateChanged(callback: () => void): void;
    /**
     * Wait for any in-flight `tools/list_changed` notifications to finish processing,
     * so the agent loop sees newly advertised tools within the same turn (#7432).
     */
    awaitPendingToolsChanges(): Promise<void>;
    /**
     * Wait for any in-flight background connection attempts (including deferred
     * OAuth reconnects) to settle, then for their resulting tools-changed
     * notifications to finish processing. Used by tests to observe the terminal
     * state of a server started in the background.
     */
    awaitPendingConnections(): Promise<void>;
    /** Register a callback invoked when an individual server's connection status changes. */
    setOnServerStatusChanged(callback: (serverName: string, status: ServerConnectionStatus) => void): void;
    /**
     * Register a callback invoked when a server announces at runtime that its
     * tool, resource, or prompt list changed. Lets consumers refresh their view
     * of a server's tools, resources, or prompts immediately instead of polling.
     */
    setOnListChanged(callback: (serverName: string, kind: McpListChangedKind) => void): void;
    /**
     * Returns the latest successfully installed unfiltered tool snapshot.
     * `undefined` means no successful list has completed; an empty array is a ready snapshot.
     */
    getServerToolSnapshot(serverName: string): readonly Readonly<LenientToolInfo>[] | undefined;
    private getOrCreateServerToolState;
    private isToolOperationStale;
    private shouldRetryStaleToolListing;
    private enqueueLiveOperation;
    private detachLiveOperations;
    private isToolSnapshotCacheEligible;
    private createToolSnapshotCacheIdentity;
    private createToolProvider;
    private serverSupportsTaskTools;
    private installToolSnapshot;
    private installPersistedToolSnapshot;
    private loadPersistedToolSnapshots;
    private restorePersistedToolSnapshots;
    private persistServerToolSnapshot;
    private startPersistedToolSnapshotRefresh;
    private refreshServerTools;
    private refreshServerToolsNow;
    /**
     * Performs a live server tool listing and atomically installs the raw snapshot.
     * Calls for one server are serialized so event-driven consumers cannot create a list loop.
     */
    listTools(serverName: string, timeoutMs?: number): Promise<readonly Readonly<LenientToolInfo>[]>;
    private listToolsAndInstall;
    private clearActiveServerToolSnapshot;
    /**
     * Forward a session event to MCP servers that opted in via `events` config.
     * Currently scoped to built-in servers only.
     */
    sendNotification(eventType: string): void;
    private notifyServerStatusChanged;
    startServers(statusCallback?: ServerStatusCallback): Promise<StartServersResult>;
    /**
     * Extension point for subclasses to inject default servers into the config.
     * This method is called during startServers() before processing the servers.
     * Subclasses should override this method and mutate the config parameter in place
     * to add custom server configurations.
     */
    protected injectDefaultServers(_config: MCPServersConfig): Promise<void>;
    /**
     * Computes the removal plan for the enterprise-managed MCP allow/deny lists
     * (managed settings only) via the Rust `managed_mcp_policy` engine. Returns an
     * empty plan when no allowlist is in force and nothing is denied. The
     * allowlists are passed as an array-of-allowlists (allowlist-intersection: a
     * server must be admitted by every source's list); the environment is
     * forwarded so `${VAR}` references in both the policy entries and the server's
     * `serverUrl` / `serverCommand` resolve before matching, consistent with
     * `.mcp.json` resolution. The native call is async so this per-server ×
     * per-matcher work never blocks the Node.js main thread.
     */
    private managedMcpPolicyPlan;
    /**
     * Whether a single server is blocked by the enterprise-managed MCP allow/deny
     * policy. Used on the dynamic single-server start path so a server added or
     * reconnected mid-session is governed identically to the bulk startup path.
     * Returns the policy log message when blocked, otherwise `undefined`.
     *
     * The exemption is granted ONLY when `trustedFirstPartyStart` is set — an
     * internal, caller-provenance flag that trusted runtime code passes when it
     * (re)starts a genuine first-party default (e.g. the built-in GitHub MCP
     * server via `configureGitHubMcp()`). It is NOT derived from any
     * caller-settable server config field (`source` / `isDefaultServer`), so a
     * public `startServer` cannot forge default status to bypass the policy.
     */
    private managedMcpPolicyBlockReason;
    /**
     * Whether a server is blocked by the *current* enterprise-managed policy on
     * the bulk startup path, evaluated against the full set of trusted first-party
     * names (built-in defaults, IDE bridge, and dynamically-started defaults). Used
     * to re-check each server immediately before its bulk connection, closing the
     * window in which a concurrent policy tightening lands after the batch config
     * was snapshotted but before the connection is established. Returns the policy
     * log message when blocked, otherwise `undefined`.
     */
    private managedMcpPolicyBlockReasonForBulk;
    /**
     * Whether `serverName` carries trusted first-party provenance from any source:
     * a dynamic trusted start (`trustedDynamicStartServerNames`), a bulk-loaded
     * built-in default (`trustedDefaultServerNames`), or a trusted external bridge
     * (`trustedExternalServerNames`). Consulted by config-free start-/restart-by-name
     * so a stopped built-in keeps its managed-policy exemption; a caller-supplied
     * replacement config must not inherit it (enforced by the `config === undefined`
     * guard at the call sites).
     */
    private isRegisteredServerTrustedFirstParty;
    /**
     * Update the enterprise-managed MCP allow/deny policy on a live host. Called
     * when managed settings change mid-session (e.g. the SDK hourly refresh, or
     * the CLI app-level flow) so the current policy is enforced immediately.
     *
     * Beyond swapping the policy arrays (which governs later dynamic
     * `startServer` calls), this re-evaluates already-loaded servers against the
     * new policy so a tightening takes effect at once rather than leaving a
     * newly-denied server connected, listed, and callable until an unrelated full
     * reload, and a relaxation restarts servers that a previous tightening
     * removed. First-party defaults stay exempt (enforced in the Rust engine via
     * the trusted-name set).
     *
     * Removed non-external configs are retained in {@link policyRemovedConfigs}
     * (not permanently deleted) so a later relax can restart them — the
     * {@link config} `mcpServers` map may be shared with the owning session.
     * External registrations (e.g. the IDE bridge) are *unregistered* rather than
     * stopped, since this host does not own their client/transport lifecycle.
     */
    setManagedMcpPolicy(allowedLists: ManagedMcpServerMatcher[][] | undefined, denied: ManagedMcpServerMatcher[] | undefined): Promise<void>;
    private enforceManagedMcpPolicy;
    private processServersWithExtensions;
    /**
     * Streamable HTTP transports terminate their server session with an explicit
     * DELETE before closing, per the MCP spec session-management guidance
     * ("Clients that no longer need a particular session SHOULD send an HTTP
     * DELETE to explicitly terminate the session"). Only the IDE connection still
     * uses an SDK `StreamableHTTPClientTransport` here — direct-Rust HTTP sessions
     * terminate inside the Rust client on close — so detect the capability
     * structurally rather than importing the SDK transport type.
     */
    private terminateTransportSession;
    stopServers(): Promise<void>;
    dispose(): Promise<void>;
    /**
     * Gets all available tools from the MCP servers. Starts the servers with @see startServers if they have not already been started.
     * the tools returned should not be used after @see stopServers has been called.
     *
     * @param settings - The narrow runtime context used by MCP transport.
     * @param logger - The logger instance.
     * @param permissions - Permissions configuration for tool access.
     * @returns A promise that resolves to an array of tools.
     */
    getTools(settings: McpHostSettingsContext, logger: RunnerLoggerContract_3, permissions: PermissionsConfig): Promise<Tool[]>;
    private refreshTransportCallbacks;
    private createTransportCallbacks;
    private resolveTransportMetadata;
    private reconnectNativeTransport;
    private startNativeTask;
    private updateNativeTask;
    /**
     * Gets the current MCP configuration.
     */
    getConfig(): MCPServersConfig;
    /**
     * Gets all connected MCP clients.
     * @returns A record of server names to their client instances
     */
    getClients(): Record<string, NativeMcpSession>;
    /**
     * Gets all servers that failed to connect.
     * @returns A record of server names to their failure information
     */
    getFailedServers(): Record<string, ServerFailureInfo>;
    /**
     * Gets all servers that require user-initiated authentication.
     * @returns A record of server names to their needs-auth information
     */
    getNeedsAuthServers(): Record<string, {
        timestamp: number;
    }>;
    /**
     * Gets the connection status of a server.
     * @param serverName - Name of the server
     * @returns The server's connection status
     */
    getServerStatus(serverName: string): ServerConnectionStatus;
    /**
     * Gets servers with pending connections.
     * @returns A record of server names to their pending connection promises
     */
    getPendingConnections(): Record<string, Promise<void>>;
    retryAuthRequiredServers(cooldownMs?: number): Promise<string[]>;
    retryAuthRequiredServer(serverName: string, cooldownMs?: number): Promise<boolean>;
    private retryAuthRequiredServersInternal;
    /**
     * Start a single MCP server, either with an explicitly supplied
     * configuration or, when `config` is omitted, by reusing the server's
     * previously-registered configuration (config-free start-by-name).
     * @param serverName - Unique name for the server
     * @param config - Server configuration. Omit to start an already-registered
     *   server by name, reusing its previously-registered configuration
     *   (config-free start-by-name); throws if no configuration is registered.
     * @param forceReauth - Optional flag to force re-authentication
     * @param customAgent - Optional custom agent information for OIDC token cache key derivation
     * @param trustedFirstPartyStart - When `true`, marks this start as a trusted
     *   first-party start (e.g. built-in servers), exempting it from managed
     *   policy checks. A config-free start-by-name preserves any trust
     *   previously established for the server; supplying a replacement `config`
     *   does not inherit that trust unless this flag is set.
     * @returns Promise that resolves when server is started
     */
    startServer(serverName: string, config?: MCPServerConfig, forceReauth?: boolean, customAgent?: CustomAgentInfo, trustedFirstPartyStart?: boolean): Promise<void>;
    /**
     * Whether `serverName` is currently connected (or connecting) with a
     * configuration matching `config`, using the same filter-aware native
     * planning `startServer` uses to decide an "already active" no-op. Lets a
     * caller reconcile a running server against a desired config without a
     * false-positive restart from post-filter differences. Returns `false` when
     * the server is not running/pending or the effective config differs.
     */
    isServerCurrentForConfig(serverName: string, config: MCPServerConfig): boolean;
    /**
     * Whether `serverName` is currently registered as an external client (e.g.
     * the IDE bridge). External transports are owned by the caller and must be
     * unregistered, never stopped/restarted by this host, so lifecycle
     * reconciliation must consult this before acting on a running server.
     */
    isExternalServer(serverName: string): boolean;
    private isServerActiveForConfig;
    private validateServerConfig;
    private applyConfigFilterToServer;
    /**
     * Forcibly revoke a server's access from this host when a graceful
     * {@link stopServer} failed (e.g. the native transport threw during close).
     * Best-effort and synchronous: removes the registry client (so tool discovery
     * and calls can no longer resolve it), its transport and config, and native
     * bookkeeping, and marks it intentionally stopped to suppress auto-reconnect.
     * Used to fail closed when tightening the enterprise managed policy so a
     * newly-denied server can never remain callable.
     */
    private quarantineServerAccess;
    private startServerOnce;
    private emitSetupTelemetry;
    /**
     * Stop a single MCP server
     * @param serverName - Name of the server to stop
     * @returns Promise that resolves when server is stopped
     */
    stopServer(serverName: string): Promise<void>;
    private stopServerAfterPreparation;
    /**
     * Restart a server, optionally with a replacement configuration.
     * @param serverName - Name of the server to restart
     * @param config - Optional replacement server configuration. When omitted, the
     *   server is restarted using its already-registered configuration (config-free
     *   restart-by-name). Throws if the server has no registered configuration.
     * @param forceReauth - Optional flag to force re-authentication
     * @param customAgent - Optional custom agent information
     * @returns Promise that resolves when server is restarted
     */
    restartServer(serverName: string, config?: MCPServerConfig, forceReauth?: boolean, customAgent?: CustomAgentInfo, trustedFirstPartyStart?: boolean): Promise<void>;
    /**
     * Replace or remove one server configuration without recreating this host.
     *
     * Runtime-only state belonging to other servers and host-level options remain
     * untouched. A disabled server stays disabled while its stored configuration is
     * updated for a later enable.
     */
    replaceServerConfig(serverName: string, config: MCPServerConfig | undefined, options?: {
        trustedFirstParty?: boolean;
    }): Promise<boolean>;
    private clearServerRuntimeRegistration;
    private removeStoredServerState;
    private setServerTrustProvenance;
    private publishServerConfigReplacement;
    /**
     * Reconnect a remote (HTTP/SSE) MCP server using a caller-supplied OAuth
     * provider — typically just after a proactive OAuth login so the fresh
     * tokens are used immediately, without re-entering the auth path.
     *
     * Contrast with `restartServer`, which goes through the processor and
     * requires `onOAuthRequired` to be wired on the host to obtain a
     * provider. This method takes the provider as a parameter, skipping
     * that indirection.
     */
    reconnectRemoteServerWithProvider(serverName: string, config: MCPRemoteServerConfig, authProvider: HostDelegatingOAuthClientProvider): Promise<void>;
    private reconnectRemoteServerWithProviderUnlocked;
    reconnectServerWithOAuthReplacement(serverName: string, request: HostDelegatingOAuthRequest): Promise<void>;
    /**
     * Restart a server reusing existing cached OIDC tokens.
     * Used for disconnect recovery when the transport is closed but auth is still valid.
     */
    reconnectServer(serverName: string): Promise<void>;
    /**
     * Evict cached OIDC tokens and restart a server to pick up fresh credentials.
     * Used for auth-retry reconnection when a tool call receives a 401.
     */
    reconnectServerWithFreshOIDCAuth(serverName: string): Promise<void>;
    /** Reconnect a remote OAuth server after a mid-session 401. */
    reconnectServerWithFreshOAuth(serverName: string, forceReauth?: boolean, onPhase?: (phase: "interactive-auth" | "transport-connect") => void): Promise<void>;
    private getHostDelegatedOAuthProvider;
    /**
     * Reconnect a server with fresh auth after a mid-session 401, routing by the
     * server's configured auth model. Only remote servers WITHOUT an OIDC config
     * take the host-delegated OAuth path; OIDC servers (local or remote) and
     * local servers fall back to the OIDC restart-with-evicted-tokens path,
     * preserving pre-#1761 behaviour.
     */
    reconnectServerWithFreshAuth(serverName: string, forceReauth?: boolean): Promise<void>;
    /**
     * This session's remote (HTTP/SSE) MCP egress decision. Awaits the deferred
     * resolution so a probe issued before {@link startServers} still sees it —
     * e.g. the tokenless OAuth connection test, which must reach a proxy-only
     * endpoint to surface its 401.
     */
    getResolvedSandboxRemoteMcpEgress(): Promise<SandboxRemoteMcpEgress>;
    /**
     * Resolve this session's remote-MCP egress from `config` (see the Rust
     * `sandboxRemoteMcpEgress` policy), store the proxy on
     * {@link runtimeConfigContext}, and route this session's OAuth HTTP clients
     * through it. Also records any denial for
     * {@link assertRemoteMcpEgressAllowed}. Async because resolving the stored
     * keychain/environment password reference is.
     *
     * The proxy password lives in the sandbox-proxy store, not the MCP one:
     * passing `runtimeConfigContext.secretConfigDir` (the `mcp-secrets` dir)
     * silently drops a persisted `${secret:…}` password whenever the OS keychain
     * is unavailable and the file fallback is consulted.
     */
    private resolveSandboxRemoteProxy;
    /**
     * Refuse a remote (HTTP/SSE) MCP connection when the sandbox denies outbound
     * egress. Remote servers are connected in-process, so mxc never sees them —
     * without this the connection would just go direct, escaping the policy.
     */
    private assertRemoteMcpEgressAllowed;
    /**
     * Atomically update the sandbox policy and restart currently-running MCP
     * servers so they pick up the new policy.
     *
     * Local (stdio) servers bake the sandbox into the spawn at process creation
     * time, so a policy change is only observable after a restart — these are
     * enumerated by {@link nativeRuntime.mcpHostSandboxRestartTargets}. Remote
     * (HTTP/SSE) servers sample the sandbox proxy only when they connect, so they
     * are restarted here whenever the effective remote-MCP proxy URL changes.
     *
     * Concurrent calls are serialized through {@link sandboxApplyChain} so a
     * burst of sandbox toggles doesn't interleave stops and starts on the same
     * server.
     */
    applySandboxConfig(config?: SandboxConfig_2): Promise<void>;
    /**
     * Check if a server is currently running
     * @param serverName - Name of the server to check
     * @returns True if server is running
     */
    isServerRunning(serverName: string): boolean;
    /**
     * Register a pre-connected MCP client (e.g., an IDE connection managed by another host).
     * The caller retains ownership of the client/transport lifecycle.
     *
     * The enterprise-managed allow/deny policy is enforced before the client is
     * exposed, so a denied external server is never listed or callable. Trusted
     * first-party bridges (the IDE connection) pass `trustedFirstPartyStart` to be
     * exempt, mirroring the trusted dynamic-start path. Returns `false` when the
     * registration was blocked by policy (nothing was registered).
     */
    registerExternalClient(serverName: string, client: NativeMcpSession, transport: Transport, config: MCPServerConfig, trustedFirstPartyStart?: boolean): Promise<boolean>;
    /**
     * Unregister a previously registered external client.
     * Does NOT close the client/transport — the caller manages that.
     */
    unregisterExternalClient(serverName: string): Promise<void>;
    /**
     * Check if a server is disabled
     * @param serverName - Name of the server to check
     * @returns True if server is disabled
     */
    isServerDisabled(serverName: string): boolean;
    /**
     * Check if a server was filtered out by a config filter (e.g. allowlist enforcement).
     * Filtered servers should be hidden from the UI (e.g. /mcp show).
     * @param serverName - Name of the server to check
     * @returns True if server was filtered out
     */
    isServerFiltered(serverName: string): boolean;
    /**
     * Disable a server at runtime.
     * Callers are responsible for persisting this change if cross-session persistence is desired.
     * @param serverName - Name of the server to disable
     * @returns Promise that resolves when server is disabled
     */
    disableServer(serverName: string): Promise<void>;
    /**
     * Enable a previously disabled server at runtime
     * @param serverName - Name of the server to enable
     * @returns Promise that resolves when server is enabled
     */
    enableServer(serverName: string): Promise<void>;
    /**
     * Extension point for subclasses to start a built in server that is not listed in
     * the MCP Config.
     * @param serverName - Name of the server to enable
     * @returns Promise that resolves when server handling is complete
     */
    protected startBuiltInServer(_serverName: string): Promise<void>;
    /**
     * Check if third-party MCP servers are enabled.
     * When false, only servers with isDefaultServer=true are allowed.
     */
    isMcp3pEnabled(): boolean;
    /**
     * Get the configuration for a running server
     * @param serverName - Name of the server
     * @returns Server configuration or undefined if not found
     */
    getServerConfig(serverName: string): MCPServerConfig | undefined;
    /**
     * Get the effective (processed) configuration for a running server.
     * This returns the config after processing (env resolution, python->pipx conversion, etc.)
     * Use this for operations that need the actual runtime config (e.g., proxy transport creation).
     * @param serverName - Name of the server
     * @returns Processed server configuration or undefined if server is not running
     */
    getEffectiveServerConfig(serverName: string): MCPServerConfig | undefined;
    /**
     * Set the callback to be invoked when an MCP tool reports progress.
     * @param callback - The callback to invoke with (toolCallId, progressMessage)
     */
    setProgressCallback(callback: ToolProgressCallback | undefined): void;
    /**
     * Set the resolver for OTel trace context on MCP tool calls.
     * When set, `traceparent`/`tracestate` will be injected into `params._meta`.
     */
    setTraceContextResolver(resolver: TraceContextResolver | undefined): void;
    /**
     * Set the interceptor invoked before MCP tool calls are sent.
     */
    setMcpToolCallInterceptor(interceptor: McpToolCallInterceptor | undefined): void;
    /**
     * Override the FIDES IFC enabled signal used to gate `_meta` surfacing on
     * tool results. Callers should source the value from
     * `IFeatureFlagService.isFidesIfcEnabled` so ExP overrides apply.
     */
    setFidesIfcEnabled(enabled: boolean | undefined): void;
    attachIfcSession(sessionId: string): void;
    /**
     * Set the task registry for non-blocking MCP task execution.
     * When set, tools with `taskSupport: "required"` register as background tasks.
     */
    setTaskRegistry(registry: TaskRegistry | undefined): void;
    /**
     * Gets all server instructions from connected MCP servers.
     * Server instructions are provided by MCP servers during initialization
     * and describe how to use the server and its features.
     * @returns A record mapping server names to their instructions
     */
    getServerInstructions(): Record<string, string>;
    /**
     * Returns the current server instruction mode (`allowlist` or `all`).
     */
    getServerInstructionMode(): MCPServerInstructionMode;
    /**
     * Sets whether instructions from all connected servers are included in the
     * system prompt. Enabling this promotes previously deferred (non-allowlisted)
     * server instructions at runtime.
     */
    setAllowAllServerInstructions(allowAllServerInstructions: boolean): void;
    /**
     * Returns the count of connected servers whose instructions are not in the
     * allowlist (i.e. currently deferred under allowlist mode).
     */
    getServerInstructionsNotInAllowlistCount(): number;
    /**
     * Register a callback to be invoked when a server sends a notifications/elicitation/complete notification.
     * @param callback - The callback to invoke with the elicitationId
     */
    setElicitationCompleteCallback(callback: (elicitationId: string) => void): void;
    /**
     * Register a callback to be invoked when a built-in server sends a user.abort notification.
     */
    setAbortCallback(callback: () => void): void;
    /**
     * Set the current abort signal so in-flight MCP tool calls can be cancelled.
     * Also stores the controller so user.abort notifications can trigger abort directly.
     */
    setAbortSignal(signal?: AbortSignal, controller?: AbortController): void;
    private abortCallback?;
    private _abortController?;
    /**
     * Handle a server->client notification forwarded from a built-in server (via
     * the registry's bridge notification router). Drives the `user.abort` hook:
     * when a built-in server that opted in via `notifications: ["user.abort"]`
     * sends `notifications/copilot` with `type: "user.abort"`, invoke the abort
     * callback first so the session can drain queued work before abort signal
     * listeners run, then trip the abort controller.
     */
    private handleBuiltinServerNotification;
    /**
     * Gets server instructions captured for embedding-based retrieval.
     * These are deferred from the system prompt and indexed for JIT injection.
     */
    getDeferredServerInstructions(): Record<string, string>;
    /**
     * Gets tool summaries for servers with deferred instructions.
     * Used to enrich embedding text for better retrieval relevance.
     */
    getDeferredServerToolSummaries(): Promise<Record<string, Array<{
        name: string;
        description: string;
    }>>>;
    /**
     * Get information about a connected IDE, if any.
     * Subclasses that support IDE connections should override this method.
     */
    getConnectedIdeInfo(): {
        ideName: string;
        workspaceFolder: string;
    } | undefined;
}

/**
 * Cache that maintains a mapping of agent ID to MCP host.
 * The root agent uses an empty string as its ID.
 */
declare class McpHostCache {
    private hosts;
    private pendingHosts;
    private logger;
    constructor(logger: RunnerLoggerContract_2);
    /**
     * Get or create an MCP host for the given agent ID.
     * Returns undefined if mcpServers is empty or undefined.
     */
    getOrCreateHost(agentId: string, mcpServers: Record<string, MCPServerConfig> | undefined, hostOptions?: Omit<McpHostOptions, "logger" | "mcpConfig">): Promise<McpHost | undefined>;
    /**
     * Get an existing host for the given agent ID.
     */
    getHost(agentId: string): McpHost | undefined;
    /**
     * Stop and remove all MCP hosts.
     */
    cleanup(): Promise<void>;
    /**
     * Propagate a sandbox policy change to every cached subagent MCP host so
     * already-running stdio servers pick up the new policy.
     *
     * Each host's `applySandboxConfig` is single-flight, so this is safe to
     * call concurrently with itself or with a sandbox toggle that races
     * subagent host creation.
     */
    applySandboxConfig(config?: SandboxConfig_3): Promise<void>;
    setAllowAllServerInstructions(allowAllServerInstructions: boolean): void;
    /**
     * Propagate an enterprise-managed MCP allow/deny policy change to every cached
     * subagent host so the current policy is enforced immediately: later dynamic
     * `startServer` calls are governed, and any already-running server that is now
     * denied or no longer allowed is stopped and removed (mirrors
     * {@link applySandboxConfig} / {@link setAllowAllServerInstructions}).
     */
    setManagedMcpPolicy(allowedLists: ManagedMcpServerMatcher[][] | undefined, denied: ManagedMcpServerMatcher[] | undefined): Promise<void>;
    /**
     * Get the number of hosts in the cache.
     */
    size(): number;
}

/**
 * Owns creating, reconciling, and lazily (re)loading a session's local
 * `McpHost`, together with the concurrency primitives that guard access to
 * that host: the single in-flight {@link McpLoadOperation} (the "strict
 * barrier" that lets turns/tool-listing/tool-search know whether MCP has
 * finished its current load), the serialization mutex that orders
 * `reloadMcpServers()` / `dispose()` / lazy-startup against each other, and the
 * disposed flag that short-circuits new work once teardown has begun.
 *
 * The concurrency state machine (mutex, in-flight operation, disposed signal)
 * is host-agnostic and easy to reason about in isolation; the host-specific
 * logic (lazy first-load, per-selected-agent server reconciliation on agent
 * switch, and whether a (re)load is needed at all) is layered on top. Callers
 * (see `Session`/`LocalSession` in `session.ts`) reach the host only through
 * this class so it stays the single owner of both.
 *
 * The `reloadMcpServers()`/`performMcpReload()` bodies stay shared behavior on
 * the base `Session` class, but the plumbing that runs a reload under a stable
 * load operation lives here (see {@link forceStartLoadingWhenStable}).
 */
declare class McpHostLifecycle {
    private readonly context;
    private readonly nativeSessionId;
    private operation?;
    private disposed;
    private mutexTail;
    private readonly disposedSignal;
    /** In-flight per-server ensures, so concurrent callers for one server share one outcome. */
    private readonly pendingServerEnsures;
    /**
     * The in-flight shared aggregate load for the MCP Apps ensure path, so
     * concurrent ensures for *different* servers share one bulk attempt and its
     * cold-load outcome — the convergence loop would otherwise let each joined
     * caller self-start a retry once the shared load fails. Cleared on settle so
     * a later distinct call can retry.
     */
    private pendingAggregateEnsureLoad;
    /**
     * Cold-load outcome recorded by the most recent {@link ensureLoaded}, so the
     * shared aggregate load can read it back when the load ran through the
     * published `ensureMcpLoaded()` seam (which returns `void`).
     */
    private lastEnsureLoadedOutcome;
    /**
     * Session-level server names we own per host generation, seeded at
     * {@link assignAndStartHost} from the config snapshot the host was built
     * with (plus Case-C targeted starts and selected-agent slots transferred to
     * session config). Keyed by the host object, so ownership is
     * generation-scoped and cleared automatically on host replacement/GC;
     * reconciliation only touches owned names, never external ones.
     */
    private readonly ownedByHost;
    /** Names of MCP servers currently running because the selected custom agent declared them (not session-level). */
    readonly selectedAgentMcpServerNames: Set<string>;
    /** The selected agent's MCP server configs as of the last reconciliation, used to detect config changes. */
    lastInitializedAgentMcpServers: Record<string, MCPServerConfig> | undefined;
    /** The session's local MCP host, once one has been created. Owned here; mutated only via {@link setMcpHost}. */
    private _mcpHost?;
    constructor(context: McpHostLifecycleContext, nativeSessionId: string);
    /** The session's local MCP host, if one has been created. */
    getMcpHost(): McpHost | undefined;
    /**
     * Assign the session's local MCP host. Clearing to `undefined` (a
     * failed/abandoned `startServers()`, a reload's dispose-before-replace, or
     * session teardown) also clears the native MCP server snapshot, so no
     * teardown path can leave `session.mcp.list()` reporting a host that no
     * longer exists.
     */
    setMcpHost(host: McpHost | undefined): void;
    /** Session-level MCP server configs, read from Rust-owned session state. */
    private getMcpServers;
    /** Session-level MCP servers the user has disabled, read from Rust-owned session state. */
    private getDisabledMcpServers;
    /** Mirror the live MCP host's serializable read/status snapshot into Rust-owned session state. */
    updateMcpServerSnapshot(host?: McpHost | undefined): void;
    private buildMcpHostSnapshot;
    private buildMcpServerSummaries;
    /** Mark the MCP lifecycle disposed. Idempotent; subsequent loads/throws are gated on this. */
    markDisposed(): void;
    /** Whether the MCP lifecycle has been torn down (see session `dispose()`). */
    isDisposed(): boolean;
    /** Throws if the MCP lifecycle has been torn down. Call at the top of (and after awaits inside) MCP-mutating operations. */
    throwIfDisposed(): void;
    /**
     * Resolves once the lifecycle is disposed. Never rejects. Lets an
     * otherwise-uninterruptible pre-host await be raced against disposal so
     * cancellation isn't stuck waiting out its full duration.
     */
    private waitForDisposal;
    /**
     * Acquire the lifecycle serialization mutex, returning a release function
     * the caller must invoke exactly once (typically in a `finally`). Serializes
     * host mutations (reload, dispose, lazy startup) against each other.
     */
    acquireLifecycleMutex(): Promise<() => void>;
    /**
     * Races `work` against disposal so an otherwise-uninterruptible await
     * (host connect handshake, pre-host policy/token resolution, etc.) can't
     * block cancellation for however long it takes. Returns
     * `{ disposed: true }` when disposal wins (the original promise's
     * eventual result, if any, is discarded).
     */
    raceWithDisposal<T>(work: Promise<T>): Promise<{
        disposed: true;
    } | {
        disposed: false;
        value: T;
    }>;
    /**
     * Run `work` under the MCP lifecycle mutex so no host load/reload/dispose can
     * interleave, racing it against disposal. For critical sections that must
     * observe a *stable* host across multiple awaits — e.g. refreshing the
     * subagent-inheritance tool snapshot and then constructing the child that
     * reads it; without the lock a reload could swap the host between the two.
     * Always releases the mutex before returning. Returns `{ cancelled: true }`
     * when disposal wins (`work` may still be running in the background; its
     * result is discarded); callers should then abandon `work`'s effects.
     */
    runWithStableHost<T>(work: () => Promise<T>): Promise<{
        cancelled: true;
    } | {
        cancelled: false;
        value: T;
    }>;
    /** The current in-flight MCP load operation, if any. */
    getCurrentLoadOperation(): McpLoadOperation | undefined;
    /** Whether an MCP load is currently in flight. */
    isLoading(): boolean;
    /** Wait for any in-flight MCP load to settle (no-op when nothing loads). */
    waitForLoadToSettle(): Promise<void>;
    /** Turn barrier: resolves once MCP settles, or once a turn is explicitly released via `allowTurnsToProceedWithoutMcp()`. */
    waitForLoadIfRequired(): Promise<boolean>;
    /** Release turns waiting on the in-flight load without waiting for MCP to settle. */
    allowTurnsToProceedWithoutMcp(): boolean;
    /**
     * Register `load` as the current MCP load operation, unless one is already
     * in flight (in which case this joins it instead — `load` is not invoked
     * again). `onSucceeded`/`onFailed` fire once `load` settles, but only if
     * this is still the current operation (a superseded operation's callbacks
     * are suppressed).
     */
    startLoading(load: () => Promise<void>, onSucceeded: () => void, onFailed: (error: unknown) => void): Promise<void>;
    /**
     * Like {@link startLoading}, but always registers a new operation as the
     * current one — even if one is already in flight — instead of joining it.
     * Used by callers (e.g. `reloadMcpServers()`) that must always perform
     * their own `load` and that have already serialized against any prior
     * operation themselves (e.g. via {@link acquireLifecycleMutex}).
     */
    forceStartLoading(load: () => Promise<void>, onSucceeded: () => void, onFailed: (error: unknown) => void): Promise<void>;
    /**
     * Like {@link forceStartLoading}, but acquires the lifecycle mutex and
     * stabilizes the barrier's current operation first, so callers needn't
     * serialize themselves. `load` owns the load slot for its duration; the sole
     * caller today is `reloadMcpServers()`.
     *
     * Waits out any in-flight load before taking the mutex (its promise resolves
     * a microtask after the mutex release, so grabbing the mutex first could let
     * the work swap the host while a waiter on that load is about to resume). If
     * a new load registers between the snapshot and the mutex, it is not
     * superseded: release and retry so registration and locking stay ordered.
     * Registers via {@link forceStartLoading} in the SAME synchronous
     * continuation as the final stability check, so no queued microtask can
     * register (and be silently superseded) in the gap.
     */
    forceStartLoadingWhenStable(load: () => Promise<void>, onSucceeded: () => void, onFailed: (error: unknown) => void): Promise<void>;
    /**
     * Cancel an in-flight load so a prompt teardown (session `dispose()`) doesn't
     * stall on a hung connect handshake: dispose the current host to abort its
     * connects, then wait for the load to settle (now quick). A no-op when
     * nothing is loading.
     */
    cancelInFlightLoad(): Promise<void>;
    /**
     * Ensures MCP is fully loaded and the selected agent's servers are
     * reconciled, looping until convergence. Always waits out any in-flight
     * load, ignoring the barrier's "allow turns to proceed without MCP"
     * release — use only for callers that need MCP tools to genuinely be
     * ready (e.g. subagent tool inheritance); the per-turn path should use
     * {@link ensureLoadedForTurn} instead.
     *
     * Never throws: a cold-load rejection is returned rather than raised, so
     * most callers can ignore the result. `assignAndStartHost` disposes+clears
     * the host on a bulk `startServers()` throw, so a returned error with an
     * absent host signals a hard host-initialization failure that the per-server
     * path ({@link ensureServerConnected}) may propagate.
     */
    ensureLoaded(): Promise<unknown>;
    /**
     * Coalesce concurrent MCP Apps ensures onto a single aggregate load + outcome.
     *
     * `runSeam` lets the caller supply the published `ensureMcpLoaded()` seam as
     * *the* aggregate load, so an external override still runs without a second
     * bulk start. The seam returns `void`, so the outcome is read back from
     * {@link lastEnsureLoadedOutcome}, which the default implementation records;
     * an override that never loads simply leaves it unset, matching the
     * pre-existing "no cold-load error" behaviour for such a consumer.
     */
    private sharedAggregateLoad;
    /**
     * Turn-aware sibling of {@link ensureLoaded}: respects the barrier's
     * "allow turns to proceed without MCP" release, returning `false`
     * immediately if released while a load is in flight (the load keeps
     * running in the background). Returns `true` once nothing is left to
     * load. Re-checking after a joined operation settles lets this trigger a
     * follow-up load for selected-agent servers the joined operation didn't
     * cover (e.g. a `reloadMcpServers()` that only touched session-level ones).
     */
    ensureLoadedForTurn(): Promise<boolean>;
    /**
     * Ensure a named MCP server is started/connected on demand for the MCP Apps
     * read/list/call paths, so a restored session connects the app's server
     * without waiting for a new turn (github/copilot-mcp-core#1996).
     *
     * Classification is host-authoritative: after the shared aggregate load, a
     * server the load attempted is registered on the host, so a redundant
     * targeted retry is never issued; a server the build did not include (Case C)
     * is started on demand. A running server whose session config changed is
     * reconciled first. Connect/restart failures are thrown (McpHost records
     * rather than rejects); an unknown/unconfigured server is a no-op so the
     * caller surfaces its own "not connected" error.
     */
    ensureServerConnected(serverName: string, runSeam?: () => Promise<void>): Promise<void>;
    private ensureServerConnectedOnce;
    /** Start a configured server under the mutex, claim ownership, reconcile drift, surface failure. */
    private startConfiguredServerUnderLock;
    private reconcileServerUnderLock;
    /**
     * Reconcile a session-level server we own against the current session config.
     * `updateOptions({ mcpServers })` mutates config synchronously without the
     * mutex, so a running server can be removed or replaced and later Apps calls
     * would otherwise keep using the stale endpoint. Ownership is scoped to the
     * current host generation (see {@link ownedByHost}), so selected-agent /
     * external servers are never touched. Removed => stop (then a bounded re-read
     * re-adds it if the config reappeared mid-stop); replaced => restart once with
     * the current config. Replacement is decided by the host's filter-aware
     * `isServerCurrentForConfig`, avoiding false positives from post-filter
     * config differences. A change during the corrective action is repaired by a
     * later call, not an unbounded loop. Must run under the lifecycle mutex.
     */
    private reconcileServerLocked;
    /**
     * `startServer()`/`restartServer()` resolve even when the handshake failed
     * (McpHost records the failure rather than rejecting), so a still-not-running
     * server after a (re)start is inspected here and the recorded cause thrown.
     * Needs-auth/filtered states record nothing and are left for the caller's
     * "not connected".
     */
    private throwIfServerFailedToStart;
    /**
     * Shared convergence loop backing {@link ensureLoaded} and
     * {@link ensureLoadedForTurn}. A self-started load is kicked off (not
     * awaited inline) so the next iteration picks it up from `this.operation`
     * and the caller's wait strategy can still release early; its result is
     * re-checked via `isLoadingNeeded()` rather than trusted, since the
     * selected agent can change mid-flight. A new load only self-starts when
     * the selected agent's servers changed since the last one we started, to
     * bound retries.
     */
    private runConvergenceLoop;
    private isLoadingNeeded;
    /**
     * Names claimed by session-level config. A selected-agent server must never
     * be dynamically started under such a name, regardless of whether the
     * session-level instance has connected, is still connecting, or failed — a
     * name is a single slot, so basing this on running-state too would let a
     * selected-agent server that started after a session-level failure get
     * misclassified as session-owned once it came up, silently dropping its
     * ownership. Read once per pass (one native read + full parse) and reused as
     * a membership set so the per-server overlap checks don't re-cross N-API.
     */
    private getSessionLevelServerNames;
    /**
     * Dispose `host` and, only if it is still the current host, clear the
     * reference — the "dispose before clearing, never clobber a newer host"
     * invariant every teardown path needs. `dispose()` closes native servers
     * whose status callbacks snapshot this host, so the clear must be last (the
     * `setMcpHost(undefined)` setter also resets the native snapshot). No-op for
     * an undefined host.
     *
     * Drains the outgoing host's connection-time SDK requests
     * ({@link McpHostLifecycleContext.cancelMcpConnectionRequests}) BEFORE
     * `dispose()`, which awaits pending connection chains that block on those
     * requests — without the drain a reload could hang on OAuth (no timeout) or
     * the 120s header-refresh timeout.
     */
    disposeHost(host: McpHost | undefined, logLabel?: string): Promise<void>;
    /**
     * Make `host` the live host and start its servers. On a `startServers()`
     * failure (partial connect included), dispose+clear via {@link disposeHost}
     * and re-throw. The single "become the live host" primitive shared by the
     * lazy-load and reload paths.
     */
    assignAndStartHost(host: McpHost, statusCallback?: Parameters<McpHost["startServers"]>[0]): Promise<Awaited<ReturnType<McpHost["startServers"]>>>;
    /**
     * Resolve the current host's model-facing tools for an in-flight turn,
     * enforcing two invariants a turn must NOT re-derive itself:
     *
     *  - **No host ⇒ no tools** (`{ kind: "no-host" }`): callers fall back to
     *    their inherited/empty set so a disposed host never leaves stale tools
     *    (whose transports are already closed) advertised to the model.
     *  - **Host swap OR reload during the fetch ⇒ `{ kind: "superseded" }`**:
     *    the caller keeps its existing snapshot. A host-identity recheck alone is
     *    insufficient — `reloadMcpServers()` registers its load operation (making
     *    {@link isLoading} true) BEFORE it disposes the old host,
     *    and `mcpHost` isn't cleared until that disposal finishes, so a retiring
     *    host can still pass `getMcpHost() === host`. Capturing the in-flight
     *    operation before the await and comparing it after (with the disposed
     *    flag) closes that window.
     *
     * The caller supplies `fetchTools` (it owns the turn-scoped settings and
     * permissions); the lifecycle owns only the presence/swap guarding.
     */
    withCurrentHostTools<T>(fetchTools: (host: McpHost) => Promise<T>): Promise<{
        kind: "tools";
        value: T;
    } | {
        kind: "no-host";
    } | {
        kind: "superseded";
    }>;
    private createAndStartHost;
    private reconcileSelectedAgentServers;
}

/**
 * The narrow set of session state and operations {@link McpHostLifecycle}
 * needs to create/reconcile a host, expressed as accessors rather than raw
 * field access. This exists because TypeScript's `protected` is enforced by
 * class hierarchy, not by module: an unrelated class holding a reference to
 * `LocalSession` cannot read/write its `protected` fields directly, even from
 * the same file. The accessors preserve that encapsulation while still letting
 * this class own the host-lifecycle logic.
 *
 * State the lifecycle genuinely *owns* — the `McpHost` itself, the running
 * selected-agent server names, the last-reconciled snapshot, and the native MCP
 * server snapshot — lives on {@link McpHostLifecycle} directly, so it is not
 * part of this context; only session behavior the lifecycle must reach back
 * into is.
 */
declare interface McpHostLifecycleContext {
    /**
     * Settle the outgoing host's connection-time SDK requests (MCP OAuth +
     * dynamic headers refresh) WITHOUT closing the request store, so
     * `McpHost.dispose()` — which awaits pending connection chains that block on
     * these requests — can tear down promptly. Nonterminal, so a replacement
     * host can still issue them.
     */
    cancelMcpConnectionRequests(): void;
    /** The selected custom agent's configured MCP servers, or `{}` if none. */
    getSelectedAgentMcpServers(): Record<string, MCPServerConfig>;
    /**
     * The live session MCP config. The native scalar the lifecycle otherwise
     * reads is produced by `serializeMcpServersForNative()`, which drops an
     * in-memory server's `serverInstance` (a JS object reference that cannot
     * round-trip through JSON). Per-server decisions that compare configs or
     * hand one to `McpHost.startServer()`/`restartServer()` must use this
     * instead, or an in-memory MCP App is restarted with an unusable config.
     */
    getLiveMcpServers(): Record<string, MCPServerConfig> | undefined;
    resolveDefaultMcpPolicyOptions(): Promise<McpHostPolicyOptions>;
    resolveActiveGitHubTokenForMcpEnv(): Promise<string | undefined>;
    createMcpHostInstance(options: {
        disabledMcpServers: string[] | undefined;
        mcpPolicy: McpHostPolicyOptions;
        activeGitHubToken: string | undefined;
    }): McpHost;
    /** Emits MCP server-instructions stats telemetry for a freshly-started host. */
    sendMcpServerInstructionsTelemetry(host: McpHost): void;
    /**
     * Publish a successful MCP load: fire the `session.mcp_servers_loaded` event
     * and bump the tools version. Invoked by the lifecycle as the load
     * operation's success callback.
     */
    publishMcpLoadSucceeded(): void;
}

declare interface McpHostOptions {
    logger: RunnerLoggerContract_3;
    mcpConfig: string | MCPServersConfig;
    disabledMcpServers?: string[];
    envValueMode?: EnvValueMode;
    sessionId?: string;
    onOAuthRequired?: (serverName: string, serverUrl: string, staticClientConfig?: McpOAuthStaticClientConfig, forceReauth?: boolean, redirectPort?: number, wwwAuthenticateParams?: McpOAuthWWWAuthenticateParams, resourceMetadata?: string, httpResponse?: McpOAuthHttpResponse, signal?: AbortSignal) => Promise<OAuthClientProvider | undefined>;
    cancelPendingOAuthRequests?: (serverName: string) => void;
    onHeadersRefresh?: HeadersRefreshCallback;
    settings?: McpHostSettingsContext;
    elicitationHandler?: (serverName: string, request: ElicitRequestParams) => Promise<ElicitResult>;
    samplingHandler?: (serverName: string, requestId: string | number, request: CreateMessageRequestParams) => Promise<CreateMessageResultWithTools | undefined>;
    mcp3pEnabled?: boolean;
    onOIDCAuthRequired?: OIDCAuthCallback;
    configFilter?: McpConfigFilter;
    telemetryCallback?: MCPTelemetryCallback;
    /**
     * Optional secret store for resolving ${secret:...} placeholders.
     * Only used in the CLI; the Actions runtime does not use this.
     */
    secretStore?: McpSecretStoreInterface;
    /**
     * When true, advertise the MCP Apps (SEP-1865) UI extension during MCP
     * `initialize` and forward `_meta.ui` on tool listings. Combined with the
     * MCP_APPS feature flag in the registry. Defaults to false.
     */
    mcpAppsEnabled?: boolean;
    /**
     * When true, include initialization instructions from all MCP servers in the
     * system prompt instead of only allowlisted servers. Defaults to false.
     */
    allowAllServerInstructions?: boolean;
    /** Active GitHub token used only to resolve GITHUB_TOKEN in stdio MCP command-line args. */
    activeGitHubToken?: string;
    /**
     * When set and `enabled`, local (stdio) MCP servers spawn inside the
     * active MXC sandbox policy. Remote (HTTP/SSE) servers are unaffected —
     * the sandbox would only apply to the proxy/transport process, not the
     * remote endpoint.
     */
    sandboxConfig?: SandboxConfig_2;
    /**
     * Returns the session working directory used as the LAST-resort cwd fallback
     * when spawning stdio MCP servers (behind `serverConfig.cwd` / `$GITHUB_WORKSPACE`,
     * which are already folded into `serverConfig.cwd` upstream). A getter (not a
     * value) so a mid-session `/cd` is reflected on the next server (re)start. When
     * omitted, or when the getter returns a non-host-absolute value, stdio servers
     * without an explicit `serverConfig.cwd` spawn in the system temp directory with
     * a per-server warning.
     */
    getWorkingDir?: () => string;
    /**
     * Enterprise-managed MCP allowlists (managed settings only), one per managed
     * source. `undefined` or an empty array means no allowlist is in force (all
     * servers pass the allow stage). A server must be admitted by EVERY source's
     * allowlist (allowlist-intersection composition); a present-but-empty inner
     * list admits nothing. See {@link ManagedMcpServerMatcher} and the Rust
     * `managed_mcp_policy` engine.
     */
    managedAllowedMcpServerLists?: ManagedMcpServerMatcher[][];
    /**
     * Enterprise-managed MCP denylist (managed settings only), the union of every
     * source's deny entries. A server matching any entry is blocked regardless of
     * the allowlist (deny wins).
     */
    managedDeniedMcpServers?: ManagedMcpServerMatcher[];
    /**
     * Names of trusted first-party (runtime-injected) MCP servers that are exempt
     * from the enterprise managed allow/deny policy. This is the ONLY exemption
     * signal — it is derived by the caller from trusted provenance (servers the
     * runtime itself assembled, marked `source: "builtin"` after user config has
     * been stripped of that marker) and passed out-of-band, so a caller cannot
     * exempt a server by forging a config field or a reserved name on the
     * object / `startServer` API paths.
     */
    trustedDefaultServerNames?: string[];
    /**
     * Optional persisted raw-tool cache. Kept opt-in so deployment targets with
     * separate listing behavior (notably CCA's out-of-process host) are unchanged.
     */
    toolSnapshotCache?: McpToolSnapshotCache;
}

/** The resolved MCP policy a host should be created/reloaded with. See `Session.resolveDefaultMcpPolicyOptions()`. */
declare interface McpHostPolicyOptions {
    mcp3pEnabled: boolean;
    configFilter?: McpConfigFilter;
    managedAllowedMcpServerLists?: ManagedMcpServerMatcher[][];
    managedDeniedMcpServers?: ManagedMcpServerMatcher[];
}

declare type McpHostSettingsContext = ClientNameContext_2 & {
    /**
     * Active `--config-dir` override, when one is in effect. Declared explicitly
     * (rather than left to {@link ClientNameContext}'s index signature) so this
     * context is assignable where a typed `configDir` is required — the sandbox
     * proxy secret-store directory is resolved from it.
     */
    configDir?: string;
    api?: {
        github?: {
            mcpServerToken?: string;
        };
    };
};

/** Host-level state, omitted when no MCP host is initialized. */
declare interface McpHostState {
    /** Names of currently-connected MCP clients. */
    clients: string[];
    /** Configured servers that are explicitly disabled. */
    disabledServers: string[];
    /** Map of server name to recorded connection failure. */
    failedServers: Record<string, McpServerFailureInfo>;
    /** Configured servers filtered out by MCP server policy. */
    filteredServers: string[];
    /** Whether third-party MCP servers are policy-enabled for this session. */
    mcp3pEnabled: boolean;
    /** Map of server name to recorded pending-auth state. */
    needsAuthServers: Record<string, McpServerNeedsAuthInfo>;
    /** Names of servers with in-flight connection attempts. */
    pendingConnections: string[];
}

declare interface MCPInMemoryServerConfig extends MCPServerConfigBase {
    type: "memory";
    serverInstance: MCPInMemoryServerInstance;
}

declare type MCPInMemoryServerInstance = MCPNativeInMemoryServerInstance | McpServer;

declare interface MCPInMemoryToolDefinition<TInput = unknown> {
    name: string;
    title?: string;
    description: string;
    inputSchema?: Record<string, unknown>;
    handler: (args: TInput, extra: MCPInMemoryToolHandlerExtra) => Promise<CallToolResult> | CallToolResult;
}

/**
 * SDK-like per-request context passed to Rust-native in-memory MCP tool callbacks.
 *
 * SDK-backed {@link McpServer} in-memory configs are still connected through the
 * SDK server path and receive the SDK's real request context. Rust-native
 * callback tool servers receive the original request id and metadata, and their
 * reverse requests and notifications are routed through the native engine.
 * `sessionId` remains unavailable because it is not part of the MCP request.
 */
declare interface MCPInMemoryToolHandlerExtra {
    signal: AbortSignal;
    requestId: RequestId;
    sessionId?: string;
    _meta?: RequestMeta;
    sendNotification: (notification: JSONRPCNotification) => Promise<void>;
    sendRequest: (request: JSONRPCRequest) => Promise<unknown>;
}

/** Server name to check running status for. */
declare interface McpIsServerRunningRequest {
    /** Name of the MCP server to check */
    serverName: string;
}

/** Whether the named MCP server is running. */
declare interface McpIsServerRunningResult {
    /** True if the server has an active client and transport. */
    running: boolean;
}

/** Payload identifying the MCP server associated with a list change. */
export declare interface McpListChangedData {
    /** Name of the MCP server whose list changed */
    serverName: string;
}

declare type McpListChangedKind = "tools" | "resources" | "prompts";

/** Server name whose tool list should be returned. */
declare interface McpListToolsRequest {
    /** Name of the connected MCP server whose tools to list. */
    serverName: string;
}

/** Tools exposed by the connected MCP server. Throws when the server is not connected. */
declare interface McpListToolsResult {
    /** Tools exposed by the server. */
    tools: McpTools[];
}

/**
 * A single MCP load attempt's state: the load promise turns/tool-listing await,
 * plus the "turns may proceed without MCP" latch that releases those waiters
 * early without cancelling the load. One instance per in-flight load; owned by
 * {@link McpHostLifecycle}.
 */
declare class McpLoadOperation {
    private readonly load;
    private readonly proceedWithoutMcp;
    private turnsMayProceedWithoutMcp;
    private loadPromise;
    start(load: () => Promise<void>, onLoadSucceeded: () => void, onLoadFailed: (error: unknown) => never): void;
    waitForMcpToLoad(): Promise<void>;
    waitForMcpToLoadIfRequired(): Promise<boolean>;
    allowTurnsToProceedWithoutMcp(): boolean;
}

declare interface MCPLocalServerConfig extends MCPServerConfigBase {
    type?: "local" | "stdio";
    command: string;
    args: string[];
    /**
     * An object of the environment variables to pass to the server.
     *
     * The interpretation of this object depends on the environment variable mode:
     * - In 'indirect' mode (default): Hybrid approach for backward compatibility
     *   - If value contains $ or ${...}, tries variable substitution first
     *   - If substitution succeeds (changes the value), uses the resolved value
     *   - If not, it tries to treat value as the name of an env var to read from current process.
     *   - If such env var exists, uses it as a string literal.
     *   Example: { "FOO": "BAR" } sets FOO=process.env.BAR (legacy)
     *   Example: { "FOO": "$BAR" } sets FOO=process.env.BAR (variable expansion)
     *   Example: { "FOO": "${BAR:-default}" } sets FOO=process.env.BAR or "default"
     * - In 'direct' mode: Key is the env var name to set in the MCP server,
     *   Value is the literal value to set. Supports variable expansion:
     *   - $VAR or ${VAR}: expands to process.env.VAR
     *   - ${VAR:-default}: expands to process.env.VAR, or "default" if VAR is undefined
     *   Example: { "FOO": "bar" } sets FOO=bar
     *   Example: { "FOO": "${BAR}" } or { "FOO": "$BAR" } sets FOO=process.env.BAR
     *   Example: { "FOO": "${BAR:-fallback}" } sets FOO=process.env.BAR or "fallback"
     *   Example: { "URL": "https://${HOST}:${PORT}" } expands both variables
     *
     * Empty means no env vars passed.
     */
    env?: Record<string, string>;
    cwd?: string;
}

declare interface MCPNativeInMemoryServerInstance {
    kind: "native-tool-server";
    name: string;
    version: string;
    tools: MCPInMemoryToolDefinition[];
}

/** Identifies the MCP server whose persisted OAuth credentials were updated. */
declare interface McpOauthAuthenticationStateChangedRequest {
    /** Whether the target session must mint a session-scoped access token instead of reusing a shared access token persisted by another session. */
    refreshSessionToken?: boolean;
    /** Name of the MCP server whose OAuth credentials were updated. Omit only when the host cannot identify the server. */
    serverName?: string;
}

/** MCP OAuth request completion notification */
export declare interface McpOauthCompletedData {
    /** How the pending OAuth request was completed */
    outcome: McpOauthCompletionOutcome;
    /** Request ID of the resolved OAuth request */
    requestId: string;
}

/** Session event "mcp.oauth_completed". MCP OAuth request completion notification */
declare interface McpOauthCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** MCP OAuth request completion notification */
    data: McpOauthCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp.oauth_completed". */
    type: "mcp.oauth_completed";
}
export { McpOauthCompletedEvent as McpOAuthCompletedEvent }
export { McpOauthCompletedEvent }

/** How the pending MCP OAuth request was completed */
export declare type McpOauthCompletionOutcome = "token" | "cancelled";

/** Pending MCP OAuth request ID and host-provided token or cancellation response. */
declare interface McpOauthHandlePendingRequest {
    /** OAuth request identifier from the mcp.oauth_required event */
    requestId: string;
    /** Host response to the pending OAuth request. */
    result: McpOauthPendingRequestResponse;
}

/** Indicates whether the pending MCP OAuth response was accepted. */
declare interface McpOauthHandlePendingResult {
    /** Whether the response was accepted. False if the request was unknown, timed out, or already resolved. */
    success: boolean;
}

declare interface McpOAuthHostTokenResult {
    accessToken: string;
    tokenType?: string;
    expiresIn?: number;
}

declare type McpOAuthHttpResponse = McpOauthHttpResponse;

/** Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. */
export declare interface McpOauthHttpResponse {
    /** Complete UTF-8 response body for host-specific challenge handling, including an empty string for an empty body. Omitted when the complete body is not valid UTF-8; body read failures fail the HTTP operation rather than exposing a partial response. */
    body?: string;
    /** HTTP response headers as observed by the runtime. Order and casing are transport-dependent, and duplicate header names may appear multiple times. */
    headers: HeaderEntry[];
    /** HTTP status code returned with the auth challenge. */
    statusCode: number;
}

/** OAuth grant type override for this login. */
declare type McpOauthLoginGrantType = "authorization_code" | "client_credentials";

/** Remote MCP server name and optional overrides controlling reauthentication, OAuth client display name, callback success-page copy, and static OAuth client selection. */
declare interface McpOauthLoginRequest {
    /** Optional override for the body text shown on the OAuth loopback callback success page. When omitted, the runtime applies a neutral fallback; callers driving interactive auth should pass surface-specific copy telling the user where to return. */
    callbackSuccessMessage?: string;
    /** Optional OAuth client ID override for this login. When set, the runtime uses this pre-registered static client instead of dynamic client registration. */
    clientId?: string;
    /** Optional override for the OAuth client display name shown on the consent screen. Applies to newly registered dynamic clients only — existing registrations keep the name they were created with. When omitted, the runtime applies a neutral fallback; callers driving interactive auth should pass their own surface-specific label so the consent screen matches the product the user sees. */
    clientName?: string;
    /** Optional OAuth client secret override for this login. The runtime treats this as an ephemeral host-owned secret, uses it for this authentication attempt and does not persist it. */
    clientSecret?: string;
    /** When true, clears any cached OAuth token for the server and runs a full new authorization. Use when the user explicitly wants to switch accounts or believes their session is stuck. */
    forceReauth?: boolean;
    /** Optional OAuth grant type override for this login. Defaults to the server configuration, or authorization_code when no grant type is specified. */
    grantType?: McpOauthLoginGrantType;
    /** Optional override indicating whether the static OAuth client is public. When false, the runtime treats it as confidential and uses the per-login clientSecret if provided, otherwise retrieving the client secret from the MCP OAuth secret store. */
    publicClient?: boolean;
    /** Name of the remote MCP server to authenticate */
    serverName: string;
}

/** OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. */
declare interface McpOauthLoginResult {
    /** URL the caller should open in a browser to complete OAuth. Omitted when cached tokens were still valid and no browser interaction was needed — the server is already reconnected in that case. When present, the runtime starts the callback listener before returning and continues the flow in the background; completion is signaled via session.mcp_server_status_changed. */
    authorizationUrl?: string;
}

declare interface McpOAuthPendingRequest {
    context: McpOAuthRequestContext;
    provider: OAuthClientProvider;
}

/** Host response to the pending OAuth request. */
declare type McpOauthPendingRequestResponse = {
    accessToken: string;
    expiresIn?: number;
    kind: "token";
    tokenType?: string;
    [key: string]: unknown;
} | {
    kind: "cancelled";
    [key: string]: unknown;
};

declare interface McpOAuthRequestContext {
    serverName: string;
    serverUrl: string;
    staticClientConfig?: McpOAuthStaticClientConfig;
    redirectPort?: number;
    wwwAuthenticateParams?: McpOAuthWWWAuthenticateParams;
    resourceMetadata?: string;
    httpResponse?: McpOAuthHttpResponse;
    reason?: McpOAuthRequestReason;
}

declare type McpOAuthRequestReason = "initial" | "refresh" | "reauth" | "upscope";

/** Reason the runtime is requesting host-provided MCP OAuth credentials */
export declare type McpOauthRequestReason = "initial" | "refresh" | "reauth" | "upscope";

/** OAuth authentication request for an MCP server */
export declare interface McpOauthRequiredData {
    /** Raw HTTP response details from the OAuth auth challenge, as observed by the runtime. Header order and casing are transport-dependent, and duplicate header names may appear multiple times. */
    httpResponse?: McpOauthHttpResponse;
    /** Why the runtime is requesting host-provided OAuth credentials. */
    reason: McpOauthRequestReason;
    /** Unique identifier for this OAuth request; used to respond via session.mcp.oauth.handlePendingRequest */
    requestId: string;
    /** Raw OAuth protected-resource metadata document fetched for the MCP server, if available */
    resourceMetadata?: string;
    /** Display name of the MCP server that requires OAuth */
    serverName: string;
    /** URL of the MCP server that requires OAuth */
    serverUrl: string;
    /** Static OAuth client configuration, if the server specifies one */
    staticClientConfig?: McpOauthRequiredStaticClientConfig;
    /** OAuth WWW-Authenticate parameters parsed from the auth challenge, if available */
    wwwAuthenticateParams?: McpOauthWWWAuthenticateParams;
}

/** Session event "mcp.oauth_required". OAuth authentication request for an MCP server */
declare interface McpOauthRequiredEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** OAuth authentication request for an MCP server */
    data: McpOauthRequiredData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp.oauth_required". */
    type: "mcp.oauth_required";
}
export { McpOauthRequiredEvent as McpOAuthRequestedEvent }
export { McpOauthRequiredEvent }

/** Static OAuth client configuration, if the server specifies one */
export declare interface McpOauthRequiredStaticClientConfig {
    /** OAuth client ID for the server */
    clientId: string;
    /** Optional OAuth client secret for confidential static clients, when the runtime can resolve one */
    clientSecret?: string;
    /** Optional non-default OAuth grant type. When set to 'client_credentials', the OAuth flow runs headlessly using the client_id + keychain-stored secret (no browser, no callback server). */
    grantType?: "client_credentials";
    /** Whether this is a public OAuth client */
    publicClient?: boolean;
}

/** Pending MCP OAuth request id to respond to. */
declare interface McpOauthRespondRequest {
    /** OAuth request identifier from the mcp.oauth_required event */
    requestId: string;
}

/** Indicates whether the pending MCP OAuth response was accepted. */
declare interface McpOauthRespondResult {
    /** Whether the response was accepted. False if the request was unknown, timed out, or already resolved. */
    success: boolean;
}

declare interface McpOAuthStaticClientConfig {
    clientId: string;
    clientSecret?: string;
    publicClient?: boolean;
    grantType?: "client_credentials";
}

/**
 * Interface for MCP OAuth storage operations.
 *
 * The `key` parameter is a store key computed by the OAuth flow.
 * For dynamic (DCR) clients it equals the raw server URL; for static clients
 * it includes a client-ID suffix so sibling servers on the same URL get
 * independent cache entries.
 */
declare interface MCPOAuthStoreInterface {
    getTokens(key: string): Promise<MCPOAuthTokens | undefined>;
    saveTokens(key: string, tokens: MCPOAuthTokens): Promise<boolean>;
    deleteTokens(key: string): Promise<void>;
    getClientRegistration(key: string): Promise<MCPClientRegistration | undefined>;
    saveClientRegistration(key: string, registration: MCPClientRegistration): Promise<void>;
    deleteClientRegistration(key: string): Promise<void>;
    getStaticClientSecret(key: string): Promise<string | undefined>;
    saveStaticClientSecret(key: string, secret: string): Promise<boolean>;
    deleteStaticClientSecret(key: string): Promise<void>;
    saveCodeVerifier(key: string, verifier: string): Promise<void>;
    getCodeVerifier(key: string): Promise<string | undefined>;
    clearCodeVerifier(key: string): Promise<void>;
}

/**
 * OAuth tokens stored for an MCP server
 */
declare interface MCPOAuthTokens {
    accessToken: string;
    refreshToken?: string;
    expiresAt?: number;
    scope?: string;
}

declare interface McpOAuthWWWAuthenticateParams {
    resourceMetadataUrl?: string;
    scope?: string;
    error?: string;
}

/** OAuth WWW-Authenticate parameters parsed from an MCP auth challenge */
export declare interface McpOauthWWWAuthenticateParams {
    /** OAuth error from the WWW-Authenticate error parameter, if present */
    error?: string;
    /** Protected resource metadata URL from the WWW-Authenticate resource_metadata parameter, if present */
    resourceMetadataUrl?: string;
    /** Requested OAuth scopes from the WWW-Authenticate scope parameter, if present */
    scope?: string;
}

/**
 * A permission request for invoking an MCP tool.
 */
declare type MCPPermissionRequest = {
    readonly kind: "mcp";
    /** The name of the MCP Server being targeted e.g. "github-mcp-server" */
    readonly serverName: string;
    /** The name of the tool being targeted e.g. "list_issues" */
    readonly toolName: string;
    /** The title of the tool being targeted e.g. "List Issues" */
    readonly toolTitle: string;
    /**
     * The _hopefully_ JSON arguments that will be passed to the MCP tool.
     *
     * This should be an object, but it's not parsed before this point so we can't guarantee that.
     * */
    readonly args?: unknown;
    /**
     * Whether the tool is read-only (e.g. a `view` operation) or not (e.g. an `edit` operation).
     */
    readonly readOnly: boolean;
    readonly autoApproval?: AutoApproval;
};

/** Session event "mcp.prompts.list_changed". Payload identifying the MCP server associated with a list change. */
export declare interface McpPromptsListChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload identifying the MCP server associated with a list change. */
    data: McpListChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp.prompts.list_changed". */
    type: "mcp.prompts.list_changed";
}

/**
 * Telemetry event emitted when secret masking was skipped for a proxy tool call.
 */
declare type McpProxySecretMaskingSkippedEvent = TelemetryEvent<"mcp_proxy_secret_masking_skipped", {
    properties: {
        /**
         * SHA-256 hash of the MCP server name.
         */
        serverName: string;
        /**
         * SHA-256 hash of the tool name that was called.
         */
        toolName: string;
        /**
         * Whether secret masking was skipped.
         */
        skipped: "true" | "false";
        /**
         * Whether secret masking is disabled for the server (if false, then masking should have occurred but was skipped, likely due to an error).
         */
        disabledForServer: "true" | "false";
    };
    restrictedProperties: {
        /**
         * The raw (unhashed) name of the MCP server.
         */
        serverName: string;
        /**
         * The raw (unhashed) name of the tool that was called.
         */
        toolName: string;
    };
    metrics: Record<string, never>;
}>;

/** Registration parameters for an external MCP client. */
declare interface McpRegisterExternalClientRequest {
    /** In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC boundary. */
    client: unknown;
    /** In-process server config (MCPServerConfig) paired with the in-process client/transport. Marked internal alongside its companions. */
    config: unknown;
    /** Logical server name for the external client */
    serverName: string;
    /** In-process MCP Transport instance. Marked internal: cannot be serialized across the JSON-RPC boundary. */
    transport: unknown;
}

declare class MCPRegistry {
    private readonly logger;
    envValueMode: EnvValueMode;
    protected settings?: ClientNameContext | undefined;
    private readonly elicitationHandler?;
    private readonly samplingHandler?;
    private readonly mcpAppsEnabled;
    protected sandboxConfig?: SandboxConfig_2 | undefined;
    private allowAllServerInstructions;
    private readonly hostStateHandle;
    private readonly ownsHostStateHandle;
    private readonly hostStateFinalizerToken;
    private toolsChangedCallback?;
    private listChangedCallback?;
    private elicitationCompleteCallback?;
    private statusChangedCallback?;
    private builtinNotificationCallback?;
    private abortSignal?;
    /**
     * Null-proto: server names are untrusted, so a name that shadows an
     * Object.prototype member (`constructor`, `__proto__`, ...) must not leak
     * through `name in clients` / `clients[name]` (copilot-agent-runtime#12507).
     */
    clients: Record<string, NativeMcpSession>;
    /**
     * Null-proto: keyed by the same untrusted server names as `clients`. A plain
     * object literal would send a `__proto__`-named transport to the prototype
     * instead of an own key, so `delete` could not remove it and the legacy
     * shutdown path's `Object.keys(transports)` scan would skip it, letting it
     * auto-reconnect (copilot-agent-runtime#12507).
     */
    transports: Record<string, Transport>;
    configs: Record<string, MCPServerConfig>;
    /**
     * Null-proto: keyed by untrusted server names, matching `clients`
     * (copilot-agent-runtime#12507).
     */
    pendingConnections: Record<string, Promise<void>>;
    /**
     * Subset of {@link pendingConnections} whose connect may block on interactive
     * browser authorization (background OAuth). Tracked so bounded callers can
     * skip them via {@link nonInteractivePendingConnections} instead of awaiting a
     * user-driven flow that could take arbitrarily long.
     */
    private readonly interactivePendingConnections;
    constructor(logger: RunnerLoggerContract_3, envValueMode?: EnvValueMode, settings?: ClientNameContext | undefined, elicitationHandler?: ((serverName: string, request: ElicitRequestParams) => Promise<ElicitResult>) | undefined, samplingHandler?: ((serverName: string, requestId: string | number, request: CreateMessageRequestParams) => Promise<CreateMessageResultWithTools | undefined>) | undefined, mcpAppsEnabled?: boolean, sandboxConfig?: SandboxConfig_2 | undefined, _headersRefreshManager?: unknown, allowAllServerInstructions?: boolean, hostStateHandle?: number);
    private createNativeConfigsProxy;
    get failedServers(): Record<string, ServerFailureInfo>;
    set failedServers(value: Record<string, ServerFailureInfo>);
    get needsAuthServers(): Record<string, {
        timestamp: number;
    }>;
    set needsAuthServers(value: Record<string, {
        timestamp: number;
    }>);
    private get serverInstructions();
    private get deferredServerInstructions();
    setToolsChangedCallback(callback: (clientName: string, isInitialConnection: boolean) => void | Promise<void>): void;
    setListChangedCallback(callback: (serverName: string, kind: McpListChangedKind) => void): void;
    notifyToolsChanged(serverName: string): void;
    /** Triggers initial tool discovery after a deferred connection becomes available. */
    notifyInitialToolsAvailable(serverName: string): void;
    private notifyToolsChangedCallback;
    setElicitationCompleteCallback(callback: (elicitationId: string) => void): void;
    setAbortSignal(signal?: AbortSignal): void;
    getAbortSignal(): AbortSignal | undefined;
    setOnStatusChanged(callback: (serverName: string, status: ServerConnectionStatus) => void): void;
    setBuiltinNotificationCallback(callback: (serverName: string, method: string, params: unknown) => void): void;
    setSandboxConfig(config?: SandboxConfig_2): void;
    private getCapabilityOptions;
    private getConnectTimeoutMs;
    private buildBridgeHandlers;
    handleNativeNotification(serverName: string, method: string, paramsJson: string): void;
    private emitListChanged;
    private recordClient;
    removeClient(serverName: string): void;
    startHttpMcpClient(_serverName: string, _serverConfig: unknown, _authProvider?: unknown, _headersRefreshManager?: unknown): Promise<void>;
    startSseMcpClient(_serverName: string, _serverConfig: unknown, _authProvider?: unknown, _headersRefreshManager?: unknown): Promise<void>;
    startLocalMcpClient(_serverName: string, _serverConfig: unknown): Promise<void>;
    startLocalMcpClientDeferred(_serverName: string, _serverConfig: unknown): void;
    trackPendingConnection(serverName: string, promise: Promise<void>, interactive?: boolean): void;
    clearPendingConnectionIfCurrent(serverName: string, promise: Promise<void>): void;
    /**
     * Reclassify an in-flight pending connection's interactive status. A
     * background OAuth connect is tracked interactive while it may block on
     * browser authorization, then reclassified non-interactive once it enters
     * the non-interactive transport connect (which samples the sandbox proxy) so
     * a bounded drain — the sandbox-restart in {@link McpHost.applySandboxConfig}
     * — awaits it and sees the resulting client instead of leaving it stranded on
     * a stale proxy.
     *
     * Guarded on the originating `promise`, like
     * {@link clearPendingConnectionIfCurrent}: a superseding attempt can replace
     * the pending entry while an earlier attempt still holds the configuration
     * lock, and the earlier attempt's later phase callback must not clear the
     * interactive flag off the replacement — that would leave a still
     * browser-blocked connect flagged non-interactive, so the drain awaits it
     * indefinitely. No-op once the server is no longer pending under `promise`.
     */
    setPendingConnectionInteractive(serverName: string, promise: Promise<void>, interactive: boolean): void;
    /**
     * Pending connection promises that are safe to await from a bounded caller
     * (e.g. the sandbox-restart drain in {@link McpHost.applySandboxConfig}).
     * Excludes background OAuth connects flagged interactive, which may block on
     * interactive browser authorization for as long as the user takes.
     */
    nonInteractivePendingConnections(): Promise<void>[];
    captureNativeServerInstructions(serverName: string, instructions: string | undefined): void;
    recordFailure(serverName: string, error: Error): void;
    clearFailure(serverName: string): void;
    getServerStderr(_serverName: string): undefined;
    recordNeedsAuth(serverName: string): void;
    clearNeedsAuth(serverName: string): void;
    markIntentionalDisconnect(serverName: string): void;
    isIntentionalDisconnect(serverName: string): boolean;
    getServerStatus(serverName: string): ServerConnectionStatus;
    ensureConnected(serverName: string): Promise<void>;
    startInMemoryMcpClient(serverName: string, serverConfig: MCPServerConfig, serverInstance: MCPInMemoryServerInstance): Promise<void>;
    registerExternalClient(serverName: string, client: NativeMcpSession, transport: Transport, config: MCPServerConfig): void;
    unregisterExternalClient(serverName: string): void;
    connectionHeadersWithDefaultUserAgent(headers: Record<string, string> | undefined): Record<string, string>;
    getServerInstructions(): Record<string, string>;
    getServerInstructionMode(): MCPServerInstructionMode;
    setAllowAllServerInstructions(allowAllServerInstructions: boolean): void;
    getServerInstructionsNotInAllowlistCount(): number;
    getDeferredServerInstructions(): Record<string, string>;
    getDeferredServerToolSummaries(): Promise<Record<string, Array<{
        name: string;
        description: string;
    }>>>;
}

/** Opaque MCP reload configuration. */
declare interface McpReloadWithConfigRequest {
    /** Opaque runtime MCP reload configuration. Marked internal: an in-process runtime shape (reloadMcpServers throws over the wire). */
    config: unknown;
}

declare interface MCPRemoteServerConfig extends MCPServerConfigBase {
    type: "http" | "sse";
    /**
     * URL of the remote server
     * NOTE: this has to be converted to a URL object before giving to transport.
     * TransportFactory will handle this conversion.
     */
    url: string;
    /**
     * Optional. HTTP headers to include in requests to the remote server.
     * This can be used for authentication or other purposes.
     * For example, you might include an Authorization header.
     */
    headers?: Record<string, string>;
    /**
     * Optional. Dynamic header refresh cache TTL in milliseconds for this server.
     * Defaults to 60 seconds when host-driven MCP headers refresh is enabled.
     * Set to 0 to refresh before every request.
     */
    headersRefreshTtlMs?: number;
    /**
     * Optional. OAuth client ID for pre-registered (static) OAuth clients.
     * When set, dynamic client registration is skipped and this client ID is used.
     * If not set, dynamic client registration (RFC 7591) is used when OAuth is detected.
     *
     * OAuth is automatically detected by probing the server at connection time
     * (via /.well-known/oauth-protected-resource or 401 Unauthorized responses).
     */
    oauthClientId?: string;
    /**
     * Optional. Indicates whether this is a public OAuth client (no secret).
     * Defaults to true (public client).
     * When false, the client secret is retrieved from the system keychain.
     */
    oauthPublicClient?: boolean;
    /**
     * Optional. OAuth grant type to use for this server.
     * - "authorization_code" (default): interactive browser-based flow with PKCE.
     * - "client_credentials": fully headless flow that POSTs directly to the token endpoint
     *   using the configured `oauthClientId` + a client secret. Requires
     *   `oauthClientId` to be set and `oauthPublicClient` to be `false`. No browser is opened
     *   and no localhost callback server is started — suitable for CI/cron usage.
     */
    oauthGrantType?: "authorization_code" | "client_credentials";
    /**
     * Optional. Additional authentication configuration for this server.
     */
    auth?: MCPServerAuthConfig;
}

/** Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove). */
declare interface McpRemoveGitHubResult {
    /** True when the auto-managed `github` MCP server was removed; false when no removal happened (e.g. user has explicitly configured a `github` server, or the server was not registered). */
    removed: boolean;
}

/** An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, MIME type, size, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. */
declare interface McpResource {
    /** Resource-level metadata */
    _meta?: Record<string, unknown>;
    /** Server-provided non-standard descriptor fields preserved from the MCP response */
    additionalProperties?: Record<string, unknown>;
    /** Model/client annotations associated with this resource */
    annotations?: McpResourceAnnotations;
    /** Optional description of what this resource represents */
    description?: string;
    /** Icons associated with this resource */
    icons?: McpResourceIcon[];
    /** MIME type of the resource, if known */
    mimeType?: string;
    /** The programmatic name of the resource */
    name: string;
    /** Resource size in bytes, when known */
    size?: number;
    /** Optional human-readable display title */
    title?: string;
    /** The resource URI (e.g. ui://... or file:///...) */
    uri: string;
}

/** Standard MCP resource annotations plus preserved non-standard annotation fields. */
declare interface McpResourceAnnotations {
    /** Server-provided non-standard annotation fields preserved from the MCP response */
    additionalProperties?: Record<string, unknown>;
    /** Intended audience roles for this resource */
    audience?: string[];
    /** Last-modified timestamp hint */
    lastModified?: string;
    /** Priority hint for model/client use */
    priority?: number;
}

/** MCP resource content with URI, optional MIME type, text or base64 blob, and resource metadata. */
declare interface McpResourceContent {
    /** Resource-level metadata (CSP, permissions, etc.) */
    _meta?: Record<string, unknown>;
    /** Base64-encoded binary content */
    blob?: string;
    /** MIME type of the content */
    mimeType?: string;
    /** Text content (e.g. HTML) */
    text?: string;
    /** The resource URI */
    uri: string;
}

/** A resource icon descriptor plus preserved non-standard icon fields. */
declare interface McpResourceIcon {
    /** Server-provided non-standard icon fields preserved from the MCP response */
    additionalProperties?: Record<string, unknown>;
    /** Icon MIME type, when known */
    mimeType?: string;
    /** Icon sizes hint */
    sizes?: string;
    /** Icon URI */
    src: string;
    /** Theme hint for this icon */
    theme?: string;
}

/** Session event "mcp.resources.list_changed". Payload identifying the MCP server associated with a list change. */
export declare interface McpResourcesListChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload identifying the MCP server associated with a list change. */
    data: McpListChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp.resources.list_changed". */
    type: "mcp.resources.list_changed";
}

/** MCP server whose resources to enumerate. */
declare interface McpResourcesListRequest {
    /** Opaque MCP pagination cursor from a prior `nextCursor` value */
    cursor?: string;
    /** Name of the MCP server whose resources to enumerate */
    serverName: string;
}

/** One page of resources advertised by the named MCP server. */
declare interface McpResourcesListResult {
    /** Opaque cursor for the next page, if the server has more resources */
    nextCursor?: string;
    /** Resources advertised by the server (proxied MCP `resources/list`) */
    resources: McpResource[];
}

/** MCP server whose resource templates to enumerate. */
declare interface McpResourcesListTemplatesRequest {
    /** Opaque MCP pagination cursor from a prior `nextCursor` value */
    cursor?: string;
    /** Name of the MCP server whose resource templates to enumerate */
    serverName: string;
}

/** One page of resource templates advertised by the named MCP server. */
declare interface McpResourcesListTemplatesResult {
    /** Opaque cursor for the next page, if the server has more resource templates */
    nextCursor?: string;
    /** Resource templates advertised by the server (proxied MCP `resources/templates/list`) */
    resourceTemplates: McpResourceTemplate[];
}

/** MCP server and resource URI to fetch. */
declare interface McpResourcesReadRequest {
    /** Name of the MCP server hosting the resource */
    serverName: string;
    /** Resource URI */
    uri: string;
}

/** Resource contents returned by the MCP server. */
declare interface McpResourcesReadResult {
    /** Resource contents returned by the server */
    contents: McpResourceContent[];
}

/** An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, name, and optional title, description, MIME type, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. */
declare interface McpResourceTemplate {
    /** Resource-template-level metadata */
    _meta?: Record<string, unknown>;
    /** Server-provided non-standard descriptor fields preserved from the MCP response */
    additionalProperties?: Record<string, unknown>;
    /** Model/client annotations associated with this template */
    annotations?: McpResourceAnnotations;
    /** Optional description of what this template is for */
    description?: string;
    /** Icons associated with resources matching this template */
    icons?: McpResourceIcon[];
    /** MIME type for resources matching this template, if uniform */
    mimeType?: string;
    /** The programmatic name of the resource template */
    name: string;
    /** Optional human-readable display title */
    title?: string;
    /** An RFC 6570 URI template for constructing resource URIs */
    uriTemplate: string;
}

/** Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. */
declare interface McpRestartServerRequest {
    /** Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). */
    config?: McpServerConfig;
    /** Name of the MCP server to restart */
    serverName: string;
}

declare interface McpSamplingAgentResult<TelemetryT extends Telemetry = Telemetry> {
    action: "success" | "failure" | "reject";
    /** The result of the sampling request, if successful. */
    result?: CreateMessageResultWithTools_2;
    /**
     * If there was an error during processing the sampling request, this field will contain a description of the error.
     * This is separate from the "reject" action, which indicates that the request was processed successfully but the
     * response was rejected (e.g. by content filters or because it didn't meet certain criteria).
     */
    error?: string;
    /**
     * Specific telemetry for the sampling request. Will be sent back to the server by the agent.
     */
    toolTelemetry?: {
        properties?: TelemetryT["properties"];
        restrictedProperties?: TelemetryT["restrictedProperties"];
        metrics?: TelemetryT["metrics"];
    };
}

/** Outcome of the sampling inference. 'success' produced a response; 'failure' encountered an error (including agent-side rejection by content filter or criteria); 'cancelled' the caller cancelled this execution via cancelSamplingExecution. */
declare type McpSamplingExecutionAction = "success" | "failure" | "cancelled";

/** Outcome of an MCP sampling execution: success result, failure error, or cancellation. */
declare interface McpSamplingExecutionResult {
    /** Outcome of the sampling inference. 'success' produced a response; 'failure' encountered an error (including agent-side rejection by content filter or criteria); 'cancelled' the caller cancelled this execution via cancelSamplingExecution. */
    action: McpSamplingExecutionAction;
    /** Error description, present when action='failure'. */
    error?: string;
    /** MCP CreateMessageResult payload (with optional 'tools' extension), present when action='success'. Treated as opaque at the schema layer; consumers should construct/consume it per the MCP CreateMessageResult shape. */
    result?: McpExecuteSamplingResult;
}

/**
 * Interface for MCP secret storage operations.
 * Secrets are stored in the OS keychain with a file-based fallback.
 *
 * The concrete implementation lives at `src/mcp-client/mcp-secret-store.ts`;
 * this interface is defined separately so that types stay import-cheap and
 * keep the `mcp-client`/`core` layers free of transitive CLI dependencies.
 */
declare interface McpSecretStoreInterface {
    /** Get a secret value by its ID. */
    getSecret(secretId: string): Promise<string | undefined>;
    /** Save a secret value. Returns true if stored in keychain, false if file fallback. */
    saveSecret(secretId: string, value: string): Promise<boolean>;
    /** Delete a secret by its ID. */
    deleteSecret(secretId: string): Promise<void>;
    /** Delete all secrets for a given server name. */
    deleteServerSecrets(serverName: string): Promise<void>;
    /**
     * Resolve all ${secret:...} placeholders in a string, replacing them
     * with the actual secret values from the store.
     * Returns the string with all resolvable placeholders replaced.
     */
    resolveSecrets(value: string): Promise<string>;
}

declare interface McpServer {
    connect(transport: Transport): Promise<unknown>;
    close?(): Promise<unknown>;
    registerTool?: unknown;
}

/** MCP server status entry, including config source/plugin source and any connection error. */
declare interface McpServer_2 {
    /** Error message if the server failed to connect */
    error?: string;
    /** Server name (config key) */
    name: string;
    /** Configuration source: user, workspace, plugin, or builtin */
    source?: McpServerSource_2;
    /** Plugin name that provided this server, when source is plugin. */
    sourcePlugin?: string;
    /** Plugin version that provided this server, when source is plugin. */
    sourcePluginVersion?: string;
    /** Connection status: connected, failed, needs-auth, pending, disabled, stopped, or not_configured */
    status: McpServerStatus_2;
}

/**
 * Authentication configuration for a remote MCP server.
 * When `true`, default auth settings are used.
 */
declare type MCPServerAuthConfig = boolean | MCPServerAuthSettings;

/** Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. */
declare type McpServerAuthConfig = boolean | McpServerAuthConfigRedirectPort;

/** Authentication settings with optional redirect port configuration. */
declare interface McpServerAuthConfigRedirectPort {
    /** Fixed port for the OAuth redirect callback server. */
    redirectPort?: number;
    [key: string]: unknown;
}

/**
 * Additional authentication settings for a remote MCP server.
 */
declare interface MCPServerAuthSettings {
    /**
     * Fixed port for the OAuth redirect callback server.
     * When set, the localhost callback server binds to this port instead of
     * an ephemeral random port. Useful when the OAuth provider requires the
     * redirect URI to be pre-registered with a known port.
     */
    redirectPort?: number;
}

declare type MCPServerConfig = MCPLocalServerConfig | MCPRemoteServerConfig | MCPInMemoryServerConfig;

/** MCP server configuration (stdio process or remote HTTP/SSE) */
declare type McpServerConfig = McpServerConfigStdio | McpServerConfigHttp;

declare interface MCPServerConfigBase {
    /**
     * Optional human-readable name for this server.
     */
    displayName?: string;
    /**
     * List of tools to include from this server. [] means none. "*" means all.
     */
    tools: string[];
    /**
     * Indicates "remote" or "local" server type.
     * If not specified, defaults to "local".
     */
    type?: string;
    /**
     * Optional. Denotes if this is a MCP server we have defined to be used when
     * the user has not provided their own MCP server config.
     *
     * Marked optional as configs coming from users will/should not have this set. Defaults to `false`.
     */
    isDefaultServer?: boolean;
    /**
     * Optional. Either a content filter mode for all tools from this server, or a map of tool name to content filter mode for the tool with that name.
     * If not specified, defaults to "hidden_characters"
     */
    filterMapping?: Record<string, ContentFilterMode> | ContentFilterMode;
    /**
     * Optional. Timeout in milliseconds for tool calls to this server.
     * If not specified, a default is used.
     */
    timeout?: number;
    /**
     * Optional. Telemetry-obfuscation policy for this server's tools.
     *
     * By default an MCP tool's name and argument names are hashed in
     * telemetry. Tools in the known-tool catalog have their name emitted in
     * the clear, but their argument names remain hashed. Set safeForTelemetry on
     * a trusted, first-party server to emit its tools' telemetry in the clear.
     * `true` unobfuscates both the tool name and its argument names;
     * an object controls each independently. Only honored for first-party
     * servers vouched by `source: "builtin"` (not the caller-settable `isDefaultServer`)
     */
    safeForTelemetry?: boolean | {
        name: boolean;
        inputsNames: boolean;
    };
    /**
     * Optional. Name of the plugin that provided this MCP server.
     * Only set for servers loaded from installed plugins.
     */
    sourcePlugin?: string;
    /**
     * Optional. Version of the plugin that provided this MCP server.
     * Only set for servers loaded from installed plugins.
     */
    sourcePluginVersion?: string;
    /**
     * Optional. True when the providing plugin declares the Agent Plugins
     * (Open Plugin Spec) `$schema`. Used at launch time to protect the injected
     * `PLUGIN_DATA` env trio from re-resolution only for spec plugins.
     */
    sourcePluginSpec?: boolean;
    /**
     * Optional. Tracks the origin of this server configuration.
     * - "user": from user's ~/.copilot/mcp-config.json
     * - "workspace": from .mcp.json or .github/mcp.json in the workspace root
     * - "plugin": from an installed plugin
     * - "builtin": default server injected by the runtime
     */
    source?: "user" | "workspace" | "plugin" | "builtin";
    /**
     * Optional. The file path this server was loaded from.
     * Set at load time; not persisted.
     */
    sourcePath?: string;
    /**
     * Optional. When true, secret masking is disabled for tool calls to this server.
     * This is checked in addition to the `copilot_swe_agent_runtime_filter_secrets_from_mcp_tool_calls`
     * feature flag — even when the feature flag enables secret filtering, setting this to true
     * will skip filtering for this server's tools.
     *
     * Only respected in the proxy transport and out of process transport.
     */
    disableSecretMasking?: boolean;
    /**
     * Optional. When true, persisted tool snapshots are not loaded or written for this server.
     * Live tool discovery still runs normally. Existing cache files are left untouched.
     *
     * Set `COPILOT_MCP_TOOL_CACHE=false` to disable the cache process-wide.
     */
    disableToolCache?: boolean;
    /**
     * Optional. When truthy, an OIDC token is automatically gathered.
     */
    oidc?: MCPServerOIDCConfig;
    /**
     * Optional. List of event types this server wants to receive as
     * `notifications/copilot` MCP notifications (host -> server direction).
     * Currently only respected for built-in servers (`source: "builtin"`).
     */
    events?: string[];
    /**
     * Optional. List of `notifications/copilot` notification types this server
     * is allowed to send to the host (server -> host direction).
     * Acts as an explicit capability opt-in. Currently only respected for
     * built-in servers (`source: "builtin"`).
     *
     * Supported values:
     * - "user.abort": server can request the agent loop to stop.
     */
    notifications?: string[];
    /**
     * Optional. Config-level warnings detected at load time (e.g. legacy
     * `oauth` key). Set at load time; not persisted.
     */
    configWarnings?: string[];
    /**
     * Optional. List of tool names to exclude from this server, applied after the `tools`
     * include filter. A tool in this list is hidden even when `tools` is `["*"]`.
     *
     * Use this to suppress MCP tools that overlap with built-in runtime tools so the model
     * never sees both variants of the same operation.
     */
    excludeTools?: string[];
    /**
     * Optional. Controls whether this server's tools are eligible for deferred loading
     * when tool search is active.
     * - `"auto"` (default): tools may be deferred once the total tool count exceeds the
     *   deferral threshold, and discovered on demand via tool search.
     * - `"never"`: tools are always included in the initial tool list sent to the model,
     *   even when tool search is enabled.
     *
     * Use `"never"` for small or frequently-used servers whose tools the model should
     * always see without first searching for them.
     */
    deferTools?: "auto" | "never";
}

/** Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) */
declare type McpServerConfigDeferTools = "auto" | "never";

/** Remote MCP server configuration accessed over HTTP or SSE. */
declare interface McpServerConfigHttp {
    /** Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. */
    auth?: McpServerAuthConfig;
    /** Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) */
    deferTools?: McpServerConfigDeferTools;
    /** Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery is unaffected. */
    disableToolCache?: boolean;
    /** Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. */
    filterMapping?: FilterMapping;
    /** HTTP headers to include in requests to the remote MCP server. */
    headers?: Record<string, string>;
    /** Whether this server is a built-in fallback used when the user has not configured their own server. */
    isDefaultServer?: boolean;
    /** OAuth client ID for a pre-registered remote MCP OAuth client. */
    oauthClientId?: string;
    /** OAuth grant type to use when authenticating to the remote MCP server. */
    oauthGrantType?: McpServerConfigHttpOauthGrantType;
    /** Whether the configured OAuth client is public and does not require a client secret. */
    oauthPublicClient?: boolean;
    /** Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. */
    oidc?: McpServerAuthConfig;
    /** Timeout in milliseconds for tool calls to this server. */
    timeout?: number;
    /** Tools to include. Defaults to all tools if not specified. */
    tools?: string[];
    /** Remote transport type. Defaults to "http" when omitted. */
    type?: McpServerConfigHttpType;
    /** URL of the remote MCP server endpoint. */
    url: string;
}

/** OAuth grant type to use when authenticating to the remote MCP server. */
declare type McpServerConfigHttpOauthGrantType = "authorization_code" | "client_credentials";

/** Remote transport type. Defaults to "http" when omitted. */
declare type McpServerConfigHttpType = "http" | "sse";

/** Stdio MCP server configuration launched as a child process. */
declare interface McpServerConfigStdio {
    /** Command-line arguments passed to the Stdio MCP server process. */
    args?: string[];
    /** Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. */
    auth?: McpServerAuthConfig;
    /** Executable command used to start the Stdio MCP server process. */
    command: string;
    /** Working directory for the Stdio MCP server process. */
    cwd?: string;
    /** Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) */
    deferTools?: McpServerConfigDeferTools;
    /** Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery is unaffected. */
    disableToolCache?: boolean;
    /** Environment variables to pass to the Stdio MCP server process. */
    env?: Record<string, string>;
    /** Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. */
    filterMapping?: FilterMapping;
    /** Whether this server is a built-in fallback used when the user has not configured their own server. */
    isDefaultServer?: boolean;
    /** Set to `true` to use defaults, or provide an object with additional auth or OIDC settings. */
    oidc?: McpServerAuthConfig;
    /** Timeout in milliseconds for tool calls to this server. */
    timeout?: number;
    /** Tools to include. Defaults to all tools if not specified. */
    tools?: string[];
}

/** Recorded MCP server connection failure. */
declare interface McpServerFailureInfo {
    /** Failure message produced when the MCP server connection failed. */
    message: string;
    /** epoch-ms timestamp at which the failure was recorded. */
    timestamp: number;
}

declare type MCPServerInstructionMode = "allowlist" | "all";

/** MCP servers configured for the session, with their connection status and host-level state. */
declare interface McpServerList {
    /** Host-level state, omitted when no MCP host is initialized. */
    host?: McpHostState;
    /** Configured MCP servers */
    servers: McpServer_2[];
}

/** Recorded MCP server pending-auth state. */
declare interface McpServerNeedsAuthInfo {
    /** epoch-ms timestamp at which the server signalled it needs authentication. */
    timestamp: number;
}

/**
 * Inline OIDC configuration for an MCP server.
 * When truthy, the runtime automatically injects an OIDC token:
 * - Local servers: as GITHUB_COPILOT_OIDC_MCP_TOKEN env var
 * - Remote servers: as a Bearer Authorization header, optionally GITHUB_COPILOT_OIDC_MCP_TOKEN for other headers
 */
declare type MCPServerOIDCConfig = boolean | Record<string, unknown>;

declare interface MCPServersConfig {
    mcpServers: Record<string, MCPServerConfig>;
}

/**
 * Telemetry event emitted when an MCP server setup completes.
 */
declare type McpServerSetupTelemetryEvent = TelemetryEvent<"mcp_server_setup", {
    properties: {
        /**
         * SHA-256 hash of the MCP server name.
         */
        serverName: string;
        /**
         * The type of server: "local", "stdio", "http", "sse", or "memory".
         */
        serverType: string;
        /**
         * Whether this is a default server provided by the runtime.
         */
        isDefaultServer: string;
        /**
         * Whether the connection was successful.
         */
        success: string;
        /**
         * Optional correlation identifier (typically the SDK session ID)
         * shared across all status emissions for the same logical agent
         * session. Lets callers join multiple `mcp_server_setup` events
         * — and the matching log lines — for one session.
         */
        sessionId?: string;
    };
    restrictedProperties: {
        /**
         * The raw (unhashed) name of the MCP server.
         */
        serverName: string;
    };
    metrics: {
        /**
         * How long the connection took in milliseconds.
         */
        setupDurationMs: number;
    };
}>;

/** Payload of `session.mcp_servers_loaded` listing MCP server status summaries. */
export declare interface McpServersLoadedData {
    /** Array of MCP server status summaries */
    servers: McpServersLoadedServer[];
}

/** Session event "session.mcp_servers_loaded". Payload of `session.mcp_servers_loaded` listing MCP server status summaries. */
declare interface McpServersLoadedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.mcp_servers_loaded` listing MCP server status summaries. */
    data: McpServersLoadedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.mcp_servers_loaded". */
    type: "session.mcp_servers_loaded";
}
export { McpServersLoadedEvent }
export { McpServersLoadedEvent as SessionMcpServersResolvedEvent }

/** A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata. */
export declare interface McpServersLoadedServer {
    /** Error message if the server failed to connect */
    error?: string;
    /** Server name (config key) */
    name: string;
    /** Name of the plugin that supplied the effective MCP server config, only when source is plugin */
    pluginName?: string;
    /** Version of the plugin that supplied the effective MCP server config, only when source is plugin */
    pluginVersion?: string;
    /** Configuration source: user, workspace, plugin, or builtin */
    source?: McpServerSource;
    /** Connection status: connected, failed, needs-auth, pending, disabled, stopped, or not_configured */
    status: McpServerStatus;
    /** Transport mechanism: stdio, http, sse (deprecated), or memory (in-process MCP server) */
    transport?: McpServerTransport;
}

/** Configuration source: user, workspace, plugin, or builtin */
export declare type McpServerSource = "user" | "workspace" | "plugin" | "builtin";

/** Configuration source: user, workspace, plugin, or builtin */
declare type McpServerSource_2 = "user" | "workspace" | "plugin" | "builtin";

/** Connection status: connected, failed, needs-auth, pending, disabled, stopped, or not_configured */
export declare type McpServerStatus = "connected" | "failed" | "needs-auth" | "pending" | "disabled" | "stopped" | "not_configured";

/** Connection status: connected, failed, needs-auth, pending, disabled, stopped, or not_configured */
declare type McpServerStatus_2 = "connected" | "failed" | "needs-auth" | "pending" | "disabled" | "stopped" | "not_configured";

/** Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. */
export declare interface McpServerStatusChangedData {
    /** Error message if the server entered a failed state */
    error?: string;
    /** Name of the MCP server whose status changed */
    serverName: string;
    /** Connection status: connected, failed, needs-auth, pending, disabled, stopped, or not_configured */
    status: McpServerStatus;
}

/** Session event "session.mcp_server_status_changed". Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. */
declare interface McpServerStatusChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. */
    data: McpServerStatusChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.mcp_server_status_changed". */
    type: "session.mcp_server_status_changed";
}
export { McpServerStatusChangedEvent }
export { McpServerStatusChangedEvent as SessionMcpServerStatusChangedEvent }

/** Transport mechanism: stdio, http, sse (deprecated), or memory (in-process MCP server) */
export declare type McpServerTransport = "stdio" | "http" | "sse" | "memory";

/** How environment-variable values supplied to MCP servers are resolved. "direct" passes literal string values; "indirect" treats values as references (e.g. names of environment variables on the host) that the runtime resolves before launch. Defaults to the runtime's startup mode; clients that intentionally launch MCP servers with literal values (e.g. CLI prompt mode and ACP) set this to "direct". */
declare type McpSetEnvValueModeDetails = "direct" | "indirect";

/** Mode controlling how MCP server env values are resolved (`direct` or `indirect`). */
declare interface McpSetEnvValueModeParams {
    /** How environment-variable values supplied to MCP servers are resolved. "direct" passes literal string values; "indirect" treats values as references (e.g. names of environment variables on the host) that the runtime resolves before launch. Defaults to the runtime's startup mode; clients that intentionally launch MCP servers with literal values (e.g. CLI prompt mode and ACP) set this to "direct". */
    mode: McpSetEnvValueModeDetails;
}

/** Env-value mode recorded on the session after the update. */
declare interface McpSetEnvValueModeResult {
    /** Mode recorded on the session after the update */
    mode: McpSetEnvValueModeDetails;
}

/** Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. */
declare interface McpStartServerRequest {
    /** MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server with its already-registered configuration (config-free start-by-name). */
    config?: McpServerConfig;
    /** Name of the MCP server to start */
    serverName: string;
}

/** MCP server startup filtering result. */
declare interface McpStartServersResult {
    /** Non-default servers allowed by policy */
    allowedServers?: McpAllowedServer[];
    /** Servers filtered out before startup */
    filteredServers: McpFilteredServer[];
}

/** Server name for an individual MCP server stop. */
declare interface McpStopServerRequest {
    /** Name of the MCP server to stop */
    serverName: string;
}

/**
 * MCP-task-specific data captured from `Task` schema messages and progress
 * notifications when an agent represents an in-flight MCP task.
 */
declare interface McpTaskInfo {
    /** MCP task ID returned by the server. */
    taskId: string;
    /** Latest task status. */
    status: "working" | "input_required" | "completed" | "failed" | "cancelled" | "paused";
    /** Optional human-readable status message. */
    statusMessage?: string;
    /** Server-requested time-to-live (ms) for this task from creation. */
    ttlMs?: number;
    /** Server-suggested polling interval (ms) for `getTask`. */
    pollIntervalMs?: number;
    /** Server's reported task creation timestamp (ISO-8601). */
    createdAt?: string;
    /** Server's reported last update timestamp (ISO-8601). */
    lastUpdatedAt?: string;
    /** Numeric progress value from the most recent progress notification. */
    progress?: number;
    /** Total for the progress numerator, when known. */
    progressTotal?: number;
}

declare type MCPTelemetryCallback = (event: McpServerSetupTelemetryEvent | McpProxySecretMaskingSkippedEvent) => Promise<void>;

declare interface McpToolCallInterceptor {
    (input: McpToolCallInterceptorInput): Promise<{
        metaToUse?: Record<string, unknown> | null;
    } | void>;
    hasHooks?: () => boolean;
}

declare type McpToolCallInterceptorInput = {
    toolCallId?: string;
    serverName: string;
    toolName: string;
    arguments: Record<string, unknown>;
    _meta?: Record<string, unknown>;
};

/** MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery metadata. */
declare interface McpTools {
    /** Tool description, when provided. */
    description?: string;
    /** Tool name. */
    name: string;
    /** Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` block was present without recognized fields. */
    ui?: McpToolUi;
}

/** Session event "mcp.tools.list_changed". Payload identifying the MCP server associated with a list change. */
export declare interface McpToolsListChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload identifying the MCP server associated with a list change. */
    data: McpListChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "mcp.tools.list_changed". */
    type: "mcp.tools.list_changed";
}

declare interface McpToolSnapshotCache {
    readonly path: string;
    identity(serverName: string, serverConfig: MCPServerConfig, effectiveLocalCwd?: string): string;
    load(): Promise<{
        snapshots: PersistedMcpToolSnapshots | undefined;
        warnings: readonly string[];
    }>;
    updateServer(cacheIdentity: string, serverName: string, tools: readonly Readonly<LenientToolInfo>[]): Promise<void>;
}

/** Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. */
declare interface McpToolUi {
    /** URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use `session.mcp.resources.read` to fetch its HTML and resource metadata. */
    resourceUri?: string;
    /** Tool visibility advertised by the server. When absent, MCP Apps defaults apply. */
    visibility?: McpToolUiVisibility[];
}

/** Consumer allowed to call an MCP tool. */
declare type McpToolUiVisibility = "model" | "app";

declare abstract class MCPTransport<ToolsProviderT = unknown> {
    protected readonly logger: RunnerLoggerContract_3;
    protected readonly coreHandle: number;
    protected callbacks: McpTransportCallbacks;
    protected constructor(settings: RuntimeSettings_2, logger: RunnerLoggerContract_3, cacheProviderTools?: boolean);
    setMcpAppsEnabled(enabled: boolean): void;
    setFidesIfcEnabled(enabled: boolean | undefined): void;
    setCallbacks(callbacks: McpTransportCallbacks): void;
    dispose(): void;
    loadTools(provider: ToolsProviderT): Promise<Tool[]>;
    refreshProvider(provider: ToolsProviderT): Promise<Tool[]>;
    protected abstract loadDescriptors(provider: ToolsProviderT): Promise<RustMcpToolDescriptor[]>;
    abstract invokeTool(toolId: string, toolParams: Record<string, unknown>, filterMode?: ContentFilterMode, toolCallId?: string, customAgentName?: string): Promise<ToolResultExpanded>;
    protected syncSecretFilter(): void;
    protected attachLiveInvokeCallbacks(descriptors: ReadonlyArray<RustMcpToolDescriptor>): Tool[];
    protected invokeDescriptorTool(toolId: string, toolParams: Record<string, unknown>, filterMode: ContentFilterMode, toolCallId?: string): Promise<ToolResultExpanded>;
}

declare type McpTransportCallbacks = {
    onPermission?: (request: RuntimeNative_2.McpPermissionRequest) => Promise<RuntimeNative_2.McpPermissionResponse>;
    onMetadata?: (request: RuntimeNative_2.McpMetadataRequest) => Promise<RuntimeNative_2.McpMetadataResponse>;
    onOauth?: (request: RuntimeNative_2.McpOAuthRequest) => Promise<RuntimeNative_2.McpOAuthResponse>;
    onElicitation?: (request: RuntimeNative_2.McpElicitationRequest) => Promise<RuntimeNative_2.McpElicitationResponse>;
    onProgress?: (event: RuntimeNative_2.McpProgressEvent) => void;
    onTaskStart?: (request: RuntimeNative_2.McpTaskStartRequest) => Promise<RuntimeNative_2.McpTaskStartResponse>;
    onTaskUpdate?: (event: RuntimeNative_2.McpTaskUpdateEvent) => void;
    onReauthRequired?: (event: RuntimeNative_2.McpReauthRequiredEvent) => void;
};

/**
 * Resolved MCP App UI resource fetched via `resources/read` for a `ui://` URI.
 * Either `text` or `blob` is populated; `mimeType` is typically `text/html` or
 * `text/html;profile=mcp-app`.
 */
declare interface McpUiResource {
    uri: string;
    mimeType: string;
    text?: string;
    blob?: string;
    _meta?: {
        ui?: McpUiResourceMeta;
    };
}

/** CSP directives that the host SHOULD apply to the rendered iframe. */
declare interface McpUiResourceCsp {
    connectDomains?: string[];
    resourceDomains?: string[];
    frameDomains?: string[];
    baseUriDomains?: string[];
}

/** Resource-level `_meta.ui` block — render hints and sandbox policy. */
declare interface McpUiResourceMeta {
    csp?: McpUiResourceCsp;
    permissions?: McpUiResourcePermissions;
    domain?: string;
    prefersBorder?: boolean;
}

/** Iframe permissions the resource requests; presence = requested. */
declare interface McpUiResourcePermissions {
    camera?: Record<string, unknown>;
    microphone?: Record<string, unknown>;
    geolocation?: Record<string, unknown>;
    clipboardWrite?: Record<string, unknown>;
}

/**
 * Tool-level `_meta.ui` block (SEP-1865).
 * Linked to a UI resource via `resourceUri` (typically `ui://...`).
 * `visibility` controls who can call the tool — `["app"]` hides it from the LLM
 * tool list while keeping it callable through the host's MCP App proxy.
 */
declare interface McpUiToolMeta {
    resourceUri?: string;
    visibility?: McpUiVisibility[];
}

/** Visibility for an MCP-Apps-aware tool. Defaults to ["model", "app"] when absent. */
declare type McpUiVisibility = "model" | "app";

/** Server name identifying the external client to remove. */
declare interface McpUnregisterExternalClientRequest {
    /** Server name of the external client to unregister */
    serverName: string;
}

declare type MemoriesPromptResult = Native.MemoryPromptResultData;

declare type MemoryApiCache = {
    promise?: Promise<MemoryApiCacheResult>;
    promiseRepoName?: string;
    result?: MemoryApiCacheResult;
    /** Epoch milliseconds when `result` was populated, used to expire the cache
     *  after a TTL so long-lived sessions pick up memories mutated by other
     *  sessions or during idle time. */
    fetchedAt?: number;
};

declare type MemoryApiCacheResult = {
    enabled: boolean;
    repoName?: string;
} & Partial<MemoriesPromptResult>;

/** Signal-only event: the agent successfully stored a memory (store_memory) or voted on one (vote_memory). No payload — consumers should re-fetch memories to pick up the change. Used to refresh memory context (e.g. re-running the context sidekick) so newly written memories surface in subsequent turns. */
export declare interface MemoryChangedData {
}

/** Session event "session.memory_changed". Signal-only event: the agent successfully stored a memory (store_memory) or voted on one (vote_memory). No payload — consumers should re-fetch memories to pick up the change. Used to refresh memory context (e.g. re-running the context sidekick) so newly written memories surface in subsequent turns. */
export declare interface MemoryChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Signal-only event: the agent successfully stored a memory (store_memory) or voted on one (vote_memory). No payload — consumers should re-fetch memories to pick up the change. Used to refresh memory context (e.g. re-running the context sidekick) so newly written memories surface in subsequent turns. */
    data: MemoryChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.memory_changed". */
    type: "session.memory_changed";
}

/** Memory configuration for this session. */
declare interface MemoryConfiguration {
    /** Whether memory is enabled for the session. */
    enabled: boolean;
}

/**
 * A permission request for a memory operation (store or vote).
 *
 * When `action` is `"store"`: `subject`, `fact`, and `citations` are present.
 * When `action` is `"vote"`: `fact`, `direction`, and `reason` are present.
 *
 * Prefer using {@link StoreMemoryPermissionRequest} or {@link VoteMemoryPermissionRequest}
 * at construction sites for stricter compile-time enforcement.
 *
 * This flat shape is kept for compatibility with the Zod-inferred event schema type
 * (Zod v3 can't model nested discriminated unions).
 */
declare type MemoryPermissionRequest = {
    readonly kind: "memory";
    readonly action: "store" | "vote";
    /** The subject of the memory being stored (store only) */
    readonly subject?: string;
    /** The fact being stored or voted on */
    readonly fact: string;
    /** The source citations for the fact (store only) */
    readonly citations?: string;
    /** The vote direction (vote only) */
    readonly direction?: "upvote" | "downvote";
    /** The reason for the vote (vote only) */
    readonly reason?: string;
    /** The scope of the memory being stored */
    readonly scope?: "repository" | "user";
    /**
     * The repository the memory is associated with, as an `owner/repo` "name
     * with owner" (NWO) string. See {@link StoreMemoryPermissionRequest.repoNwo}.
     */
    readonly repoNwo?: string;
    readonly autoApproval?: AutoApproval;
};

/**
 * All types of message events that can be emitted by the `Client`.
 * Model clients are expected to emit assistant messages, tool results, and
 * runtime-injected user messages only. System/developer prompts are session-owned
 * input artifacts surfaced via `system.message` session events instead.
 */
declare type MessageEvent_2 = {
    kind: "message";
    turn?: number;
    callId?: string;
    modelCall?: ModelCallParam;
    message: ChatCompletionMessageParam & ReasoningMessageParam_2;
} | AssistantMessageEvent_2 | UserMessageEvent_2 | ToolMessageEvent;

declare type MessageExtraInfo = unknown;

declare type MessageSource = {
    readonly kind: "skill";
    readonly name: string;
    readonly pluginName?: string;
    readonly summary?: string;
} | {
    readonly kind: "subagent";
    readonly name: string;
    readonly summary?: string;
} | {
    readonly kind: "mcp";
    readonly server: string;
    readonly pluginName?: string;
    readonly summary?: string;
} | {
    readonly kind: "tool";
    readonly name: string;
    readonly summary?: string;
};

/**
 * Emitted at the end of a getCompletionWithTools call with the final internal
 * messages array (including the system message). Consumers can use this to
 * obtain the exact messages the LLM saw — after truncation, compaction, and
 * other preRequest processor mutations — so that follow-up calls (e.g. PR
 * description generation) can reuse the same prefix and preserve prompt
 * caching.
 */
declare type MessagesSnapshotEvent = {
    kind: "messages_snapshot";
    messages: ChatCompletionMessageParam[];
};

/** Per-source attribution breakdown for the session's current context window, or null if uninitialized. */
declare interface MetadataContextAttributionResult {
    /** Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). */
    contextAttribution: SessionContextAttribution;
}

/** Parameters for the heaviest-messages query. */
declare interface MetadataContextHeaviestMessagesRequest {
    /** Maximum number of messages to return, most-expensive first. Omit for the server default. */
    limit?: number;
}

/** The heaviest individual messages in the session's context window, most-expensive first. */
declare interface MetadataContextHeaviestMessagesResult {
    /** Heaviest messages, most-expensive first. */
    messages: ContextHeaviestMessage[];
    /** Total token count of the current context window, so callers can compute each message's share without a second call. */
    totalTokens: number;
}

/** Model identifier and token limits used to compute the context-info breakdown. */
declare interface MetadataContextInfoRequest {
    /** Maximum output tokens allowed by the target model. Pass 0 if unknown. */
    outputTokenLimit: number;
    /** Maximum prompt tokens allowed by the target model. Pass 0 to use the runtime default. */
    promptTokenLimit: number;
    /** Model identifier used for tokenization. Omit to use the session default. Used both for token counting and to compute display values. */
    selectedModel?: string;
}

/** Token breakdown for the session's current context window, or null if uninitialized. */
declare interface MetadataContextInfoResult {
    /** Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). */
    contextInfo: SessionContextInfo;
}

/** Indicates whether the local session is currently processing a turn or background continuation. */
declare interface MetadataIsProcessingResult {
    /** Whether the session is currently processing user/agent messages. False for non-local sessions (which don't run a local agentic loop). Reflects an in-flight turn or background continuation. */
    processing: boolean;
}

/** Model identifier to use when re-tokenizing the session's existing messages. */
declare interface MetadataRecomputeContextTokensRequest {
    /** Model identifier used for tokenization. The runtime token-counts both chat-context and system-context messages against this model. */
    modelId: string;
}

/** Re-tokenize the session's existing messages against `modelId` and return the token totals. Useful for hosts that want an initial estimate of context usage on session resume, before the next agent turn fires `session.context_info_changed` events. Returns zeros for an empty session. */
declare interface MetadataRecomputeContextTokensResult {
    /** Tokens contributed by user/assistant/tool messages (excludes system/developer prompts). */
    messagesTokenCount: number;
    /** Tokens contributed by system/developer prompt snapshots. */
    systemTokenCount: number;
    /** Sum of tokens across chat-context and system-context messages currently held by the session. */
    totalTokens: number;
}

/** Updated working-directory/git context to record on the session. */
declare interface MetadataRecordContextChangeRequest {
    /** Updated working directory and git context. Emitted as the new payload of `session.context_changed`. */
    context: SessionWorkingDirectoryContext;
}

/** Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). For a local session, a report whose `cwd` diverges from the session's current working directory is ignored (the call still succeeds but records nothing and emits no event); move a local session's working directory via `metadata.setWorkingDirectory` instead. */
declare interface MetadataRecordContextChangeResult {
}

/** Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. */
declare interface MetadataSetWorkingDirectoryRequest {
    /** Absolute path to set as the session's working directory. The runtime updates the session's recorded cwd so subsequent operations (shell tools, file lookups, telemetry) anchor to it. */
    workingDirectory: string;
}

/** Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. */
declare interface MetadataSetWorkingDirectoryResult {
    /** Working directory after the update */
    workingDirectory: string;
}

/** The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot') */
declare type MetadataSnapshotCurrentMode = "interactive" | "plan" | "autopilot";

/** Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. */
declare interface MetadataSnapshotRemoteMetadata {
    /** The pull request number the remote session is associated with, if any. */
    pullRequestNumber?: number;
    /** The repository the remote session targets. */
    repository: MetadataSnapshotRemoteMetadataRepository;
    /** The original resource identifier (task ID or PR node ID), preserved across event-replay reconstructions. Falls back to `sessionId` when absent. */
    resourceId?: string;
    /** Whether the remote task originated from Copilot Coding Agent (cca) or a CLI `--remote` invocation. */
    taskType?: MetadataSnapshotRemoteMetadataTaskType;
}

/** The repository the remote session targets. */
declare interface MetadataSnapshotRemoteMetadataRepository {
    /** The branch the remote session is operating on. */
    branch: string;
    /** The GitHub repository name (without owner). */
    name: string;
    /** The GitHub owner (user or organization) of the target repository. */
    owner: string;
}

/** Whether the remote task originated from Copilot Coding Agent (cca) or a CLI `--remote` invocation. */
declare type MetadataSnapshotRemoteMetadataTaskType = "cca" | "cli";

/** Agent mode change details including previous and new modes */
export declare interface ModeChangedData {
    /** The session mode the agent is operating in */
    newMode: SessionMode;
    /** The session mode the agent is operating in */
    previousMode: SessionMode;
}

/** Session event "session.mode_changed". Agent mode change details including previous and new modes */
declare interface ModeChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Agent mode change details including previous and new modes */
    data: ModeChangedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.mode_changed". */
    type: "session.mode_changed";
}
export { ModeChangedEvent }
export { ModeChangedEvent as SessionModeChangedEvent }

declare type Model = {
    id: string;
    name: string;
    preview?: boolean;
    vendor?: string;
    capabilities: {
        family?: string;
        supports: {
            streaming?: boolean;
            tool_calls?: boolean;
            vision?: boolean;
            /**
             * Resolved Anthropic adaptive-thinking capability for this model:
             * - `"unsupported"`: the model rejects `thinking.type = "adaptive"`.
             * - `"optional"`: the model accepts adaptive thinking and also
             *   accepts `thinking.type = "enabled"` (dual-mode).
             * - `"required"`: the model only accepts adaptive thinking and
             *   rejects `thinking.type = "enabled"` with HTTP 400 (e.g.
             *   opus-4.7/4.8).
             *
             * CAPI serves a single boolean which the runtime reconciles into
             * this enum; otherwise the runtime fills it in from the
             * programmatic capability-default switch. A host
             * `ModelCapabilitiesOverride` takes precedence over both.
             */
            adaptive_thinking?: AdaptiveThinkingSupport;
            /**
             * Reasoning effort levels accepted by CAPI for this model
             * (e.g., `["low", "medium", "high"]`). When present and non-empty,
             * the runtime intersects this with its locally configured
             * `supportedReasoningEfforts` so we never offer an effort CAPI
             * won't accept. A missing field or empty list is treated as
             * "no info" — the local list is used as-is.
             */
            reasoning_effort?: string[];
        };
        limits: {
            max_prompt_tokens?: number;
            max_output_tokens?: number;
            max_context_window_tokens: number;
            vision?: {
                supported_media_types: string[];
                max_prompt_images: number;
                max_prompt_image_size: number;
            };
        };
    };
    supported_endpoints?: string[];
    policy?: {
        state: "enabled" | "disabled" | "unconfigured";
        terms?: string;
    };
    billing?: {
        multiplier?: number;
        restricted_to?: string[];
        /** Token-level pricing information from CAPI. */
        token_prices?: FlatTokenPrices | TieredTokenPrices;
        /**
         * Optional server-driven promotion for this model. When present with an
         * active `ends_at` (UTC, in the future), the picker hoists the model
         * above the other concrete models (the "Auto" row intentionally stays
         * first) and surfaces the promo message/discount. `message` carries only
         * the base promo text; the client formats `ends_at` into a
         * human-readable expiry and appends it at display time.
         */
        promo?: {
            id?: string;
            discount_percent?: number;
            ends_at?: string;
            message?: string;
        };
    };
    /** Model category for the model picker (e.g., lightweight, versatile, powerful). */
    model_picker_category?: "lightweight" | "versatile" | "powerful";
    /** Price category for the model picker (e.g., low, medium, high, very_high). */
    model_picker_price_category?: "low" | "medium" | "high" | "very_high";
    custom_model?: CustomModelMetadata;
    /**
     * Issues that may prevent the model from being used by certain consumers.
     * Populated by the local enrichment layer — CAPI never sends this field.
     * Each entry has a machine-readable `code` and a human-readable `message`.
     */
    issues?: {
        code: string;
        message: string;
    }[];
    /**
     * Warning messages from CAPI about this model.
     * Each entry has a machine-readable `code` and a human-readable `message`.
     * Codes include `client_version_deprecated`, `model_degraded_provider`,
     * `model_degraded_github`, and `model_high_usage`.
     */
    warning_messages?: {
        code: string;
        message: string;
    }[];
};

/** Copilot model metadata, including identifier, display name, capabilities, policy, billing, reasoning efforts, and picker categories. */
declare interface Model_2 {
    /** Billing information */
    billing?: ModelBilling;
    /** Model capabilities and limits */
    capabilities: ModelCapabilities;
    /** Model identifier (e.g., "claude-sonnet-4.5") */
    id: string;
    /** Model capability category for grouping in the model picker */
    modelPickerCategory?: ModelPickerCategory;
    /** Relative cost tier for token-based billing users */
    modelPickerPriceCategory?: ModelPickerPriceCategory;
    /** Display name */
    name: string;
    /** Policy state (if applicable) */
    policy?: ModelPolicy;
    /** Supported reasoning effort levels (only present if model supports reasoning effort) */
    supportedReasoningEfforts?: string[];
}

/** Billing information */
declare interface ModelBilling {
    /** Whole-number percentage discount (0-100) applied to usage billed through this model. Populated for the synthetic `auto` model, where requests routed by auto-mode are billed at a reduced rate; absent for concrete models. */
    discountPercent?: number;
    /** Billing cost multiplier relative to the base rate */
    multiplier?: number;
    /** Active server-driven promotion for this model, if any. Present when the model is being promoted with a discount, which may be time-boxed or open-ended. */
    promo?: ModelBillingPromo;
    /** Token-level pricing information for this model */
    tokenPrices?: ModelBillingTokenPrices;
}

/** Active server-driven promotion for a model, including its discount and optional expiry. */
declare interface ModelBillingPromo {
    /** Percentage discount (0-100) applied while the promotion is active. May be fractional. */
    discountPercent?: number;
    /** UTC ISO 8601 timestamp marking when the promotion ends. Optional: an open-ended promotion omits this field. When present, the API only surfaces a promo whose expiry parses and is in the future, so consumers should treat a past value as expired. */
    endsAt?: string;
    /** Stable identifier for the promotion campaign. */
    id?: string;
    /** Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it when present. */
    message?: string;
}

/** Token-level pricing information for this model */
declare interface ModelBillingTokenPrices {
    /** Number of tokens per standard billing batch */
    batchSize?: number;
    /**
     * Use cacheReadPrice instead. AI Credits cost per billing batch of cached tokens
     * @deprecated
     */
    cachePrice?: number;
    /** AI Credits cost per billing batch of cached (read) tokens */
    cacheReadPrice?: number;
    /** AI Credits cost per billing batch of cache-write (cache creation) tokens. */
    cacheWritePrice?: number;
    /**
     * Use maxPromptTokens instead. Prompt token budget for the default tier. The total context window is this value plus the model's max_output_tokens.
     * @deprecated
     */
    contextMax?: number;
    /** AI Credits cost per billing batch of input tokens */
    inputPrice?: number;
    /** Long context tier pricing (available for models with extended context windows) */
    longContext?: ModelBillingTokenPricesLongContext;
    /** Prompt token budget for the default tier. The total context window is this value plus the model's max_output_tokens. */
    maxPromptTokens?: number;
    /** AI Credits cost per billing batch of output tokens */
    outputPrice?: number;
}

/** Long context tier pricing (available for models with extended context windows) */
declare interface ModelBillingTokenPricesLongContext {
    /**
     * Use cacheReadPrice instead. AI Credits cost per billing batch of cached tokens
     * @deprecated
     */
    cachePrice?: number;
    /** AI Credits cost per billing batch of cached (read) tokens */
    cacheReadPrice?: number;
    /** AI Credits cost per billing batch of cache-write (cache creation) tokens. */
    cacheWritePrice?: number;
    /**
     * Use maxPromptTokens instead. Prompt token budget for the long context tier. The total context window is this value plus the model's max_output_tokens.
     * @deprecated
     */
    contextMax?: number;
    /** AI Credits cost per billing batch of input tokens */
    inputPrice?: number;
    /** Prompt token budget for the long context tier. The total context window is this value plus the model's max_output_tokens. */
    maxPromptTokens?: number;
    /** AI Credits cost per billing batch of output tokens */
    outputPrice?: number;
}

/** For HTTP 400 failures only: whether the response carried a structured CAPI error envelope (structured_error, a deterministic validation failure) or no error body (bodyless, the transient gateway/proxy signature). Absent for non-400 failures. */
export declare type ModelCallFailureBadRequestKind = "bodyless" | "structured_error";

/** Failed LLM API call metadata for telemetry */
export declare interface ModelCallFailureData {
    /** Completion ID from the model provider (e.g., chatcmpl-abc123) */
    apiCallId?: string;
    /** API endpoint used for this model call, matching CAPI supported_endpoints vocabulary */
    apiEndpoint?: AssistantUsageApiEndpoint;
    /** For HTTP 400 failures only: whether the response carried a structured CAPI error envelope (structured_error, a deterministic validation failure) or no error body (bodyless, the transient gateway/proxy signature). Absent for non-400 failures. */
    badRequestKind?: ModelCallFailureBadRequestKind;
    /** Duration of the failed API call in milliseconds */
    durationMs?: number;
    /** For HTTP 400 failures only: the `code` from the CAPI error envelope (e.g. 'model_max_prompt_tokens_exceeded') identifying which deterministic validation failure occurred. Raw server-controlled string, emitted only through restricted telemetry. Absent for bodyless or non-400 failures. */
    errorCode?: string;
    /** Raw provider/runtime error message for restricted telemetry */
    errorMessage?: string;
    /** For HTTP 400 failures only: the `type` from the CAPI error envelope (e.g. 'websocket_error'), a coarser companion to errorCode for envelopes that carry no code. Raw server-controlled string, emitted only through restricted telemetry. Absent for bodyless or non-400 failures. */
    errorType?: string;
    /** Whether the failure originated from an API response or the request transport */
    failureKind?: ModelCallFailureKind;
    /** What initiated this API call (e.g., "sub-agent", "mcp-sampling"); absent for user-initiated calls */
    initiator?: string;
    /** Whether the session selected Auto mode for the failed call */
    isAuto?: boolean;
    /** Whether the failed call used a bring-your-own-key provider */
    isByok?: boolean;
    /** Effective maximum output-token limit for the failed call */
    maxOutputTokens?: number;
    /** Effective maximum prompt-token limit for the failed call */
    maxPromptTokens?: number;
    /** Model identifier used for the failed API call */
    model?: string;
    /** GitHub request tracing ID (x-github-request-id header) for server-side log correlation */
    providerCallId?: string;
    /** Per-quota usage snapshots parsed from the failed response's quota headers, keyed by quota identifier. Present when the error response carried quota headers (e.g. a 402 once the additional spend limit is reached) so the UI can refresh the quota display on failure. */
    quotaSnapshots?: Record<string, AssistantUsageQuotaSnapshot>;
    /** Reasoning effort level used for the failed model call, if applicable */
    reasoningEffort?: string;
    /** Content-free structural summary of the failing request. Contains only counts and shape flags (no prompt content), so it is safe for unrestricted telemetry. Populated only for client-error (4xx) failures. */
    requestFingerprint?: ModelCallFailureRequestFingerprint;
    rte?: boolean;
    /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */
    serviceRequestId?: string;
    /** Where the failed model call originated */
    source: ModelCallFailureSource;
    /** HTTP status code from the failed request */
    statusCode?: number;
    /** Transport used for the failed model call (http or websocket) */
    transport?: ModelCallFailureTransport;
}

/** Session event "model.call_failure". Failed LLM API call metadata for telemetry */
declare interface ModelCallFailureEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Failed LLM API call metadata for telemetry */
    data: ModelCallFailureData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "model.call_failure". */
    type: "model.call_failure";
}
export { ModelCallFailureEvent }
export { ModelCallFailureEvent as ModelCallFailureSessionEvent }

declare type ModelCallFailureEvent_2 = {
    kind: "model_call_failure";
    turn: number;
    callId?: string;
    modelCallDurationMs: number;
    /** The effective reasoning effort used for this model call, when applicable. */
    reasoningEffort?: ReasoningEffort;
    /**
     * The model call that failed, if available.
     */
    modelCall: ModelCallParam;
    /**
     * A string representation of the messages sent as input to the model call, if available.
     */
    requestMessages?: string;
    /**
     * Per-quota usage snapshots parsed from the failed response's quota headers, if present.
     * Lets the UI refresh the quota display even when a request fails (e.g. a 402 once the
     * additional spend limit is reached).
     */
    quotaSnapshots?: Record<string, QuotaSnapshot>;
    rte?: boolean;
};

declare type ModelCallFailureEvent_3 = Extract<Event_2, {
    kind: "model_call_failure";
}>;

/** Boundary that produced a model call failure */
export declare type ModelCallFailureKind = "api" | "transport";

/** Content-free structural summary of the failing request for diagnosing malformed 4xx calls */
export declare interface ModelCallFailureRequestFingerprint {
    /** Total number of image content parts */
    imagePartCount: number;
    /** Image parts whose media type cannot be determined (rejected by strict providers) */
    imagePartsMissingMediaType: number;
    /** Role of the final message in the request */
    lastMessageRole?: string;
    /** Total number of messages in the request */
    messageCount: number;
    /** Tool calls whose name is missing or empty (rejected by strict providers) */
    namelessToolCallCount: number;
    /** Total number of tool calls across assistant messages */
    toolCallCount: number;
    /** Number of "tool" result messages in the request */
    toolResultMessageCount: number;
}

/** Where the failed model call originated */
export declare type ModelCallFailureSource = "top_level" | "subagent" | "mcp_sampling";

/** Transport used for a failed model call */
export declare type ModelCallFailureTransport = "http" | "websocket";

declare interface ModelCallParam {
    api_id?: string;
    model?: string;
    api_endpoint?: CopilotAPIEndpoint;
    transport?: "http" | "websocket";
    failure_kind?: "api" | "transport";
    error?: string;
    status?: number;
    request_id?: string;
    client_request_id?: string;
    service_request_id?: string;
    rte?: boolean;
    initiator?: string;
    /**
     * For HTTP 400 failures only: whether the response carried a structured CAPI
     * error envelope ("structured_error", a deterministic validation failure such
     * as a token-limit or schema violation) or no error body ("bodyless", the
     * transient gateway/proxy signature). Absent for non-400 failures.
     * A known-ahead enum, so safe for unrestricted telemetry.
     */
    badRequestKind?: BadRequestKind;
    /**
     * For HTTP 400 failures only: the `code` field from the CAPI error envelope
     * (e.g. "model_max_prompt_tokens_exceeded"), identifying which deterministic
     * validation failure occurred. A raw server-controlled string (not a
     * known-ahead enum), so it is emitted only through restricted telemetry.
     * Length-capped defensively. Absent for bodyless or non-400 failures.
     */
    errorCode?: string;
    /**
     * For HTTP 400 failures only: the `type` field from the CAPI error envelope
     * (e.g. "websocket_error", "invalid_request_error"), a coarser companion to
     * {@link ModelCallParam.errorCode} that categorizes envelopes carrying no
     * `code`. Same raw server-controlled / restricted-only handling as `errorCode`.
     */
    errorType?: string;
}

/** Model API dispatch metadata for internal telemetry */
export declare interface ModelCallStartData {
    /** Model identifier used for this API call, when known */
    model?: string;
    /** Previous response or interaction identifier included in the model request, when present */
    previousResponseId?: string;
    /** Identifier of the assistant turn that initiated the model call */
    turnId: string;
}

declare type ModelCallStartedEvent = {
    kind: "model_call_started";
    model: string;
    modelInfo: object;
    turn: number;
    timestampMs: number;
    previousResponseId?: string;
};

/** Session event "model.call_start". Model API dispatch metadata for internal telemetry */
export declare interface ModelCallStartEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Model API dispatch metadata for internal telemetry */
    data: ModelCallStartData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "model.call_start". */
    type: "model.call_start";
}

declare type ModelCallSuccessEvent = {
    kind: "model_call_success";
    turn: number;
    callId?: string;
    modelCallDurationMs: number;
    /**
     * Time to first token in milliseconds. Only available for streaming requests.
     */
    ttftMs?: number;
    /**
     * Average inter-token latency in milliseconds. Only available for streaming requests.
     * Calculated as the average time between successive tokens.
     */
    interTokenLatencyMs?: number;
    modelCall: ModelCallParam;
    responseChunk: CopilotChatCompletionChunk;
    responseUsage: ModelResponseUsage | undefined;
    /**
     * A string representation of the messages sent as input to the model call, if available.
     */
    requestMessages?: string;
    quotaSnapshots?: Record<string, QuotaSnapshot>;
    /**
     * GitHub's request tracing ID (x-github-request-id header) for this model call.
     */
    requestId?: string;
    /**
     * Copilot service request ID (x-copilot-service-request-id header) for this model call.
     */
    serviceRequestId?: string;
    rte?: boolean;
    /** Per-request cost/usage data from CAPI (`copilot_usage` response field). */
    copilotUsage?: CopilotUsage;
    /** The reasoning effort level used for this model call, if applicable. */
    reasoningEffort?: ReasoningEffort;
    /** Number of tools sent to the model for this call. */
    toolCount?: number;
    /** Token count from the tool definitions sent to the model for this call. */
    toolTokenCount?: number;
};

/** Model capabilities and limits */
declare interface ModelCapabilities {
    /** Token limits for prompts, outputs, and context window */
    limits?: ModelCapabilitiesLimits;
    /** Feature flags indicating what the model supports */
    supports?: ModelCapabilitiesSupports;
}

/** Token limits for prompts, outputs, and context window */
declare interface ModelCapabilitiesLimits {
    /** Maximum total context window size in tokens */
    max_context_window_tokens?: number;
    /** Maximum number of output/completion tokens */
    max_output_tokens?: number;
    /** Maximum number of prompt/input tokens */
    max_prompt_tokens?: number;
    /** Vision-specific limits */
    vision?: ModelCapabilitiesLimitsVision;
}

/** Vision-specific limits */
declare interface ModelCapabilitiesLimitsVision {
    /** Maximum image size in bytes */
    max_prompt_image_size: number;
    /** Maximum number of images per prompt */
    max_prompt_images: number;
    /** MIME types the model accepts */
    supported_media_types: string[];
}

/**
 * Deep-partial override for model capabilities, derived from {@link Model}.
 * Only non-undefined values are applied over the runtime-resolved capabilities.
 */
declare type ModelCapabilitiesOverride = DeepOptional<Model["capabilities"]>;

/** Optional capability overrides (vision, tool_calls, reasoning, etc.). */
declare interface ModelCapabilitiesOverride_2 {
    /** Token limits for prompts, outputs, and context window */
    limits?: ModelCapabilitiesOverrideLimits;
    /** Feature flags indicating what the model supports */
    supports?: ModelCapabilitiesOverrideSupports;
}

/** Token limits for prompts, outputs, and context window */
declare interface ModelCapabilitiesOverrideLimits {
    /** Maximum total context window size in tokens */
    max_context_window_tokens?: number;
    /** Maximum number of output/completion tokens */
    max_output_tokens?: number;
    /** Maximum number of prompt/input tokens */
    max_prompt_tokens?: number;
    /** Vision-specific limits */
    vision?: ModelCapabilitiesOverrideLimitsVision;
}

/** Vision-specific limits */
declare interface ModelCapabilitiesOverrideLimitsVision {
    /** Maximum image size in bytes */
    max_prompt_image_size?: number;
    /** Maximum number of images per prompt */
    max_prompt_images?: number;
    /** MIME types the model accepts */
    supported_media_types?: string[];
}

/** Feature flags indicating what the model supports */
declare interface ModelCapabilitiesOverrideSupports {
    /** Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). */
    adaptive_thinking?: AdaptiveThinkingSupport_2;
    /** Whether this model supports reasoning effort configuration */
    reasoningEffort?: boolean;
    /** Whether this model supports vision/image input */
    vision?: boolean;
}

/** Feature flags indicating what the model supports */
declare interface ModelCapabilitiesSupports {
    /** Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). */
    adaptive_thinking?: AdaptiveThinkingSupport_2;
    /** Whether this model supports reasoning effort configuration */
    reasoningEffort?: boolean;
    /** Whether this model supports vision/image input */
    vision?: boolean;
}

/** Model change details including previous and new model identifiers */
export declare interface ModelChangeData {
    /** Reason the change happened, when not user-initiated. `"rate_limit_auto_switch"` for changes triggered by the auto-mode-switch rate-limit recovery path, or `"refusal_fallback"` when the active model declined a request (content refusal) and the runtime switched to the configured refusal-fallback model. UI clients can use this to render contextual copy. */
    cause?: string;
    /** Context tier after the model change; null explicitly clears a previously selected tier */
    contextTier?: ContextTier | null;
    /** Newly selected model identifier */
    newModel: string;
    /** Model that was previously selected, if any */
    previousModel?: string;
    /** Reasoning effort level before the model change, if applicable */
    previousReasoningEffort?: string;
    /** Reasoning summary mode before the model change, if applicable */
    previousReasoningSummary?: ReasoningSummary;
    /** Output verbosity level before the model change, if applicable */
    previousVerbosity?: Verbosity;
    /** Reasoning effort level after the model change, if applicable */
    reasoningEffort?: string | null;
    /** Reasoning summary mode after the model change, if applicable */
    reasoningSummary?: ReasoningSummary;
    /** Output verbosity level after the model change, if applicable */
    verbosity?: Verbosity;
}

/** Session event "session.model_change". Model change details including previous and new model identifiers */
declare interface ModelChangeEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Model change details including previous and new model identifiers */
    data: ModelChangeData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.model_change". */
    type: "session.model_change";
}
export { ModelChangeEvent }
export { ModelChangeEvent as SessionModelChangeEvent }

declare interface ModelHint {
    name?: string;
}

/** List of Copilot models available to the resolved user, including capabilities and billing metadata. */
declare interface ModelList {
    /** List of available models with full metadata */
    models: Model_2[];
}

/** Optional listing options. */
declare type ModelListRequest = {
    skipCache?: boolean;
};

/** Model capability category for grouping in the model picker */
declare type ModelPickerCategory = "lightweight" | "versatile" | "powerful";

/** Relative cost tier for token-based billing users */
declare type ModelPickerPriceCategory = "low" | "medium" | "high" | "very_high";

/** Policy state (if applicable) */
declare interface ModelPolicy {
    /** Current policy state for this model */
    state: ModelPolicyState;
    /** Usage terms or conditions for this model */
    terms?: string;
}

/** Current policy state for this model */
declare type ModelPolicyState = "enabled" | "disabled" | "unconfigured";

declare interface ModelPreferences {
    hints?: ModelHint[];
    costPriority?: number;
    speedPriority?: number;
    intelligencePriority?: number;
}

/**
 * OpenAI's CompletionUsage extended with provider-specific token counts.
 * Providers like Anthropic report cache writes as `cache_creation_input_tokens`,
 * while OpenAI reports `cache_write_tokens`. CAPI also reports Gemini reasoning
 * tokens as top-level `reasoning_tokens`; this type carries provider-specific
 * data alongside the standard usage fields so all token counts travel together.
 */
declare type ModelResponseUsage = NonNullable<ChatCompletion["usage"]> & {
    prompt_tokens_details?: {
        /** Tokens written to the prompt cache (e.g. Anthropic's `cache_creation_input_tokens`). */
        cache_creation_tokens?: number;
        /** Internal cache lifetime derived from provider response metadata. */
        cache_ttl_seconds?: number;
    };
    /** Reasoning tokens reported by CAPI for models like Gemini. */
    reasoning_tokens?: number;
};

/** Reasoning effort level to apply to the currently selected model. */
declare interface ModelSetReasoningEffortRequest {
    /** Reasoning effort level to apply to the currently selected model. The host is responsible for validating the value against the model's supported levels before calling. */
    reasoningEffort: string;
}

/** Update the session's reasoning effort without changing the selected model. Use `switchTo` instead when you also need to change the model. The runtime stores the effort on the session and applies it to subsequent turns. */
declare interface ModelSetReasoningEffortResult {
    /** Reasoning effort level recorded on the session after the update */
    reasoningEffort: string;
}

/** Optional GitHub token used to list models for a specific user instead of the global auth context. */
declare type ModelsListRequest = {
    gitHubToken?: string;
};

/**
 * Outcome of a session model switch (`setSelectedModel` / `applyModelChange`).
 *
 * `deferred` is the authoritative signal — captured atomically by the native
 * switch — that the change was ENQUEUED as a cancellable `/model` command
 * (because a turn was active or another model change was already queued) rather
 * than applied to the live session immediately. When `true`, the session's live
 * model is unchanged until the queued change drains; callers must not infer this
 * from a later state re-read, which races concurrent drains.
 */
export declare interface ModelSwitchOutcome {
    deferred: boolean;
}

/** Target model identifier and optional reasoning effort, summary, capability overrides, and context tier. */
declare interface ModelSwitchToRequest {
    /** Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. */
    contextTier?: ContextTier_2;
    /** When true, defer this switch (enqueue it) if another model change is already queued, even when no turn is active — so it drains last (FIFO) and wins over the already-queued change. Intended for genuine user-initiated model selections; internal restore/reapply switches omit it and apply immediately when no turn is active. When no other model change is queued this has no effect (a switch still applies immediately unless a turn is active). */
    deferIfModelChangeQueued?: boolean;
    /** Override individual model capabilities resolved by the runtime */
    modelCapabilities?: ModelCapabilitiesOverride_2;
    /** Model selection id to switch to, as returned by `list`. A bare id (e.g. `claude-sonnet-4.6`) names a Copilot (CAPI) model; a provider-qualified id (`provider/id`, e.g. `acme/claude-sonnet`) targets a registry BYOK model. */
    modelId: string;
    /** Reasoning effort level to use for the model. CAPI values are model-defined and validated against the selected model; BYOK providers may define additional values. "none" disables reasoning. When omitted, no effort override is applied. */
    reasoningEffort?: string;
    /** Reasoning summary mode to request for supported model clients */
    reasoningSummary?: ReasoningSummary_3;
    /** Output verbosity level to request for supported models */
    verbosity?: Verbosity_3;
}

/** The model identifier active on the session after the switch. */
declare interface ModelSwitchToResult {
    /** True when the switch was deferred (enqueued as a cancellable `/model` command) because a turn was active or another model change was already queued, rather than applied immediately. When true, the session's live model is unchanged until the queued change drains. */
    deferred?: boolean;
    /** Currently active model identifier after the switch */
    modelId?: string;
}

/** Agent interaction mode to apply to the session. */
declare interface ModeSetRequest {
    /** The session mode the agent is operating in */
    mode: SessionMode_2;
}

/**
 * A named BYOK provider connection (transport + credentials only), referenced by
 * {@link ProviderModelConfig} entries via {@link NamedProviderConfig.name}.
 *
 * Unlike the single, whole-session `provider` ({@link ProviderConfig}) — which
 * makes the entire session BYOK, bypasses Copilot API authentication, and
 * disables internal session telemetry (and, in the CLI's server mode, the CLI
 * telemetry service too) — named providers are **additive**: they coexist with
 * CAPI auth so models from CAPI and one or more BYOK providers can be mixed
 * within a single session and across sub-agents. Because such a session stays
 * CAPI-authenticated, the whole-session telemetry suppression tied to `provider`
 * does **not** apply here; note that BYOK inference requests are still sent only
 * to their own provider endpoint and never to Copilot.
 */
declare interface NamedProviderConfig {
    /** Stable identifier referenced by {@link ProviderModelConfig.provider}. Must not contain `/`. */
    name: string;
    /** Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. */
    type?: ProviderType;
    /** Wire API format (openai/azure only). Defaults to "completions". */
    wireApi?: WireApi;
    /** Transport for OpenAI Responses requests. Defaults to "http". */
    transport?: ProviderTransport;
    /** API endpoint URL. */
    baseUrl: string;
    /** API key. Optional for local providers like Ollama. */
    apiKey?: string;
    /**
     * Bearer token for authentication. Sets the Authorization header directly.
     * Takes precedence over apiKey when both are set.
     */
    bearerToken?: string;
    /** Azure-specific options. */
    azure?: ProviderConfigAzure;
    /** Custom HTTP headers to include in all outbound requests to the provider. */
    headers?: Record<string, string>;
    /**
     * Wire flag set when an out-of-process SDK client supplies tokens for this
     * provider via the `providerToken.getToken` callback (e.g. wrapping
     * `@azure/identity`). When set, the runtime acquires a fresh token per
     * request to this provider and applies it as an `Authorization: Bearer
     * <token>` header (the bearer/OAuth scheme, not a provider-specific API-key
     * header such as Anthropic's `x-api-key`). When set alongside
     * `apiKey`/`bearerToken`, the callback takes precedence: the static
     * credentials are not sent and the per-request token is used instead.
     */
    hasBearerTokenProvider?: boolean;
}

/** A named BYOK provider connection (transport + credentials). */
declare interface NamedProviderConfig_2 {
    /** API key. Optional for local providers like Ollama. */
    apiKey?: string;
    /** Azure-specific provider options. */
    azure?: ProviderConfigAzure_2;
    /** API endpoint URL. */
    baseUrl: string;
    /** Bearer token for authentication. Sets the Authorization header directly. Takes precedence over apiKey when both are set. */
    bearerToken?: string;
    /** When true, the SDK client supplies bearer tokens on demand: the runtime calls the client-session `providerToken.getToken` callback before each request and applies the returned token as an `Authorization: Bearer <token>` header. This is the bearer/OAuth scheme used by Azure AD / managed-identity tokens and provider OAuth access tokens (including Anthropic's), not a provider-specific API-key header such as Anthropic's `x-api-key`. The token-acquiring function itself stays on the SDK side and is never serialized; only this flag crosses the wire. When set alongside `apiKey`/`bearerToken`, the callback takes precedence: the runtime applies the token returned by `providerToken.getToken` as the `Authorization: Bearer` header for each request and does not send the static credential. */
    hasBearerTokenProvider?: boolean;
    /** Custom HTTP headers to include in all outbound requests to the provider. */
    headers?: Record<string, string>;
    /** Stable identifier referenced by BYOK model definitions. Must not contain '/'. */
    name: string;
    /** Provider transport. Defaults to "http". */
    transport?: ProviderConfigTransport;
    /** Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. */
    type?: ProviderConfigType;
    /** Wire API format (openai/azure only). Defaults to "completions". */
    wireApi?: ProviderConfigWireApi;
}

/** The session's friendly name, or null when not yet set. */
declare interface NameGetResult {
    /** The session name (user-set or auto-generated), or null if not yet set */
    name: string | null;
}

/** Auto-generated session summary to apply as the session's name when no user-set name exists. */
declare interface NameSetAutoRequest {
    /** Auto-generated session summary. Empty/whitespace-only values are ignored; values are trimmed before persisting. */
    summary: string;
}

/** Indicates whether the auto-generated summary was applied as the session's name. */
declare interface NameSetAutoResult {
    /** Whether the auto-generated summary was persisted. False if the session already has a user-set name, the summary normalized to empty, or the session does not have a workspace. */
    applied: boolean;
}

/** New friendly name to apply to the session. */
declare interface NameSetRequest {
    /** New session name (1–100 characters, trimmed of leading/trailing whitespace) */
    name: string;
}

declare type NativeHookPipelineOptions = {
    sessionId?: string;
    onToolCallAllowed?: (toolCallId: string) => void;
    onAdditionalContext?: (toolCallId: string, context: string) => void;
    onBatchStart?: () => void;
    appendFailureContextToToolResult?: boolean;
    requestHookPermission?: (request: {
        kind: "hook";
        toolCallId: string;
        toolName: string;
        toolArgs: unknown;
        hookMessage?: string;
    }) => Promise<PermissionRequestResult>;
};

declare class NativeHookPipelineProcessor implements IPreToolsExecutionProcessor, IPostToolExecutionProcessor {
    private readonly processor;
    private readonly options;
    private readonly additionalContexts;
    constructor(processor: NativeHookProcessor, options: NativeHookPipelineOptions);
    toJSON(): string;
    drainAdditionalContexts(): {
        toolCallId: string;
        context: string;
    }[];
    /**
     * Fail closed when the bound hook session was disposed mid-request. A
     * hook-session replacement/resume can swap the session's processor while this
     * pipeline is still bound to the previous one; that handle is then gone and
     * the configured `preToolUse` hooks (denials, permission prompts, arg
     * mutations) cannot run on it. Disposal is an internal lifecycle event, not
     * authorization to bypass those hooks, so every still-pending tool call is
     * denied with a transient reason rather than allowed through unchecked.
     *
     * `Session` now keeps a replaced processor alive until the turn it is bound
     * to finishes, so this path is a genuine last-resort backstop rather than the
     * routine outcome of a hook reload. The message therefore states plainly what
     * happened (hook configuration changed mid-request), that the tool did NOT
     * run, and that recovery needs a NEW turn — the current one is halted on
     * purpose, so "retry the tool call" was actively misleading. When the
     * disposing caller supplied a reason it is quoted instead of guessing at
     * compaction/resume.
     *
     * The denial results are still emitted, so the tool_use<->tool_result
     * invariant holds (no orphaned tool_use / permanent CAPI 400). They use
     * `resultType: "rejected"` so the turn halts (native `user_halted` / the JS
     * agentic-loop exit) instead of continuing. The request's processor pipeline
     * is captured once, bound to this now-disposed processor, so if the turn kept
     * running the model's immediate retry would be re-evaluated by the *same*
     * stale pipeline and denied again (a retry trap). Halting ends the completion,
     * so the retry lands on the next request, which binds to the session's live
     * replacement processor. Denials already gathered (e.g. from `preCommit`) are
     * preserved.
     */
    private denyPendingToolCallsOnDisposal;
    preToolsExecution(context: PreToolsExecutionContext): Promise<Map<string, ToolResultExpanded> | void>;
    postToolExecution(context: PostToolExecutionContext): Promise<void>;
}

declare class NativeHookProcessor {
    readonly handle: number;
    private options;
    private readonly callbackRegistrations;
    private readonly secretScanningHandle;
    private configured;
    private disposed;
    private disposalReasonText;
    constructor(handle: number, options: NativeHookProcessorOptions, configured?: boolean);
    fork(sessionId: string, options?: Partial<NativeHookProcessorOptions>): NativeHookProcessor;
    configure(): void;
    updateCwd(cwd: string): void;
    refreshContext(): void;
    get isDisposed(): boolean;
    /** Why this processor was disposed, when the disposing caller supplied a reason. */
    get disposalReason(): string | undefined;
    setCallbackRegistration(ownerId: string, registrationId: number, source?: string): void;
    removeCallbackRegistration(ownerId: string): void;
    preSession(source: "new" | "resume", initialPrompt: string): Promise<Record<string, unknown> | undefined>;
    userPrompt(prompt: string, sessionId?: string): Promise<Record<string, unknown> | undefined>;
    userPromptTransformed(prompt: string, transformedPrompt: string, sessionId?: string): Promise<Record<string, unknown> | undefined>;
    postSession(reason?: string, error?: Error): Promise<Record<string, unknown> | undefined>;
    onResult(currentCommitHash: string): Promise<string | undefined>;
    prePrDescription(description: string): Promise<string>;
    preCommit(toolCalls: PreToolsExecutionContext["toolCalls"]): Promise<Map<string, ToolResultExpanded>>;
    event(eventName: string, input: Record<string, unknown>, sessionId?: string): Promise<Record<string, unknown> | undefined>;
    preMcpToolCall(input: object, sessionId?: string): Promise<Record<string, unknown> | undefined>;
    subagentStart(input: Record<string, unknown>): Promise<Record<string, unknown> | undefined>;
    subagentStop(input: Record<string, unknown>): Promise<Record<string, unknown> | undefined>;
    permissionRequest(permissionRequest: unknown, conventions?: "windows" | "posix"): Promise<PermissionRequestHooksRunResult>;
    postToolUseFailure(toolName: string, toolArgs: unknown, toolResult: ToolResultExpanded, sessionId?: string): Promise<NativeProcessorPostToolUseFailureResult>;
    createMcpToolCallInterceptor(sessionId?: string): McpToolCallInterceptor;
    /**
     * Whether any hook, declarative or registered callback, is registered for
     * `eventName`.
     *
     * Presence only. No matcher is inspected: a matcher naming a subject says a
     * hook targets it, not what the hook would decide about it.
     */
    eventHookPresence(eventName: string): boolean;
    createPipeline(options?: NativeHookPipelineOptions): NativeHookPipelineProcessor;
    listResources(): Promise<NativeHookResourceRow[]>;
    getPluginHookCount(): number;
    loadRepoHooks(hooksDir?: string): Promise<HookSessionLoadResult>;
    getCallbackRegistrations(): ReadonlyArray<readonly [string, number, string]>;
    reportProgress(progress: NativeProcessorProgressMessage): void;
    /**
     * Dispose the native hook session backing this processor.
     *
     * `reason` describes *why* the processor is going away (e.g. "the session's
     * hooks were reloaded"). It is surfaced verbatim to the model by
     * {@link NativeHookPipelineProcessor} when an in-flight request that is still
     * bound to this processor has to fail closed, so the model is told what
     * actually happened instead of a hard-coded guess.
     */
    dispose(reason?: string): boolean;
    private get progress();
    private toOutput;
    private handleLifecycle;
}

declare type NativeHookProcessorOptions = {
    cwd: string;
    logger: RunnerLoggerContract_2;
    emitHookStart?: (event: HookLifecycleStart) => void;
    emitHookEnd?: (event: HookLifecycleEnd) => void;
    emitProgress?: (event: NativeProcessorProgressMessage) => void;
    emitTelemetryJson?: (eventJson: string) => Promise<void>;
    secretScanning?: {
        settingsJson: string;
        repoLocation: string;
        initialCommitHash: string;
    };
};

declare type NativeImageProcessorPreRequestConfig = {
    handle: InstanceType<typeof nativeRuntime.ImageProcessorHandle>;
    mode: "capi" | "support";
    maxDimension: number;
    capiVisionFeatureEnabled?: boolean;
    githubServerUrl?: string;
    settingsJson?: string;
    attachmentResolverNetworkingConfigId?: string;
    uploadUrl?: string;
    uploadNetworkingConfigId?: string;
    repoId?: string;
    userToken?: string;
};

/**
 * Result of an MCP `tools/call`, mirroring the wire shape (`content` blocks +
 * optional `isError` / `structuredContent` / `_meta`). Left intentionally open
 * so callers can read fields the engine forwards verbatim.
 */
declare interface NativeMcpCallToolResult {
    content?: unknown[];
    isError?: boolean;
    structuredContent?: unknown;
    _meta?: unknown;
    [key: string]: unknown;
}

/**
 * Extra client capabilities to advertise during the initialize handshake, beyond
 * the sampling/elicitation support implied by a wired responder. These mirror the
 * flags the JS registry advertised from runtime settings: URL-mode elicitation,
 * the MCP Apps (`io.modelcontextprotocol/ui`) extension, and MCP Tasks
 * (`tasks.requests.tools.call`). Omitted flags default to disabled.
 */
declare interface NativeMcpCapabilityOptions {
    /** Advertise `elicitation.url` (only meaningful with a wired elicitation responder). */
    elicitationUrl?: boolean;
    /** Advertise the MCP Apps (`io.modelcontextprotocol/ui`) extension. */
    mcpApps?: boolean;
    /** Advertise the MCP Tasks `tasks.requests.tools.call` capability. */
    tasks?: boolean;
    /**
     * Client name advertised as `clientInfo.name` during the initialize handshake.
     * Some MCP servers key behavior off the exact client name, so callers set it
     * explicitly; omitted leaves the engine's build-env default.
     */
    clientName?: string;
    /** Client version advertised as `clientInfo.version`; only applied alongside `clientName`. */
    clientVersion?: string;
}

/**
 * Result of a sampling request, mirroring the MCP `CreateMessageResult` wire
 * shape (`model` + `role` + `content`, optional `stopReason`). Left open so the
 * host can include fields the engine forwards verbatim.
 */
declare interface NativeMcpCreateMessageResult {
    model: string;
    role: string;
    content: unknown;
    stopReason?: string;
    [key: string]: unknown;
}

/**
 * Result of a task-augmented `tools/call` (`CreateTaskResult`, `resultType:
 * "task"`): the seed state of the created task, with the task fields flattened
 * at the top level (SEP-2663). The caller polls `tasks/get` with `taskId`. Left
 * open for verbatim fields.
 */
declare interface NativeMcpCreateTaskResult extends NativeMcpTask {
    resultType?: "task";
    _meta?: unknown;
}

/** A server-initiated `elicitation/create` request handed to the host. */
declare interface NativeMcpElicitationRequest {
    /** The `CreateElicitationRequestParams`, parsed from the engine's JSON. */
    params: unknown;
}

/**
 * Answers a server-initiated elicitation request. The engine awaits the resolved
 * `CreateElicitationResult`; a thrown error is reported back to the server as an
 * elicitation failure.
 */
declare type NativeMcpElicitationResponder = (request: NativeMcpElicitationRequest) => Promise<NativeMcpElicitationResult> | NativeMcpElicitationResult;

/**
 * Result of an elicitation request, mirroring the MCP `CreateElicitationResult`
 * wire shape: the user's `action` and, when accepted, the collected `content`
 * (which must conform to the request's `requestedSchema`). Left open so the host
 * can include fields the engine forwards verbatim.
 */
declare interface NativeMcpElicitationResult {
    action: "accept" | "decline" | "cancel";
    content?: Record<string, unknown>;
    [key: string]: unknown;
}

/**
 * Per-request dynamic HTTP headers for a remote connection, backed by the host
 * headers-refresh manager. `getHeaders` is consulted before every request;
 * `refreshAfterAuthFailure` recomputes them after a `401`. Each resolves to the
 * headers to overlay, or `undefined` for "no dynamic headers" (and, for the
 * refresh, "decline the retry").
 */
declare interface NativeMcpHeadersRefresh {
    getHeaders(): Promise<Record<string, string> | undefined>;
    refreshAfterAuthFailure(): Promise<Record<string, string> | undefined>;
}

/**
 * Result of an MCP `resources/list`, mirroring the wire shape (`resources`
 * array plus optional `nextCursor`). Descriptor extension fields are preserved
 * under each descriptor's `additionalProperties` map.
 */
declare interface NativeMcpListResourcesResult {
    resources?: NativeMcpResourceDescriptor[];
    nextCursor?: string;
    _meta?: unknown;
    [key: string]: unknown;
}

/**
 * Result of an MCP `resources/templates/list`, mirroring the wire shape
 * (`resourceTemplates` array plus optional `nextCursor`). Descriptor extension
 * fields are preserved under each descriptor's `additionalProperties` map.
 */
declare interface NativeMcpListResourceTemplatesResult {
    resourceTemplates?: NativeMcpResourceTemplateDescriptor[];
    nextCursor?: string;
    _meta?: unknown;
    [key: string]: unknown;
}

/** A server notification forwarded from the engine over a live connection. */
declare interface NativeMcpNotification {
    /** The JSON-RPC notification method (e.g. `notifications/tools/list_changed`). */
    method: string;
    /** The notification params serialized as a JSON string (`"null"` when empty). */
    paramsJson: string;
}

/** Receives server notifications observed on a connection. */
declare type NativeMcpNotificationListener = (notification: NativeMcpNotification) => void;

/** A `notifications/progress` update for a single in-flight `callTool`. */
declare interface NativeMcpProgress {
    /** The progress token correlating this update to its originating request. */
    progressToken: string | number;
    /** The work completed so far (units are server-defined). */
    progress: number;
    /** The total amount of work, when the server reports it. */
    total?: number;
    /** An optional human-readable status message. */
    message?: string;
    [key: string]: unknown;
}

/** Receives `notifications/progress` for a single `callTool` while it runs. */
declare type NativeMcpProgressListener = (progress: NativeMcpProgress) => void;

/**
 * Result of an MCP `resources/read`, mirroring the wire shape (`contents`
 * blocks). Left open so callers can read fields the engine forwards verbatim.
 */
declare interface NativeMcpReadResourceResult {
    contents?: unknown[];
    _meta?: unknown;
    [key: string]: unknown;
}

/** Standard MCP resource annotation fields plus preserved vendor extensions. */
declare interface NativeMcpResourceAnnotations {
    audience?: string[];
    priority?: number;
    lastModified?: string;
    additionalProperties?: Record<string, unknown>;
}

/** Resource descriptor returned by `resources/list`. */
declare interface NativeMcpResourceDescriptor {
    uri: string;
    name: string;
    title?: string;
    description?: string;
    mimeType?: string;
    size?: number;
    icons?: NativeMcpResourceIcon[];
    annotations?: NativeMcpResourceAnnotations;
    _meta?: Record<string, unknown>;
    additionalProperties?: Record<string, unknown>;
}

/** Standard MCP resource icon fields plus preserved vendor extensions. */
declare interface NativeMcpResourceIcon {
    src: string;
    mimeType?: string;
    sizes?: string;
    theme?: string;
    additionalProperties?: Record<string, unknown>;
}

/** Resource template descriptor returned by `resources/templates/list`. */
declare interface NativeMcpResourceTemplateDescriptor {
    uriTemplate: string;
    name: string;
    title?: string;
    description?: string;
    mimeType?: string;
    icons?: NativeMcpResourceIcon[];
    annotations?: NativeMcpResourceAnnotations;
    _meta?: Record<string, unknown>;
    additionalProperties?: Record<string, unknown>;
}

/** A server-initiated `sampling/createMessage` request handed to the host. */
declare interface NativeMcpSamplingRequest {
    /**
     * The server-assigned JSON-RPC request id (a number or string) from the MCP
     * protocol, parsed from the engine's JSON.
     */
    requestId: string | number;
    /** The `CreateMessageRequestParams`, parsed from the engine's JSON. */
    params: unknown;
}

/**
 * Answers a server-initiated sampling request. The engine awaits the resolved
 * `CreateMessageResult`; a thrown error is reported back to the server as a
 * sampling failure.
 */
declare type NativeMcpSamplingResponder = (request: NativeMcpSamplingRequest) => Promise<NativeMcpCreateMessageResult> | NativeMcpCreateMessageResult;

/** Parameters for launching a sandboxed (mxc in-process sandbox) stdio MCP server. */
declare interface NativeMcpSandboxedStdioParams {
    /** Executable to spawn inside the sandbox. */
    command: string;
    /** Arguments passed to the executable. */
    args?: string[];
    /** Environment variables applied directly to the sandboxed process. */
    env?: Record<string, string>;
    /** Working directory for the sandboxed process. */
    cwd: string;
    /** Effective MCP sandbox policy (the routing flags already stripped). */
    sandboxConfig: SandboxConfig_2;
}

/**
 * The server's MCP initialize result: protocol version, advertised
 * capabilities, server implementation info, and optional instructions. Left
 * open so callers can read fields the engine forwards verbatim.
 */
declare interface NativeMcpServerInfo {
    protocolVersion?: string;
    capabilities?: Record<string, unknown>;
    serverInfo?: {
        name?: string;
        version?: string;
        [key: string]: unknown;
    };
    instructions?: string;
    [key: string]: unknown;
}

declare class NativeMcpSession {
    /** Native connection handle, or `undefined` once closed. */
    private handle;
    /** Identity token used to unregister the GC backstop on explicit close. */
    private readonly cleanupToken;
    /**
     * Subscribes a rejector to post-initialize transport send failures, returning
     * an unsubscribe. Only wired for bridge connections (which own a JS-side
     * transport whose `send` can reject out of band); `undefined` for the
     * native-owned stdio/HTTP connections, whose send failures surface in-band
     * through the engine. See {@link raceSendFailure}.
     */
    private readonly subscribeSendFailure?;
    private constructor();
    /**
     * Spawns a stdio MCP server and completes the initialize handshake. When
     * `onNotification` is provided, server notifications (tool-list changes,
     * progress) are forwarded to it for the connection's lifetime. When
     * `onSampling` and/or `onElicitation` are provided, server-initiated
     * `sampling/createMessage` / `elicitation/create` requests are bridged to
     * them (and the client advertises each wired capability). `options`
     * advertises additional capabilities (URL elicitation, MCP Apps, Tasks).
     * When `onClose` is provided and `onStderr` is supplied, each line the child
     * writes to stderr is forwarded to `onStderr` for the connection's lifetime
     * (and during the initial handshake, so startup failures surface diagnostics).
     */
    static connectStdio(params: NativeMcpStdioParams, onNotification?: NativeMcpNotificationListener, onSampling?: NativeMcpSamplingResponder, onElicitation?: NativeMcpElicitationResponder, options?: NativeMcpCapabilityOptions, connectTimeoutMs?: number, onClose?: () => void, onStderr?: (line: string) => void): Promise<NativeMcpSession>;
    /**
     * Spawns a stdio MCP server inside the in-process MXC sandbox and completes
     * the initialize handshake, driving the native client over the sandbox
     * child's bridged stdio. Behaves exactly like {@link connectStdio} — same
     * notification/sampling/elicitation bridging, capability advertisement,
     * connect-timeout handling, and `onClose`/`onStderr` forwarding — but the
     * server runs under the resolved MCP sandbox policy. The command + args are
     * shell-escaped into the sandbox command line (PowerShell on Windows, a bare
     * `/bin/sh -c` command elsewhere) by {@link nativeRuntime.sandboxBuildSandboxedShellScript}; the
     * sandbox group-kills the whole process tree on close.
     */
    static connectSandboxedStdio(params: NativeMcpSandboxedStdioParams, onNotification?: NativeMcpNotificationListener, onSampling?: NativeMcpSamplingResponder, onElicitation?: NativeMcpElicitationResponder, options?: NativeMcpCapabilityOptions, connectTimeoutMs?: number, onClose?: () => void, onStderr?: (line: string) => void): Promise<NativeMcpSession>;
    /**
     * Connects to a remote MCP server over Streamable HTTP and completes the
     * initialize handshake. When `onNotification` is provided, server
     * notifications are forwarded to it for the connection's lifetime. When
     * `onSampling` and/or `onElicitation` are provided, server-initiated
     * `sampling/createMessage` / `elicitation/create` requests are bridged to
     * them (and the client advertises each wired capability). `options`
     * advertises additional capabilities (URL elicitation, MCP Apps, Tasks).
     * When `connectTimeoutMs` is provided, the connection will be aborted if
     * the initialize handshake does not complete within the specified time.
     */
    static connectStreamableHttp(params: NativeMcpStreamableHttpParams, onNotification?: NativeMcpNotificationListener, onSampling?: NativeMcpSamplingResponder, onElicitation?: NativeMcpElicitationResponder, options?: NativeMcpCapabilityOptions, connectTimeoutMs?: number, onClose?: () => void): Promise<NativeMcpSession>;
    /**
     * Connects to a remote MCP server over the legacy HTTP+SSE transport and
     * completes the initialize handshake. Behaves exactly like
     * {@link connectStreamableHttp} — same params (url, headers, bearer token),
     * notification/sampling/elicitation bridging, capability advertisement, and
     * bounded connect timeout — but speaks the pre-Streamable-HTTP wire protocol
     * for servers that only expose an SSE endpoint.
     */
    static connectSse(params: NativeMcpStreamableHttpParams, onNotification?: NativeMcpNotificationListener, onSampling?: NativeMcpSamplingResponder, onElicitation?: NativeMcpElicitationResponder, options?: NativeMcpCapabilityOptions, connectTimeoutMs?: number, onClose?: () => void): Promise<NativeMcpSession>;
    /**
     * Wraps a native connection handle in the temporary TypeScript session facade.
     * Connect-timeout and orphan-handle cleanup are owned by the native boundary.
     */
    private static fromNativeConnect;
    /**
     * Connects to a Rust-owned in-memory tool server. The MCP session and
     * transport stay native; only the actual tool handlers cross back to the
     * still-TypeScript host as temporary callbacks.
     */
    static connectCallbackToolServer(server: MCPNativeInMemoryServerInstance, onNotification?: NativeMcpNotificationListener, onSampling?: NativeMcpSamplingResponder, onElicitation?: NativeMcpElicitationResponder, options?: NativeMcpCapabilityOptions, connectTimeoutMs?: number): Promise<NativeMcpSession>;
    /**
     * Connects to an MCP server reached through a pre-built SDK {@link Transport}
     * (e.g. the IDE socket transport) and completes the initialize handshake. The
     * native client cannot spawn or own this transport, so it relays JSON-RPC
     * frames over a temporary napi bridge surface. When `onNotification`,
     * `onSampling`, and/or `onElicitation` are
     * provided they behave exactly as for the other transports.
     *
     * Frame ordering mirrors the SDK `Client.connect` contract: the inbound
     * `onmessage` hook is installed and the transport is `start()`ed (so outbound
     * sends are valid) BEFORE the native connect kicks off `initialize` through
     * `sendToServer`. Inbound frames that arrive before the connection handle is
     * known are buffered and flushed once it is, so the initialize response is
     * never dropped.
     */
    static connectBridgeTransport(transport: Transport, onNotification?: NativeMcpNotificationListener, onSampling?: NativeMcpSamplingResponder, onElicitation?: NativeMcpElicitationResponder, options?: NativeMcpCapabilityOptions, connectTimeoutMs?: number): Promise<NativeMcpSession>;
    /**
     * Awaits the initialize handshake for a freshly-bridged `handle`. When
     * `connectTimeoutMs` is provided the wait is bounded: if initialize does not
     * complete in time the half-open native handle is released and the connect
     * rejects, so a slow or unresponsive server cannot hang startup forever (the
     * issue-#8888 floor for slow brokered auth — the policy lives in
     * `MCPRegistry`). The native boundary owns timeout clamping and half-open
     * handle release. A `connectFailure` promise (wired by bridge connects)
     * rejects the wait early if the transport fails before the handshake completes
     * (a send rejection or a close), preserving the transport's original error
     * instead of waiting out the timeout (or hanging forever when unbounded).
     */
    private static awaitInitialized;
    /**
     * Assembles the capability flags the engine advertises during initialize: the
     * sampling/elicitation support implied by a wired responder, plus the optional
     * URL-elicitation, MCP Apps, and Tasks flags. Mirrors the shape of the napi
     * `McpHandlerCapabilitiesJs` object.
     */
    private static buildCapabilities;
    /**
     * Whether the connect must take the capability-passing (`WithHandlers`) path
     * rather than the cheaper notification-only / bare connect. That path is
     * required when any client capability is advertised (sampling, elicitation,
     * MCP Apps, Tasks) — each builds a real `CopilotClientHandler` — and also
     * whenever a client identity (`clientName` + `clientVersion`) is configured,
     * because only the capability-passing path forwards `clientInfo` to the
     * engine. The bare/notification connects omit the capabilities object, which
     * would drop the advertised `clientInfo` (the SDK always sends it, and some
     * MCP servers key off the `"github-copilot-developer"` client name). With no
     * capability flags set, the handler path advertises an empty capability set,
     * staying byte-for-byte inert like rmcp's `()` handler aside from `clientInfo`.
     */
    private static advertisesHandlerCapability;
    /**
     * Adapts a `NativeMcpSamplingResponder` to the engine's fire-and-forget
     * callback: parse the request params, run the responder, and report the
     * `CreateMessageResult` (or a failure message) back through the engine via
     * the request's correlation token.
     */
    private static wrapSampling;
    /**
     * Adapts a `NativeMcpElicitationResponder` to the engine's fire-and-forget
     * callback: parse the request params, run the responder, and report the
     * `CreateElicitationResult` (or a failure message) back through the engine
     * via the request's correlation token.
     */
    private static wrapElicitation;
    /**
     * Adapts a {@link NativeMcpHeadersRefresh} to the engine's fire-and-forget
     * callback: resolve the host's dynamic headers (pre-request or post-`401`
     * refresh) and report them back as `{ headers }` via the request's
     * correlation token. A failure completes leniently with no headers so the
     * request proceeds with its static headers rather than wedging the
     * connection.
     */
    private static wrapHeadersRefresh;
    listTools(options?: {
        timeoutMs?: number;
    }): Promise<LenientToolInfo[]>;
    /**
     * Invokes `name` with optional `args`. `meta` supplies request-level `_meta`
     * (trace context, hook-controlled MCP metadata) forwarded to the server as a
     * sibling of the arguments, not nested inside them. `options.timeoutMs` bounds
     * the call with a progress-aware timer; when `options.resetTimeoutOnProgress`
     * is set, each `notifications/progress` for this call restarts that timer so a
     * long-but-progressing tool is not cancelled (matching the JS SDK's
     * `resetTimeoutOnProgress`). When no `timeoutMs` is supplied the call is
     * bounded by {@link DEFAULT_NATIVE_REQUEST_TIMEOUT_MS} (the JS SDK's default
     * request timeout), so an unconfigured call is never unbounded.
     * `options.onProgress`, when provided, receives each `notifications/progress`
     * for this call while it runs (the JS SDK's per-request `onprogress`).
     */
    callTool(name: string, args?: Record<string, unknown>, meta?: Record<string, unknown>, options?: {
        timeoutMs?: number;
        resetTimeoutOnProgress?: boolean;
        onProgress?: NativeMcpProgressListener;
        signal?: AbortSignal;
    }): Promise<NativeMcpCallToolResult>;
    /**
     * Races a request-response engine operation against this session's post-init
     * transport send failures (bridge connections only). When a `transport.send`
     * rejects out of band — e.g. an OAuth 401 surfaced as `UnauthorizedError` once
     * the SDK's inline re-auth flow returns REDIRECT, or a remote/stdio disconnect —
     * the in-flight call rejects with that error instead of hanging until the
     * request timeout, letting the caller retry (matching the JS SDK `Client`). For
     * native-owned connections (no subscriber) the operation is awaited unchanged.
     */
    private raceSendFailure;
    /**
     * Awaits a native request operation, reconstructing a real {@link McpError}
     * (via {@link adaptNativeMcpError}) from a server-returned JSON-RPC error the
     * napi boundary flattened into a string. Every request method routes through
     * this so callers observe `.code`/`.data` and class identity (e.g.
     * {@link UrlElicitationRequiredError}) just as with the pre-port SDK `Client`.
     */
    private awaitNative;
    /**
     * Adapts a {@link NativeMcpProgressListener} to the engine's progress
     * callback, which delivers each `ProgressNotificationParam` as a JSON string.
     * A malformed payload is dropped rather than thrown, since progress is
     * advisory and must never fail the in-flight call.
     */
    private static wrapProgress;
    /**
     * Returns the server's initialize result — protocol version, advertised
     * capabilities, server info, and optional instructions — captured during the
     * handshake. Backs the host's `getServerVersion` / `getServerCapabilities` /
     * `getInstructions` accessors.
     */
    serverInfo(): Promise<NativeMcpServerInfo>;
    /** Reads the resource identified by `uri`, preserving arbitrary fields. */
    readResource(uri: string): Promise<NativeMcpReadResourceResult>;
    /**
     * Lists a page of resources advertised by the server (`resources/list`),
     * preserving descriptor extensions under `additionalProperties`.
     */
    listResources(options?: {
        cursor?: string;
    }): Promise<NativeMcpListResourcesResult>;
    /**
     * Lists a page of resource templates advertised by the server
     * (`resources/templates/list`), preserving descriptor extensions under
     * `additionalProperties`.
     */
    listResourceTemplates(options?: {
        cursor?: string;
    }): Promise<NativeMcpListResourceTemplatesResult>;
    /**
     * Sends an arbitrary JSON-RPC request (`method` plus optional `params`) and
     * returns the parsed result. The escape hatch for protocol methods without a
     * first-class wrapper. When `options.timeoutMs` is set the request is bounded
     * by that deadline and rejects with a timeout on expiry (a long-poll caller
     * treats that as "no event yet, poll again"); otherwise the request is
     * unbounded (the engine applies no timeout of its own).
     */
    request(method: string, params?: Record<string, unknown>, options?: {
        timeoutMs?: number;
    }): Promise<unknown>;
    /**
     * Sends an arbitrary JSON-RPC notification (`method` plus optional `params`)
     * fire-and-forget: there is no response and no request id, so the returned
     * promise resolves as soon as the engine hands the frame to the transport.
     * The client->server notification counterpart to {@link request}, used for
     * host->server events (e.g. the `notifications/copilot` `user.abort` signal)
     * the server consumes without replying.
     */
    notify(method: string, params?: Record<string, unknown>): Promise<void>;
    /**
     * Invokes `name` as a task-augmented tool call (MCP Tasks / SEP-2663).
     * `args` / `meta` behave as in {@link callTool}; task augmentation is
     * negotiated by the tasks extension the client declares in its initialize
     * capabilities (rmcp 3.0 replaced the dedicated `tasks` capability field
     * with the `extensions` map), not by a per-request `_meta` marker. The
     * server MAY enqueue a task (`kind: "task"`) or — as the spec permits —
     * complete the work synchronously and answer with an immediate
     * `CallToolResult` (`kind: "result"`); callers discriminate on the returned
     * envelope.
     */
    callToolAsTask(name: string, args?: Record<string, unknown>, meta?: Record<string, unknown>, options?: {
        timeoutMs?: number;
    }): Promise<NativeMcpTaskCallResult>;
    /** Fetches a task's lifecycle status/metadata (`tasks/get`). */
    getTask(taskId: string): Promise<NativeMcpTask>;
    /**
     * Retrieves a completed task's payload — the original call's result. rmcp 3.0
     * (SEP-2663) removed the standalone `tasks/result` method; the terminal
     * payload is inlined into the `tasks/get` response and unwrapped here.
     */
    getTaskResult(taskId: string): Promise<NativeMcpCallToolResult>;
    /**
     * Requests cancellation of a task (`tasks/cancel`), returning the server's
     * empty acknowledgement. rmcp 3.0 (SEP-2663) makes this an ack; the cancelled
     * state is observed via a subsequent `getTask`.
     */
    cancelTask(taskId: string): Promise<NativeMcpTaskAck>;
    /** Native connection token for runtime components that dispatch directly. */
    get nativeHandle(): number;
    /** Restores typed MCP errors returned directly by a runtime component. */
    static adaptError(error: unknown): unknown;
    /**
     * Tears down the connection (process-tree teardown for stdio, session
     * cancel for remote) and releases the handle. Idempotent: a second call is a
     * no-op.
     */
    close(): Promise<void>;
    private requireHandle;
}

/** Parameters for launching a stdio MCP server subprocess. */
declare interface NativeMcpStdioParams {
    /** Executable to spawn. */
    command: string;
    /** Arguments passed to the executable. */
    args?: string[];
    /** Environment variables added to the subprocess environment. */
    env?: Record<string, string>;
    /** Working directory for the subprocess. */
    cwd?: string;
}

/** Parameters for connecting to a remote MCP server over Streamable HTTP. */
declare interface NativeMcpStreamableHttpParams {
    /** The server endpoint URL. */
    url: string;
    /** Custom HTTP headers sent with every request. */
    headers?: Record<string, string>;
    /**
     * A bare bearer token (no `Bearer ` prefix), sent as the `Authorization`
     * header. Mutually exclusive with an `Authorization` entry in `headers`.
     */
    bearerToken?: string;
    /**
     * Optional per-request dynamic-header provider (the host headers-refresh
     * manager). When set, the engine overlays these headers onto every request
     * and retries one `401` after refreshing them. Only honored on the
     * `onClose`-bearing connect paths the registry uses.
     */
    headersRefresh?: NativeMcpHeadersRefresh;
    /**
     * Whether the connection has an OAuth provider configured. Threaded to the
     * dynamic-header overlay so a dynamic `Authorization` header is suppressed
     * (the OAuth bearer wins). Defaults to `false`.
     */
    hasAuthProvider?: boolean;
    /**
     * Optional proxy URL to route this remote connection through. Set when MCP
     * sandboxing is enabled and the sandbox has a `network.proxy` configured, so
     * remote (HTTP/SSE) MCP traffic honors the same egress as sandboxed
     * subprocesses. Takes precedence over the runtime's process-env proxy.
     */
    proxyUrl?: string;
}

/**
 * An MCP task (MCP Tasks / SEP-2663), mirroring the wire shape: the `taskId`,
 * lifecycle `status`, timestamps, and optional `ttlMs` / `pollIntervalMs` /
 * `statusMessage`. Left open so callers can read fields the engine forwards
 * verbatim.
 */
declare interface NativeMcpTask {
    taskId: string;
    status: string;
    createdAt?: string;
    lastUpdatedAt?: string;
    ttlMs?: number | null;
    pollIntervalMs?: number;
    statusMessage?: string;
    [key: string]: unknown;
}

/**
 * Empty acknowledgement for `tasks/cancel` (`TaskAckResult`, `resultType:
 * "complete"`, SEP-2663). Cancellation is cooperative; the cancelled state is
 * observed via a subsequent `tasks/get`. Left open for verbatim fields.
 */
declare interface NativeMcpTaskAck {
    resultType?: "complete";
    _meta?: unknown;
    [key: string]: unknown;
}

/**
 * Discriminated outcome of a task-augmented `tools/call`. When the client
 * advertises task support, the server MAY materialize the call as a task and
 * return a task reference (`kind: "task"`), or — as the spec permits — complete
 * the work synchronously and answer with an immediate `CallToolResult`
 * (`kind: "result"`). The host polls the former and returns the latter directly.
 */
declare type NativeMcpTaskCallResult = {
    kind: "task";
    createTaskResult: NativeMcpCreateTaskResult;
} | {
    kind: "result";
    callToolResult: NativeMcpCallToolResult;
};

declare type NativeOnRequestErrorProcessorConfig = {
    kind: "truncator";
    handle: unknown;
    disableSizeTruncation?: boolean;
} | {
    kind: "compaction";
    handle: unknown;
};

declare type NativePreRequestProcessorConfig = {
    kind: "truncator";
    handle: unknown;
    latestUserPromptIndex?: number;
    latestUserPromptMarker?: string;
    latestUserPromptMessage?: ChatCompletionMessageParam;
    latestUserPromptMessageJson?: string;
    disableSizeTruncation?: boolean;
} | {
    kind: "response_limits";
    handle?: unknown;
    sessionId?: string;
    /** The response limits, when configured. */
    limits?: {
        maxAiCredits?: number;
    };
} | {
    kind: "compaction";
    handle: unknown;
    /**
     * Whether the compaction prompt should ask the model to generate a
     * `<checkpoint_title>` for the summary. Captured here so the native
     * pre-request arm can drive the summary prepare-start without a JS
     * bridge round-trip.
     */
    includeCheckpointTitle: boolean;
} | {
    kind: "immediate_prompt";
    sessionId: string;
    currentRunInteractionId?: string;
};

/**
 * A chat message as projected by the native runtime. Carries an optional
 * `__copilotMessageSource` sidecar that is kept non-enumerable on public chat messages.
 */
declare type NativeProjectedMessage = ChatCompletionMessageParam & {
    __copilotMessageSource?: MessageSource;
    __copilotUserShellOutput?: {
        success: boolean;
        command?: string;
        output: string;
    };
};

declare interface NativeRestorePreview {
    fileCount: number;
    files: HistoryRewindFilePreview[];
}

declare interface NativeRestoreResult {
    outcome: "success" | "files_rolled_back" | "rollback_incomplete" | "nothing_to_restore";
    restoredFiles: string[];
    skippedFiles: HistorySkippedFileRestore[];
    pruneEventIds: string[];
    error?: string;
}

declare type NativeRuntime = Omit<RuntimeNativeModule, "SessionDatabaseHandle" | "sandboxConfigsEqual" | "sandboxEffectiveFor" | "sandboxEffectiveForOptional" | "sandboxResolveConfig" | "sessionStoreTrackingPostToolUsePlan"> & {
    SessionDatabaseHandle: new (...args: ConstructorParameters<typeof RuntimeNative.SessionDatabaseHandle>) => SessionDatabaseHandleCompat;
    sandboxConfigsEqual(a: RuntimeNative.SandboxConfig, b: RuntimeNative.SandboxConfig): boolean;
    sandboxEffectiveFor(config: RuntimeNative.SandboxConfig, routingFlag: string): RuntimeNative.SandboxConfig | null;
    sandboxEffectiveForOptional(config: RuntimeNative.SandboxConfig | undefined | null, routingFlag: string): RuntimeNative.SandboxConfig;
    sandboxResolveConfig(config?: RuntimeSandboxSettingsConfig | null): RuntimeNative.SandboxConfig;
    sessionStoreTrackingPostToolUsePlan(sessionId: unknown, turnIndex: unknown, inputJson: string): string;
};

/**
 * Process-wide Rust runtime, lazy-loaded on first member access.
 *
 * Imported as a const so call sites read like normal property access
 * (`nativeRuntime.tokensCountString(...)`) rather than a factory
 * call. The actual napi addon load is deferred to the first member
 * access via the Proxy below, so importing this module does NOT require
 * the `runtime.<triple>.node` binary to be built — only invoking a
 * method does. That matters for tooling (schema generation, type
 * checks) that imports shared types without exercising the runtime.
 *
 * The native runtime is a napi-rs N-API binary published as
 * `runtime.<triple>.node` inside `src/runtime/` (or a parallel
 * directory next to the bundled CLI). napi-rs owns the Tokio runtime and
 * surfaces async results as JS Promises, so callers never need to manage
 * init / shutdown / free — the addon stays alive for the process lifetime.
 *
 * Methods are camelCase (e.g. `tokensCountString`,
 * `sessionIfcHydrateEvents`) and mirror the Rust `#[napi]` exports under
 * `src/runtime/src/<domain>/api*.rs`. Sync exports return values
 * directly; async exports return `Promise<T>`.
 */
declare const nativeRuntime: NativeRuntime;

declare type NativeSessionFixedInvoker = (sessionId: string, paramsJson?: string | null) => Promise<string>;

declare type NativeSessionHostEffectCaller = {
    extensionId?: string;
};

declare type NativeSessionMethodInvoker = (sessionId: string, method: string, paramsJson?: string | null) => Promise<string>;

declare interface NormalizedCopilotUsage {
    tokenDetails: Array<{
        batchSize: number;
        costPerBatch: number;
        tokenCount: number;
        tokenType: string;
    }>;
    totalNanoAiu: number;
}

declare interface OAuthClientInformation extends Record<string, unknown> {
    client_id: string;
    client_secret?: string;
    client_id_issued_at?: number;
    client_secret_expires_at?: number;
}

declare type OAuthClientInformationFull = OAuthClientInformation & OAuthClientMetadata;

declare type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull;

declare interface OAuthClientMetadata extends Record<string, unknown> {
    redirect_uris: string[];
    token_endpoint_auth_method?: string;
    grant_types?: string[];
    response_types?: string[];
    client_name?: string;
    client_uri?: string;
    logo_uri?: string;
    scope?: string;
    contacts?: string[];
    tos_uri?: string;
    policy_uri?: string;
    jwks_uri?: string;
    jwks?: unknown;
    software_id?: string;
    software_version?: string;
    software_statement?: string;
}

declare interface OAuthClientProvider {
    get redirectUrl(): string | URL | undefined;
    clientMetadataUrl?: string;
    get clientMetadata(): OAuthClientMetadata;
    state?(): string | Promise<string>;
    clientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;
    saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise<void>;
    tokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;
    saveTokens(tokens: OAuthTokens): void | Promise<void>;
    redirectToAuthorization(authorizationUrl: URL): void | Promise<void>;
    saveCodeVerifier(codeVerifier: string): void | Promise<void>;
    codeVerifier(): string | Promise<string>;
    addClientAuthentication?: AddClientAuthentication;
    validateResourceURL?(serverUrl: string | URL, resource?: string): Promise<URL | undefined>;
    invalidateCredentials?(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): void | Promise<void>;
    prepareTokenRequest?(scope?: string): URLSearchParams | Promise<URLSearchParams | undefined> | undefined;
    saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;
    discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;
}

declare interface OAuthDiscoveryState extends OAuthServerInfo {
    resourceMetadataUrl?: string;
}

declare interface OAuthMetadata extends Record<string, unknown> {
    issuer: string;
    authorization_endpoint: string;
    token_endpoint: string;
    registration_endpoint?: string;
    scopes_supported?: string[];
    response_types_supported: string[];
    response_modes_supported?: string[];
    grant_types_supported?: string[];
    token_endpoint_auth_methods_supported?: string[];
    token_endpoint_auth_signing_alg_values_supported?: string[];
    service_documentation?: string;
    revocation_endpoint?: string;
    revocation_endpoint_auth_methods_supported?: string[];
    revocation_endpoint_auth_signing_alg_values_supported?: string[];
    introspection_endpoint?: string;
    introspection_endpoint_auth_methods_supported?: string[];
    introspection_endpoint_auth_signing_alg_values_supported?: string[];
    code_challenge_methods_supported?: string[];
    client_id_metadata_document_supported?: boolean;
    [key: string]: unknown;
}

declare interface OAuthProtectedResourceMetadata {
    resource: string;
    authorization_servers?: string[];
    jwks_uri?: string;
    scopes_supported?: string[];
    bearer_methods_supported?: string[];
    resource_signing_alg_values_supported?: string[];
    resource_name?: string;
    resource_documentation?: string;
    resource_policy_uri?: string;
    resource_tos_uri?: string;
    tls_client_certificate_bound_access_tokens?: boolean;
    authorization_details_types_supported?: string[];
    dpop_signing_alg_values_supported?: string[];
    dpop_bound_access_tokens_required?: boolean;
    [key: string]: unknown;
}

declare interface OAuthServerInfo {
    authorizationServerUrl: string;
    authorizationServerMetadata?: AuthorizationServerMetadata;
    resourceMetadata?: OAuthProtectedResourceMetadata;
}

declare interface OAuthTokens {
    access_token: string;
    token_type: string;
    expires_in?: number;
    scope?: string;
    refresh_token?: string;
    id_token?: string;
}

declare type OIDCAuthCallback = (secretNames: string[], mcpServerNames: string[], agentName?: string, agentVersion?: string) => Promise<OIDCAuthResult>;

/**
 * Structured result from an OIDC token exchange, keeping secret-based tokens
 * and MCP-server-based tokens in separate maps so callers don't need to
 * re-classify names after the fact.
 */
declare interface OIDCAuthResult {
    /** Tokens keyed by OIDC secret name (GITHUB_COPILOT_OIDC_* / GITHUB_AGENTIC_APP_OIDC_*). */
    secretTokens: Record<string, string>;
    /** Tokens keyed by MCP server name. */
    mcpServerTokens: Record<string, string>;
    /** Failures reported for individual token exchanges that failed upstream. */
    failures: OIDCTokenFailure[];
    /** Warnings reported for individual token exchanges. */
    warnings: OIDCTokenWarning[];
}

/** Describes a single upstream OIDC token exchange failure. */
declare interface OIDCTokenFailure {
    /** HTTP-level status code from the upstream provider. */
    responseCode: number;
    /** User-facing message describing the failure. */
    message: string;
    /** Internal error detail for logging/diagnostics. */
    error: string;
    /** Optional URL with more context about the failure. */
    failureUrl?: string;
    /** Optional MCP server name associated with this failure. */
    serverName?: string;
    /** Optional secret name associated with this failure. */
    secretName?: string;
}

declare interface OIDCTokenWarning {
    /** User-facing message describing the warning. */
    message: string;
}

/** Why the binary data is absent: it exceeded the inline size limit, or its asset was unavailable */
export declare type OmittedBinaryOmittedReason = "too_large" | "asset_unavailable";

/** Why the binary data is absent: it exceeded the inline size limit, or its asset was unavailable */
declare type OmittedBinaryOmittedReason_2 = "too_large" | "asset_unavailable";

/** A binary result whose data was omitted from persistence due to the inline size limit */
export declare interface OmittedBinaryResult {
    /** Decoded byte length of the omitted binary data */
    byteLength: number;
    /** Human-readable description of the binary data */
    description?: string;
    /** Optional metadata from the producing tool. */
    metadata?: Record<string, unknown>;
    /** MIME type of the omitted binary data */
    mimeType: string;
    /** Why the binary data is absent: it exceeded the inline size limit, or its asset was unavailable */
    omittedReason: OmittedBinaryOmittedReason;
    /** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
    type: OmittedBinaryType;
}

/** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
export declare type OmittedBinaryType = "image" | "resource";

declare type OnRequestErrorContext = {
    /**
     * The current turn.
     */
    readonly turn: number;
    /**
     * The current retry attempt.
     */
    readonly retry: number;
    /**
     * The maximum number of retry attempts.
     */
    readonly maxRetries: number;
    /**
     * The error received in response to a request.
     */
    readonly error: unknown;
    /**
     * The HTTP status code from the error response, if available.
     */
    readonly status: number | undefined;
    /**
     * Information about the model being called.
     */
    readonly modelInfo: CompletionWithToolsModel;
    /**
     * The current {@link GetCompletionWithToolsOptions}
     */
    readonly getCompletionWithToolsOptions: GetCompletionWithToolsOptions | undefined;
};

declare type OnRequestErrorResult = {
    /**
     * If the processor does something to handle the error and wishes for there to be a retry
     * it should set this to how many milliseconds to wait before retrying.
     */
    retryAfter: number;
    /** Why this retry is happening (e.g., "snippy_annotations"). Defaults to "streaming_error" if not set. */
    retryReason?: string;
};

/**
 * Arms of the three-arm OpenAI Responses prompt-caching experiment
 * ({@link DefinedExpFlags.OPENAI_EXPLICIT_PROMPT_CACHING}):
 * - "control": system prompt stays in `instructions`; no explicit markers.
 * - "explicit": `prompt_cache_options: { mode: "explicit" }`, the split system
 *   prompt as two separately marked `input_text` blocks, and a breakpoint on
 *   the latest eligible conversation message.
 * - "hybrid": the two marked system blocks only — no `prompt_cache_options` and
 *   no latest-message breakpoint, leaving OpenAI's implicit caching in play.
 */
declare const OPENAI_PROMPT_CACHING_ARMS: readonly ["control", "explicit", "hybrid"];

declare type OpenAiPromptCachingArm = (typeof OPENAI_PROMPT_CACHING_ARMS)[number];

/** Open canvas instance snapshot. */
declare interface OpenCanvasInstance {
    /** Provider-local canvas identifier */
    canvasId: string;
    /** Owning provider identifier */
    extensionId: string;
    /** Owning extension display name, when available */
    extensionName?: string;
    /** Host-local PNG path for the canvas icon, when supplied */
    icon?: string;
    /** Input supplied when the instance was opened */
    input?: unknown;
    /** Stable caller-supplied canvas instance identifier */
    instanceId: string;
    /** Provider-supplied status text */
    status?: string;
    /** Rendered title */
    title?: string;
    /** URL for web-rendered canvases */
    url?: string;
}

declare interface OpenIdProviderDiscoveryMetadata extends OAuthMetadata {
    userinfo_endpoint?: string;
    jwks_uri: string;
    acr_values_supported?: string[];
    subject_types_supported: string[];
    id_token_signing_alg_values_supported: string[];
    id_token_encryption_alg_values_supported?: string[];
    id_token_encryption_enc_values_supported?: string[];
    userinfo_signing_alg_values_supported?: string[];
    userinfo_encryption_alg_values_supported?: string[];
    userinfo_encryption_enc_values_supported?: string[];
    request_object_signing_alg_values_supported?: string[];
    request_object_encryption_alg_values_supported?: string[];
    request_object_encryption_enc_values_supported?: string[];
    display_values_supported?: string[];
    claim_types_supported?: string[];
    claims_supported?: string[];
    claims_locales_supported?: string[];
    ui_locales_supported?: string[];
    claims_parameter_supported?: boolean;
    request_parameter_supported?: boolean;
    request_uri_parameter_supported?: boolean;
    require_request_uri_registration?: boolean;
    op_policy_uri?: string;
    op_tos_uri?: string;
}

/** Content-exclusion policy supplied to `session.options.update`, with rules, last-updated data, and scope. */
declare interface OptionsUpdateAdditionalContentExclusionPolicy {
    last_updated_at: unknown;
    rules: OptionsUpdateAdditionalContentExclusionPolicyRule[];
    /** Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration. */
    scope: OptionsUpdateAdditionalContentExclusionPolicyScope;
    [key: string]: unknown;
}

/** Single content-exclusion rule supplied to `session.options.update`, with paths, match conditions, and source. */
declare interface OptionsUpdateAdditionalContentExclusionPolicyRule {
    ifAnyMatch?: string[];
    ifNoneMatch?: string[];
    paths: string[];
    /** Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. */
    source: OptionsUpdateAdditionalContentExclusionPolicyRuleSource;
    [key: string]: unknown;
}

/** Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. */
declare interface OptionsUpdateAdditionalContentExclusionPolicyRuleSource {
    name: string;
    type: string;
}

/** Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration. */
declare type OptionsUpdateAdditionalContentExclusionPolicyScope = "repo" | "all";

/** Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. */
declare type OptionsUpdateContextTier = "default" | "long_context";

/** How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). */
declare type OptionsUpdateEnvValueMode = "direct" | "indirect";

/** Reasoning summary mode for supported model clients. */
declare type OptionsUpdateReasoningSummary = "none" | "concise" | "detailed";

/** Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. */
declare type OptionsUpdateToolFilterPrecedence = "available" | "excluded";

declare type OrphanedToolPermissionState = "interrupted" | "awaiting-permission" | "approved" | "denied" | "awaiting-external-tool" | "external-tool-completed";

declare interface OrphanedToolResumeInfo {
    toolCallId: string;
    toolName: string;
    args: unknown;
    state: OrphanedToolPermissionState;
    permissionRequestId?: string;
    permissionResult?: PermissionRequestResult;
    permissionRequest?: PermissionRequest_2;
    externalToolRequestId?: string;
    externalToolCompletion?: ExternalToolCompletion;
    externalToolRequest?: {
        sessionId: string;
        toolName: string;
        arguments: unknown;
    };
}

declare type OutputInstructionsMode = "response_text" | "inbox";

/**
 * Controls how a {@link SendOptions} message interacts with the agent loop
 * when no opportunistic delivery is available.
 *
 * - `false` (or omitted): the message wakes / continues / restarts the loop.
 * - `{ type: "wait-for-next-turn" }`: the message is buffered and drained
 *   on the next user-driven turn.
 * - `{ type: "drop" }`: the message is discarded if it cannot ride along on
 *   an already-scheduled model call.
 */
export declare type PassivePolicy = false | {
    type: "drop" | "wait-for-next-turn";
};

declare type PathManager = NativePathManager;

/**
 * A path permission prompt emitted after the permission service has already
 * identified which paths need explicit approval.
 */
declare type PathPermissionAccessKind = "read" | "shell" | "write";

declare type PathPermissionPromptRequest = {
    readonly kind: "path";
    readonly accessKind: PathPermissionAccessKind;
    readonly paths: ReadonlyArray<PossiblePath>;
    readonly toolCallId?: string;
    readonly autoApproval?: AutoApproval;
};

/** A still-pending elicitation request with its original payload and source (for switch-back re-surfacing). */
declare type PendingElicitationRequest = {
    requestId: string;
    request: ElicitRequestParams;
    elicitationSource?: string;
};

/** Empty payload; the event signals that the pending message queue has changed */
export declare interface PendingMessagesModifiedData {
}

/** Session event "pending_messages.modified". Empty payload; the event signals that the pending message queue has changed */
export declare interface PendingMessagesModifiedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Empty payload; the event signals that the pending message queue has changed */
    data: PendingMessagesModifiedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "pending_messages.modified". */
    type: "pending_messages.modified";
}

/** Pending permission prompt reconstructed from event history, with request ID and user-facing prompt details. */
declare interface PendingPermissionRequest {
    /** The user-facing permission prompt details (commands, write, read, mcp, url, memory, custom-tool, path, hook) */
    request: PermissionPromptRequest;
    /** Unique identifier for the pending permission request */
    requestId: string;
}

/** List of pending permission requests reconstructed from event history. */
declare interface PendingPermissionRequestList {
    /** Pending permission prompts reconstructed from the session's event history. Equivalent to the set of `permission.requested` events that have not yet been followed by a matching `permission.completed` event. Used by clients (e.g. the CLI) to hydrate UI for prompts that were emitted before the client attached to the session. */
    items: PendingPermissionRequest[];
}

declare type PendingQueuedItem = Awaited<ReturnType<SessionQueueApi["pendingItems"]>>["items"][number];

/**
 * Manages the request/response lifecycle for permission and user-input interactions.
 *
 * Rust owns the deterministic request metadata, prompt lookup/tombstone state,
 * duplicate-response decisions, and emitted event payload plans. TypeScript
 * keeps only JS-owned live effects: Promise resolvers, OAuth provider objects,
 * timers, and the two event callbacks.
 */
declare class PendingRequestStore {
    private readonly emitEphemeral;
    private readonly emit;
    private readonly sessionId;
    private readonly permissionRequests;
    private readonly userInputRequests;
    private readonly elicitationRequests;
    private readonly samplingRequests;
    private readonly mcpOAuthRequests;
    private readonly mcpHeadersRefreshRequests;
    private mcpConnectionRequestsClosed;
    private readonly externalToolRequests;
    private readonly queuedCommandRequests;
    private readonly commandExecutionRequests;
    private readonly exitPlanModeRequests;
    private readonly autoModeSwitchRequests;
    private readonly sessionLimitsExhaustedRequests;
    constructor(emitEphemeral: (type: string, data: Record<string, unknown>) => void, emit: (type: string, data: Record<string, unknown>) => void, sessionId: string);
    addHookAllowedToolCallId(toolCallId: string): void;
    clearHookAllowedToolCallIds(): void;
    isHookAllowedToolCallId(toolCallId: string): boolean;
    /** Emit a permission request event (raw + derived prompt data) and return a promise for the client's response. */
    requestPermissionPrompt<TResponse extends PermissionPromptResponse>(permissionRequest: PermissionRequest_2, promptRequest: PermissionPromptRequest_2): Promise<TResponse>;
    /** Emit a user input request event and return a promise that resolves when responded to. */
    requestUserInput(request: UserInputRequest): Promise<UserInputResponse>;
    /** Respond to a pending permission request by its ID. */
    respondToPermission(requestId: string, result: PermissionPromptResponse): boolean;
    /** Respond and return the removed request context only to the accepted caller. */
    respondToPermissionWithContext(requestId: string, result: PermissionPromptResponse): PermissionResponseResolution;
    /**
     * Respond to a pending user input request by its ID. Returns true if the
     * request was still pending (and was resolved by this call), false if the
     * request ID was unknown or already resolved.
     */
    respondToUserInput(requestId: string, response: UserInputResponse): boolean;
    /** Emit an elicitation request event and return a promise that resolves when responded to. */
    requestElicitation(request: ElicitRequestWithToolCallId): Promise<ElicitResult>;
    requestElicitation(request: ElicitRequestParams, elicitationSource: string): Promise<ElicitResult>;
    /** Respond to a pending elicitation request by its ID. */
    respondToElicitation(requestId: string, response: ElicitResult): void;
    /**
     * Try to respond to a pending elicitation request by its ID.
     * Returns true if the request was found and resolved, false if already resolved.
     */
    tryRespondToElicitation(requestId: string, response: ElicitResult): boolean;
    /** Emit a sampling request event and return a promise that resolves when responded to. */
    requestSampling(serverName: string, mcpRequestId: string | number, request: CreateMessageRequestParams): Promise<CreateMessageResultWithTools | undefined>;
    /**
     * Respond to a pending sampling request by its ID. Response is optional
     * for reject/cancel.
     */
    respondToSampling(requestId: string, response?: CreateMessageResultWithTools): boolean;
    /** Cancel all pending requests tied to a specific capability. */
    cancelRequestsForCapability(capability: string): void;
    /** Emit an MCP OAuth request event and return a promise that resolves when a client responds with a provider. */
    requestMcpOAuth(serverName: string, serverUrl: string, provider: OAuthClientProvider, staticClientConfig?: McpOAuthStaticClientConfig, redirectPort?: number, wwwAuthenticateParams?: McpOAuthWWWAuthenticateParams, resourceMetadata?: string, httpResponse?: McpOAuthHttpResponse, reason?: McpOAuthRequestReason, signal?: AbortSignal): Promise<OAuthClientProvider | undefined>;
    /** Start an MCP OAuth request while retaining its generated request ID for cross-client dismissal. */
    requestMcpOAuthTracked(serverName: string, serverUrl: string, provider: OAuthClientProvider, staticClientConfig?: McpOAuthStaticClientConfig, redirectPort?: number, wwwAuthenticateParams?: McpOAuthWWWAuthenticateParams, resourceMetadata?: string, httpResponse?: McpOAuthHttpResponse, reason?: McpOAuthRequestReason): {
        requestId: string;
        response: Promise<OAuthClientProvider | undefined>;
    };
    getMcpOAuthRequest(requestId: string): McpOAuthPendingRequest | undefined;
    /** Respond to a pending MCP OAuth request by its ID. */
    respondToMcpOAuth(requestId: string, provider: OAuthClientProvider | undefined): boolean;
    /** Cancel OAuth prompts superseded by an authentication change from another client or process. */
    cancelPendingMcpOAuthRequests(serverName?: string): number;
    private cancelAllMcpOAuthRequests;
    /** Emit an MCP headers refresh request event and return the host's dynamic headers response. */
    requestMcpHeadersRefresh(request: HeadersRefreshRequest, timeoutMs?: number): Promise<Record<string, string> | undefined>;
    /**
     * Respond to a pending MCP headers refresh request. `undefined` means the
     * host has no dynamic headers for this refresh and is not cached by the manager.
     */
    respondToMcpHeadersRefresh(requestId: string, headers: Record<string, string> | undefined): boolean;
    private cancelAllMcpHeadersRefreshRequests;
    /** Close MCP connection-time SDK interactions and settle any requests already waiting for a client. */
    closeMcpConnectionRequests(): void;
    /**
     * Settle MCP connection-time SDK interactions (OAuth + dynamic headers
     * refresh) currently waiting on a client, WITHOUT marking the store closed.
     *
     * Unlike {@link closeMcpConnectionRequests} (terminal, used at full session
     * teardown), this leaves the store able to serve new OAuth/header requests.
     * A host reload disposes the outgoing host while these requests may still be
     * pending, and `McpHost.dispose()` awaits the host's connection/configuration
     * chains — which block on these very requests (OAuth has no timeout; a headers
     * refresh waits up to 120s). Draining them here lets the outgoing host tear
     * down promptly without disabling the interactions for the replacement host.
     */
    cancelMcpConnectionRequests(): void;
    /** Emit an external tool request event and return a promise that resolves when responded to. */
    requestExternalTool(request: ExternalToolRequest): Promise<ToolResult>;
    /** Start an external tool request while retaining its generated request ID for cross-client dismissal. */
    requestExternalToolTracked(request: ExternalToolRequest): {
        requestId: string;
        response: Promise<ToolResult>;
    };
    /** Respond to a pending external tool request by its ID. */
    respondToExternalTool(requestId: string, result: ToolResult): boolean;
    /** Reject a pending external tool request (e.g., on abort). */
    rejectExternalTool(requestId: string, error: Error): boolean;
    /** Reject all pending external tool requests (e.g., when the session is aborted). */
    rejectAllExternalTools(error: Error): void;
    /**
     * Cancel all pending permission requests, emitting a terminal
     * `permission.completed` for each so clients dismiss any open prompt. The
     * completion is emitted persistently (matching `requestPermissionPrompt` and
     * `Session.respondToPermission`) so it is replayed on re-attach — otherwise a
     * cancelled request (e.g. an extension/hook permission gate) would leave its
     * persisted `permission.requested` with no matching completion and the prompt
     * would stick and reappear on every re-attach.
     */
    cancelAllPermissions(reason: string): void;
    /** Emit a queued command event and return a promise that resolves when responded to. */
    requestQueuedCommand(command: string): Promise<QueuedCommandResult_2>;
    /**
     * Respond to a pending queued command request by its ID. Returns true
     * when a pending entry was found and resolved.
     */
    respondToQueuedCommand(requestId: string, result: QueuedCommandResult_2): boolean;
    /** Reject all pending queued command requests (e.g., when the session is aborted). */
    rejectAllQueuedCommands(error: Error): void;
    /**
     * Create a pending command execution and emit a command.execute event.
     * The server intercepts this event and routes to the owning connection.
     */
    executeCommand(commandName: string, args: string): Promise<CommandExecutionResult>;
    /** Respond to a pending command execution request by its ID. Returns true if a request was found. */
    respondToCommandExecution(requestId: string, error?: string): boolean;
    /** Reject pending command executions for specific command names (e.g., on client disconnect). */
    rejectCommandExecutionsForNames(commandNames: Set<string>, error: Error): void;
    /** Reject all pending command execution requests (e.g., when the session is aborted). */
    rejectAllCommandExecutions(error: Error): void;
    /** Emit an exit plan mode request event and return a promise that resolves when responded to. */
    requestExitPlanMode(request: ExitPlanModeRequest, planContent?: string): Promise<ExitPlanModeResponse>;
    /**
     * Create a pending exit plan mode request, emit the event, and return both the requestId and promise.
     * Use this when the caller needs the requestId to route a callback response through respondToExitPlanMode().
     */
    createExitPlanModeRequest(request: ExitPlanModeRequest, planContent?: string): {
        requestId: string;
        promise: Promise<ExitPlanModeResponse>;
    };
    /** Respond to a pending exit plan mode request by its ID. */
    respondToExitPlanMode(requestId: string, response: ExitPlanModeResponse): boolean;
    /** Emit an auto-mode switch request and return a promise that resolves when responded to. */
    requestAutoModeSwitch(errorCode: string | undefined, retryAfterSeconds: number | undefined): Promise<AutoModeSwitchResponse_2>;
    /**
     * Respond to a pending auto-mode switch request by its ID. Returns true if
     * the request was still pending (and was resolved by this call).
     */
    respondToAutoModeSwitch(requestId: string, response: AutoModeSwitchResponse_2): boolean;
    /** Emit an exhausted session-limit request and return a promise that resolves when responded to. */
    requestSessionLimitsExhausted(usedAiCredits: number, maxAiCredits: number): Promise<SessionLimitsExhaustedResponse_2>;
    /**
     * Respond to a pending exhausted session-limit request by its ID. Returns
     * true if the request was still pending, false if already resolved.
     */
    respondToSessionLimitsExhausted(requestId: string, response: SessionLimitsExhaustedResponse_2): boolean;
    private nativeRequest;
    private nativeRespond;
    private nativeDrain;
}

/** A still-pending ask_user request with its original payload (for switch-back re-surfacing). */
declare type PendingUserInputRequest = {
    requestId: string;
    request: UserInputRequest;
};

/** Allow-all mode for the session. */
export declare type PermissionAllowAllMode = "off" | "on" | "auto";

/** Permission response variant indicating the request was approved without persisting an approval rule. */
export declare interface PermissionApproved {
    /** The permission request was approved */
    kind: "approved";
}

/** Permission response variant that approves a request and persists the provided approval to a project location key. */
export declare interface PermissionApprovedForLocation {
    /** The approval to persist for this location */
    approval: UserToolSessionApproval;
    /** Approved and persisted for this project location */
    kind: "approved-for-location";
    /** The location key (git root or cwd) to persist the approval to */
    locationKey: string;
}

/** Permission response variant that approves a request and remembers the provided approval for the rest of the session. */
export declare interface PermissionApprovedForSession {
    /** The approval to add as a session-scoped rule */
    approval: UserToolSessionApproval;
    /** Approved and remembered for the rest of the session */
    kind: "approved-for-session";
}

/** Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is "auto"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request. */
export declare interface PermissionAutoApproval {
    /** Classified cause of an `error` recommendation. Absent for every other recommendation. */
    failureReason?: AutoApprovalJudgeFailureReason;
    /** Model id that produced the recommendation, when the judge was consulted and reported one. Absent for `excluded` (the judge was not consulted) and for failures that occurred before a model was selected. */
    model?: string;
    /** Human-readable reason for the judge's recommendation, when available. */
    reason?: string;
    /** The auto-approval safety judge's outcome for this request. */
    recommendation: AutoApprovalRecommendation;
}

/** Permission response variant indicating the request was cancelled before use, with an optional reason. */
export declare interface PermissionCancelled {
    /** The permission request was cancelled before a response was used */
    kind: "cancelled";
    /** Optional explanation of why the request was cancelled */
    reason?: string;
}

/** Permission request completion notification signaling UI dismissal */
export declare interface PermissionCompletedData {
    /** Request ID of the resolved permission request; clients should dismiss any UI for this request */
    requestId: string;
    /** The result of the permission request */
    result: PermissionResult;
    /** Optional tool call ID associated with this permission prompt; clients may use it to correlate UI created from tool-scoped prompts */
    toolCallId?: string;
}

/** Session event "permission.completed". Permission request completion notification signaling UI dismissal */
export declare interface PermissionCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Permission request completion notification signaling UI dismissal */
    data: PermissionCompletedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "permission.completed". */
    type: "permission.completed";
}

/** The client's response to the pending permission prompt */
declare type PermissionDecision = PermissionDecisionApproveOnce | PermissionDecisionApproveForSession | PermissionDecisionApproveForLocation | PermissionDecisionApprovePermanently | PermissionDecisionReject | PermissionDecisionUserNotAvailable | PermissionDecisionApproved | PermissionDecisionApprovedForSession | PermissionDecisionApprovedForLocation | PermissionDecisionCancelled | PermissionDecisionDeniedByRules | PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser | PermissionDecisionDeniedInteractivelyByUser | PermissionDecisionDeniedByContentExclusionPolicy | PermissionDecisionDeniedByPermissionRequestHook;

/** Permission-decision variant indicating the request was approved. */
declare interface PermissionDecisionApproved {
    /** The permission request was approved */
    kind: "approved";
}

/** Permission-decision variant indicating approval was persisted for a project location, with approval details and location key. */
declare interface PermissionDecisionApprovedForLocation {
    /** The approval to persist for this location */
    approval: UserToolSessionApproval_2;
    /** Approved and persisted for this project location */
    kind: "approved-for-location";
    /** The location key (git root or cwd) to persist the approval to */
    locationKey: string;
}

/** Permission-decision variant indicating approval was remembered for the session, with approval details. */
declare interface PermissionDecisionApprovedForSession {
    /** The approval to add as a session-scoped rule */
    approval: UserToolSessionApproval_2;
    /** Approved and remembered for the rest of the session */
    kind: "approved-for-session";
}

/** Permission-decision request variant to approve and persist a permission for a project location, with approval details and location key. */
declare interface PermissionDecisionApproveForLocation {
    /** Approval to persist for this location */
    approval: PermissionDecisionApproveForLocationApproval;
    /** Approve and persist for this project location */
    kind: "approve-for-location";
    /** Location key (git root or cwd) to persist the approval to */
    locationKey: string;
}

/** Approval to persist for this location */
declare type PermissionDecisionApproveForLocationApproval = PermissionDecisionApproveForLocationApprovalCommands | PermissionDecisionApproveForLocationApprovalRead | PermissionDecisionApproveForLocationApprovalWrite | PermissionDecisionApproveForLocationApprovalMcp | PermissionDecisionApproveForLocationApprovalMcpSampling | PermissionDecisionApproveForLocationApprovalMemory | PermissionDecisionApproveForLocationApprovalCustomTool | PermissionDecisionApproveForLocationApprovalExtensionManagement | PermissionDecisionApproveForLocationApprovalFactory | PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess;

/** Location-scoped approval details for specific command identifiers. */
declare interface PermissionDecisionApproveForLocationApprovalCommands {
    /** Command identifiers covered by this approval. */
    commandIdentifiers: string[];
    /** Approval scoped to specific command identifiers. */
    kind: "commands";
}

/** Location-scoped approval details for a custom tool, keyed by tool name. */
declare interface PermissionDecisionApproveForLocationApprovalCustomTool {
    /** Approval covering a custom tool. */
    kind: "custom-tool";
    /** Custom tool name. */
    toolName: string;
}

/** Location-scoped approval details for extension-management operations, optionally narrowed by operation. */
declare interface PermissionDecisionApproveForLocationApprovalExtensionManagement {
    /** Approval covering extension lifecycle operations such as enable, disable, or reload. */
    kind: "extension-management";
    /** Optional operation identifier; when omitted, the approval covers all extension management operations. */
    operation?: string;
}

/** Location-scoped approval details for an extension's permission-gated capability access, keyed by extension name. */
declare interface PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess {
    /** Extension name. */
    extensionName: string;
    /** Approval covering an extension's request to access a permission-gated capability. */
    kind: "extension-permission-access";
}

/** Location-scoped factory approval, optionally narrowed by approval key. */
declare interface PermissionDecisionApproveForLocationApprovalFactory {
    /** Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. */
    approvalKey?: string;
    /** Approval covering factory operations. */
    kind: "factory";
}

/** Location-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. */
declare interface PermissionDecisionApproveForLocationApprovalMcp {
    /** Approval covering an MCP tool. */
    kind: "mcp";
    /** MCP server name. */
    serverName: string;
    /** MCP tool name, or null to cover every tool on the server. */
    toolName: string | null;
}

/** Location-scoped approval details for MCP sampling requests from a server. */
declare interface PermissionDecisionApproveForLocationApprovalMcpSampling {
    /** Approval covering MCP sampling requests for a server. */
    kind: "mcp-sampling";
    /** MCP server name. */
    serverName: string;
}

/** Location-scoped approval details for writes to long-term memory. */
declare interface PermissionDecisionApproveForLocationApprovalMemory {
    /** Approval covering writes to long-term memory. */
    kind: "memory";
}

/** Location-scoped approval details for read-only filesystem operations. */
declare interface PermissionDecisionApproveForLocationApprovalRead {
    /** Approval covering read-only filesystem operations. */
    kind: "read";
}

/** Location-scoped approval details for filesystem write operations. */
declare interface PermissionDecisionApproveForLocationApprovalWrite {
    /** Approval covering filesystem write operations. */
    kind: "write";
}

/** Permission-decision request variant to approve for the rest of the session, with optional tool approval or URL domain. */
declare interface PermissionDecisionApproveForSession {
    /** Session-scoped approval to remember (tool prompts only; omitted for path/url prompts) */
    approval?: PermissionDecisionApproveForSessionApproval;
    /** URL domain to approve for the rest of the session (URL prompts only) */
    domain?: string;
    /** Approve and remember for the rest of the session */
    kind: "approve-for-session";
}

/** Session-scoped approval to remember (tool prompts only; omitted for path/url prompts) */
declare type PermissionDecisionApproveForSessionApproval = PermissionDecisionApproveForSessionApprovalCommands | PermissionDecisionApproveForSessionApprovalRead | PermissionDecisionApproveForSessionApprovalWrite | PermissionDecisionApproveForSessionApprovalMcp | PermissionDecisionApproveForSessionApprovalMcpSampling | PermissionDecisionApproveForSessionApprovalMemory | PermissionDecisionApproveForSessionApprovalCustomTool | PermissionDecisionApproveForSessionApprovalExtensionManagement | PermissionDecisionApproveForSessionApprovalFactory | PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess;

/** Session-scoped approval details for specific command identifiers. */
declare interface PermissionDecisionApproveForSessionApprovalCommands {
    /** Command identifiers covered by this approval. */
    commandIdentifiers: string[];
    /** Approval scoped to specific command identifiers. */
    kind: "commands";
}

/** Session-scoped approval details for a custom tool, keyed by tool name. */
declare interface PermissionDecisionApproveForSessionApprovalCustomTool {
    /** Approval covering a custom tool. */
    kind: "custom-tool";
    /** Custom tool name. */
    toolName: string;
}

/** Session-scoped approval details for extension-management operations, optionally narrowed by operation. */
declare interface PermissionDecisionApproveForSessionApprovalExtensionManagement {
    /** Approval covering extension lifecycle operations such as enable, disable, or reload. */
    kind: "extension-management";
    /** Optional operation identifier; when omitted, the approval covers all extension management operations. */
    operation?: string;
}

/** Session-scoped approval details for an extension's permission-gated capability access, keyed by extension name. */
declare interface PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess {
    /** Extension name. */
    extensionName: string;
    /** Approval covering an extension's request to access a permission-gated capability. */
    kind: "extension-permission-access";
}

/** Session-scoped factory approval, optionally narrowed by approval key. */
declare interface PermissionDecisionApproveForSessionApprovalFactory {
    /** Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. */
    approvalKey?: string;
    /** Approval covering factory operations. */
    kind: "factory";
}

/** Session-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. */
declare interface PermissionDecisionApproveForSessionApprovalMcp {
    /** Approval covering an MCP tool. */
    kind: "mcp";
    /** MCP server name. */
    serverName: string;
    /** MCP tool name, or null to cover every tool on the server. */
    toolName: string | null;
}

/** Session-scoped approval details for MCP sampling requests from a server. */
declare interface PermissionDecisionApproveForSessionApprovalMcpSampling {
    /** Approval covering MCP sampling requests for a server. */
    kind: "mcp-sampling";
    /** MCP server name. */
    serverName: string;
}

/** Session-scoped approval details for writes to long-term memory. */
declare interface PermissionDecisionApproveForSessionApprovalMemory {
    /** Approval covering writes to long-term memory. */
    kind: "memory";
}

/** Session-scoped approval details for read-only filesystem operations. */
declare interface PermissionDecisionApproveForSessionApprovalRead {
    /** Approval covering read-only filesystem operations. */
    kind: "read";
}

/** Session-scoped approval details for filesystem write operations. */
declare interface PermissionDecisionApproveForSessionApprovalWrite {
    /** Approval covering filesystem write operations. */
    kind: "write";
}

/** Permission-decision request variant to approve only the current permission request. */
declare interface PermissionDecisionApproveOnce {
    /** True only when a host surfaced this request to a user who approved it. */
    approvedInteractively?: boolean;
    /** Approve this single request only */
    kind: "approve-once";
}

/** Permission-decision request variant to permanently approve a URL domain across sessions. */
declare interface PermissionDecisionApprovePermanently {
    /** URL domain to approve permanently */
    domain: string;
    /** Approve and persist across sessions (URL prompts only) */
    kind: "approve-permanently";
}

/** Permission-decision variant indicating the request was cancelled before use, with an optional reason. */
declare interface PermissionDecisionCancelled {
    /** The permission request was cancelled before a response was used */
    kind: "cancelled";
    /** Optional explanation of why the request was cancelled */
    reason?: string;
}

/** Optional informational context describing how and where the permission decision was made. This does not affect permission behavior. */
declare interface PermissionDecisionContext {
    /** Disposition of the permission request as observed by the responding client. */
    outcome: PermissionDecisionOutcome;
    /** Controlled reason or actor responsible for the response. */
    source: PermissionDecisionSource;
    /** Client surface that submitted the response. */
    surface: PermissionDecisionSurface;
}

/** Permission-decision variant indicating denial by content-exclusion policy, with path and message. */
declare interface PermissionDecisionDeniedByContentExclusionPolicy {
    /** Denied by the organization's content exclusion policy */
    kind: "denied-by-content-exclusion-policy";
    /** Human-readable explanation of why the path was excluded */
    message: string;
    /** File path that triggered the exclusion */
    path: string;
}

/** Permission-decision variant indicating denial by a permission request hook, with optional message and interrupt flag. */
declare interface PermissionDecisionDeniedByPermissionRequestHook {
    /** Whether to interrupt the current agent turn */
    interrupt?: boolean;
    /** Denied by a permission request hook registered by an extension or plugin */
    kind: "denied-by-permission-request-hook";
    /** Optional message from the hook explaining the denial */
    message?: string;
}

/** Permission-decision variant indicating explicit denial by permission rules, with the matching rules. */
declare interface PermissionDecisionDeniedByRules {
    /** Denied because approval rules explicitly blocked it */
    kind: "denied-by-rules";
    /** Rules that denied the request */
    rules: PermissionRule_2[];
}

/** Permission-decision variant indicating the user denied an interactive prompt, with optional feedback and force-reject flag. */
declare interface PermissionDecisionDeniedInteractivelyByUser {
    /** Optional feedback from the user explaining the denial */
    feedback?: string;
    /** Whether to force-reject the current agent turn */
    forceReject?: boolean;
    /** Denied by the user during an interactive prompt */
    kind: "denied-interactively-by-user";
}

/** Permission-decision variant indicating no approval rule matched and user confirmation was unavailable. */
declare interface PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser {
    /** Denied because no approval rule matched and user confirmation was unavailable */
    kind: "denied-no-approval-rule-and-could-not-request-from-user";
}

/** Disposition of a permission request as observed by the responding client. */
declare type PermissionDecisionOutcome = "auto_approved" | "autopilot_denied" | "prompted_user";

/** Permission-decision request variant to reject a pending permission request, with optional feedback. */
declare interface PermissionDecisionReject {
    /** Optional feedback explaining the rejection */
    feedback?: string;
    /** Reject the request */
    kind: "reject";
}

/** Pending permission request ID and the decision to apply (approve/reject and scope). */
declare interface PermissionDecisionRequest {
    /** Optional informational context describing how and where this response was made. Omit it to preserve legacy behavior without attributing an origin. */
    decisionContext?: PermissionDecisionContext;
    /** Request ID of the pending permission request */
    requestId: string;
    /** The client's response to the pending permission prompt */
    result: PermissionDecision;
}

/** Controlled reason or actor responsible for a permission response. */
declare type PermissionDecisionSource = "judge_recommendation" | "human_response" | "host_policy" | "unattended_fallback";

/** Client surface that submitted a permission response. */
declare type PermissionDecisionSurface = "tui" | "prompt_mode" | "copilot_app" | "sdk";

/** Permission-decision variant indicating no user was available to confirm the request. */
declare interface PermissionDecisionUserNotAvailable {
    /** No user is available to confirm the request */
    kind: "user-not-available";
}

/** Permission response variant denying a path under content exclusion policy, with the path and message. */
export declare interface PermissionDeniedByContentExclusionPolicy {
    /** Denied by the organization's content exclusion policy */
    kind: "denied-by-content-exclusion-policy";
    /** Human-readable explanation of why the path was excluded */
    message: string;
    /** File path that triggered the exclusion */
    path: string;
}

/** Permission response variant denied by a permission-request hook, with optional message and interrupt flag. */
export declare interface PermissionDeniedByPermissionRequestHook {
    /** Whether to interrupt the current agent turn */
    interrupt?: boolean;
    /** Denied by a permission request hook registered by an extension or plugin */
    kind: "denied-by-permission-request-hook";
    /** Optional message from the hook explaining the denial */
    message?: string;
}

/** Permission response variant denied because matching approval rules explicitly blocked the request. */
export declare interface PermissionDeniedByRules {
    /** Denied because approval rules explicitly blocked it */
    kind: "denied-by-rules";
    /** Rules that denied the request */
    rules: PermissionRule[];
}

/** Permission response variant denied in an interactive user prompt, with optional feedback and force-reject flag. */
export declare interface PermissionDeniedInteractivelyByUser {
    /** Optional feedback from the user explaining the denial */
    feedback?: string;
    /** Whether to force-reject the current agent turn */
    forceReject?: boolean;
    /** Denied by the user during an interactive prompt */
    kind: "denied-interactively-by-user";
}

/** Permission response variant denied because no approval rule matched and user confirmation was unavailable. */
export declare interface PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser {
    /** Denied because no approval rule matched and user confirmation was unavailable */
    kind: "denied-no-approval-rule-and-could-not-request-from-user";
}

/** Location-scoped tool approval to persist. */
declare interface PermissionLocationAddToolApprovalParams {
    /** Tool approval to persist and apply */
    approval: PermissionsLocationsAddToolApprovalDetails;
    /** Location key (git root or cwd) to persist the approval to */
    locationKey: string;
}

/** Working directory to load persisted location permissions for. */
declare interface PermissionLocationApplyParams {
    /** Working directory whose persisted location permissions should be applied */
    workingDirectory: string;
}

/** Summary of persisted location permissions applied to the session. */
declare interface PermissionLocationApplyResult {
    /** Number of persisted allowed directories added to the live path manager */
    appliedDirectoryCount: number;
    /** Number of location-scoped rules added to the live permission service */
    appliedRuleCount: number;
    /** Location-scoped rules applied to the live permission service */
    appliedRules: PermissionRule_2[];
    /** Whether a different location was applied since the previous apply call */
    changed: boolean;
    /** Location key used in the location-permissions store */
    locationKey: string;
    /** Whether the location is a git repo or directory */
    locationType: PermissionLocationType;
}

/** Working directory to resolve into a location-permissions key. */
declare interface PermissionLocationResolveParams {
    /** Working directory whose permission location should be resolved */
    workingDirectory: string;
}

/** Resolved location-permissions key and type. */
declare interface PermissionLocationResolveResult {
    /** Location key used in the location-permissions store */
    locationKey: string;
    /** Whether the location is a git repo or directory */
    locationType: PermissionLocationType;
}

/** Whether the location is a git repo or directory */
declare type PermissionLocationType = "repo" | "dir";

/** Directory path to add to the session's allowed directories. */
declare interface PermissionPathsAddParams {
    /** Directory to add to the allow-list. The runtime resolves and validates the path before adding. */
    path: string;
}

/** Path to evaluate against the session's allowed directories. */
declare interface PermissionPathsAllowedCheckParams {
    /** Path to check against the session's allowed directories */
    path: string;
}

/** Indicates whether the supplied path is within the session's allowed directories. */
declare interface PermissionPathsAllowedCheckResult {
    /** Whether the path is within the session's allowed directories */
    allowed: boolean;
}

/** If specified, replaces the session's path-permission policy. The runtime constructs the appropriate PathManager based on these inputs (rooted at the session's working directory). Omit to leave the current path policy unchanged. */
declare interface PermissionPathsConfig {
    /** Additional directories to allow tool access to (in addition to the session's working directory). When `unrestricted` is true, these are still pre-populated on the UnrestrictedPathManager so they remain visible via getDirectories() (e.g. for @-mention completion). */
    additionalDirectories?: string[];
    /** Whether to include the system temp directory in the allowed list (defaults to true). Ignored when `unrestricted` is true. */
    includeTempDirectory?: boolean;
    /** If true, the runtime allows access to all paths without prompting. Equivalent to constructing an UnrestrictedPathManager. */
    unrestricted?: boolean;
    /** Workspace root path (special-cased to be allowed even before the directory exists). Ignored when `unrestricted` is true. */
    workspacePath?: string;
}

/** Snapshot of the session's allow-listed directories and primary working directory. */
declare interface PermissionPathsList {
    /** All directories currently allowed for tool access on this session. */
    directories: string[];
    /** The primary working directory for this session. */
    primary: string;
}

/** Directory path to set as the session's new primary working directory. */
declare interface PermissionPathsUpdatePrimaryParams {
    /** Directory to set as the new primary working directory for the session's permission policy. */
    path: string;
}

/** Path to evaluate against the session's workspace (primary) directory. */
declare interface PermissionPathsWorkspaceCheckParams {
    /** Path to check against the session workspace directory */
    path: string;
}

/** Indicates whether the supplied path is within the session's workspace directory. */
declare interface PermissionPathsWorkspaceCheckResult {
    /** Whether the path is within the session workspace directory */
    allowed: boolean;
}

/** Derived user-facing permission prompt details for UI consumers */
export declare type PermissionPromptRequest = PermissionPromptRequestCommands | PermissionPromptRequestWrite | PermissionPromptRequestRead | PermissionPromptRequestMcp | PermissionPromptRequestUrl | PermissionPromptRequestMemory | PermissionPromptRequestCustomTool | PermissionPromptRequestPath | PermissionPromptRequestHook | PermissionPromptRequestExtensionManagement | PermissionPromptRequestFactory | PermissionPromptRequestExtensionPermissionAccess;

/**
 * A user-facing permission prompt payload emitted by the session.
 */
declare type PermissionPromptRequest_2 = UserToolPermissionRequest | PathPermissionPromptRequest | (UserUrlPermissionRequest & {
    readonly kind: "url";
}) | HookPermissionRequest;

/** Shell command permission prompt */
export declare interface PermissionPromptRequestCommands {
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Whether the UI can offer session-wide approval for this command pattern */
    canOfferSessionApproval: boolean;
    /** Command identifiers covered by this approval prompt */
    commandIdentifiers: string[];
    /** The complete shell command text to be executed */
    fullCommandText: string;
    /** Human-readable description of what the command intends to do */
    intention: string;
    /** Prompt kind discriminator */
    kind: "commands";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Optional warning message about risks of running this command */
    warning?: string;
}

/** Custom tool invocation permission prompt */
export declare interface PermissionPromptRequestCustomTool {
    /** Arguments to pass to the custom tool */
    args?: unknown;
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Prompt kind discriminator */
    kind: "custom-tool";
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Description of what the custom tool does */
    toolDescription: string;
    /** Name of the custom tool */
    toolName: string;
}

/** Extension management permission prompt */
export declare interface PermissionPromptRequestExtensionManagement {
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Name of the extension being managed */
    extensionName?: string;
    /** Prompt kind discriminator */
    kind: "extension-management";
    /** The extension management operation (scaffold, reload) */
    operation: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Extension permission access prompt */
export declare interface PermissionPromptRequestExtensionPermissionAccess {
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Capabilities the extension is requesting */
    capabilities: string[];
    /** Name of the extension requesting permission access */
    extensionName: string;
    /** Prompt kind discriminator */
    kind: "extension-permission-access";
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Factory run or authoring permission prompt */
export declare interface PermissionPromptRequestFactory {
    /** Canonical key used for scoped factory approvals */
    approvalKey: string;
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Whether this factory is eligible for persistent approval */
    canPersistApproval: boolean;
    declaredMaxAiCredits?: number;
    declaredMaxConcurrentSubagents?: number;
    declaredMaxTotalSubagents?: number;
    declaredTimeoutSeconds?: number;
    /** Factory description */
    description: string;
    /** Prompt kind discriminator */
    kind: "factory";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Effective AI-credit limit; omitted means unlimited */
    maxAiCredits?: number;
    /** Effective concurrent-subagent limit; omitted means unlimited */
    maxConcurrentSubagents?: number;
    /** Effective total-subagent limit; omitted means unlimited */
    maxTotalSubagents?: number;
    /** Factory name */
    name: string;
    /** Factory operation, either run or author */
    operation: FactoryPermissionOperation;
    /** Declared factory phases */
    phases: FactoryPermissionPhase[];
    /** Effective active-time limit in seconds; omitted means unlimited */
    timeoutSeconds?: number;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Hook confirmation permission prompt */
export declare interface PermissionPromptRequestHook {
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Optional message from the hook explaining why confirmation is needed */
    hookMessage?: string;
    /** Prompt kind discriminator */
    kind: "hook";
    /** Arguments of the tool call being gated */
    toolArgs?: unknown;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Name of the tool the hook is gating */
    toolName: string;
}

/** MCP tool invocation permission prompt */
export declare interface PermissionPromptRequestMcp {
    /** Arguments to pass to the MCP tool */
    args?: unknown;
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Prompt kind discriminator */
    kind: "mcp";
    /** Name of the MCP server providing the tool */
    serverName: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Internal name of the MCP tool */
    toolName: string;
    /** Human-readable title of the MCP tool */
    toolTitle: string;
}

/** Memory operation permission prompt */
export declare interface PermissionPromptRequestMemory {
    /** Whether this is a store or vote memory operation */
    action?: PermissionRequestMemoryAction;
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Source references for the stored fact (store only) */
    citations?: string;
    /** Vote direction (vote only) */
    direction?: PermissionRequestMemoryDirection;
    /** The fact being stored or voted on */
    fact: string;
    /** Prompt kind discriminator */
    kind: "memory";
    /** Reason for the vote (vote only) */
    reason?: string;
    /** Topic or subject of the memory (store only) */
    subject?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Path access permission prompt */
export declare interface PermissionPromptRequestPath {
    /** Underlying permission kind that needs path approval */
    accessKind: PermissionPromptRequestPathAccessKind;
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Prompt kind discriminator */
    kind: "path";
    /** File paths that require explicit approval */
    paths: string[];
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Underlying permission kind that needs path approval */
export declare type PermissionPromptRequestPathAccessKind = "read" | "shell" | "write";

/** File read permission prompt */
export declare interface PermissionPromptRequestRead {
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Human-readable description of why the file is being read */
    intention: string;
    /** Prompt kind discriminator */
    kind: "read";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Path of the file or directory being read */
    path: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** URL access permission prompt */
export declare interface PermissionPromptRequestUrl {
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Human-readable description of why the URL is being accessed */
    intention: string;
    /** Prompt kind discriminator */
    kind: "url";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Immediately preceding URL when this prompt is for a redirect target */
    redirectedFrom?: string;
    /** True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. */
    requestSandboxBypass?: boolean;
    /** Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. */
    requestSandboxBypassReason?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** URL to be fetched */
    url: string;
}

/** File write permission prompt */
export declare interface PermissionPromptRequestWrite {
    /** Auto-approval judge information for this request; present only when auto mode is enabled. */
    autoApproval?: PermissionAutoApproval;
    /** Whether the UI can offer session-wide approval for file write operations */
    canOfferSessionApproval: boolean;
    /** Unified diff showing the proposed changes */
    diff: string;
    /** Path of the file being written to */
    fileName: string;
    /** Human-readable description of the intended file change */
    intention: string;
    /** Prompt kind discriminator */
    kind: "write";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Complete new file contents for newly created files */
    newFileContents?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** A client response to a pending user-facing permission prompt. */
declare type PermissionPromptResponse = PermissionRequestResult | UserToolPermissionRequestResponse<UserToolPermissionRequest["kind"]> | UserPathPermissionRequestResponse | UserUrlPermissionRequestResponse;

/** Notification payload describing the permission prompt that the client just rendered. */
declare interface PermissionPromptShownNotification {
    /** Human-readable description of the prompt the user is being asked to approve. Used by the runtime to fire the registered `permission_prompt` notification hook (e.g. terminal bell, desktop notification). */
    message: string;
}

/** Details of the permission being requested */
export declare type PermissionRequest = PermissionRequestShell | PermissionRequestWrite | PermissionRequestRead | PermissionRequestMcp | PermissionRequestUrl | PermissionRequestMemory | PermissionRequestCustomTool | PermissionRequestHook | PermissionRequestExtensionManagement | PermissionRequestFactory | PermissionRequestExtensionPermissionAccess;

/**
 * A permission request which will be used to check tool or path usage against config and/or request user approval.
 */
declare type PermissionRequest_2 = {
    toolCallId?: string;
} & (ShellPermissionRequest | WritePermissionRequest | MCPPermissionRequest | ReadPermissionRequest | UrlPermissionRequest | MemoryPermissionRequest | CustomToolPermissionRequest | HookPermissionRequest | ExtensionManagementPermissionRequest | FactoryPermissionRequest | ExtensionPermissionAccessRequest);

declare interface PermissionRequestContext {
    permissionRequest?: PermissionRequest_2;
    promptRequest?: PermissionPromptRequest_2 | PermissionPromptRequest;
}

/** Custom tool invocation permission request */
export declare interface PermissionRequestCustomTool {
    /** Arguments to pass to the custom tool */
    args?: unknown;
    /** Permission kind discriminator */
    kind: "custom-tool";
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Description of what the custom tool does */
    toolDescription: string;
    /** Name of the custom tool */
    toolName: string;
}

/** Permission request notification requiring client approval with request details */
export declare interface PermissionRequestedData {
    /** Details of the permission being requested */
    permissionRequest: PermissionRequest;
    /** Derived user-facing permission prompt details for UI consumers */
    promptRequest?: PermissionPromptRequest;
    /** Unique identifier for this permission request; used to respond via session.respondToPermission() */
    requestId: string;
    /** When true, this permission was already resolved by a permissionRequest hook and requires no client action */
    resolvedByHook?: boolean;
    /** Neutral risk metadata supplied by the tool host. Consumers may display this value but must not use it to bypass the permission decision. */
    riskAssessment?: unknown;
}

/** Session event "permission.requested". Permission request notification requiring client approval with request details */
export declare interface PermissionRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Permission request notification requiring client approval with request details */
    data: PermissionRequestedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "permission.requested". */
    type: "permission.requested";
}

/** Extension management permission request */
export declare interface PermissionRequestExtensionManagement {
    /** Name of the extension being managed */
    extensionName?: string;
    /** Permission kind discriminator */
    kind: "extension-management";
    /** The extension management operation (scaffold, reload) */
    operation: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Extension permission access request */
export declare interface PermissionRequestExtensionPermissionAccess {
    /** Capabilities the extension is requesting */
    capabilities: string[];
    /** Name of the extension requesting permission access */
    extensionName: string;
    /** Permission kind discriminator */
    kind: "extension-permission-access";
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Factory run or authoring permission request */
export declare interface PermissionRequestFactory {
    /** Canonical key used for scoped factory approvals */
    approvalKey: string;
    /** Whether this factory is eligible for persistent approval */
    canPersistApproval: boolean;
    declaredMaxAiCredits?: number;
    declaredMaxConcurrentSubagents?: number;
    declaredMaxTotalSubagents?: number;
    declaredTimeoutSeconds?: number;
    /** Factory description */
    description: string;
    /** Permission kind discriminator */
    kind: "factory";
    /** Effective AI-credit limit; omitted means unlimited */
    maxAiCredits?: number;
    /** Effective concurrent-subagent limit; omitted means unlimited */
    maxConcurrentSubagents?: number;
    /** Effective total-subagent limit; omitted means unlimited */
    maxTotalSubagents?: number;
    /** Factory name */
    name: string;
    /** Factory operation, either run or author */
    operation: FactoryPermissionOperation;
    /** Declared factory phases */
    phases: FactoryPermissionPhase[];
    /** Effective active-time limit in seconds; omitted means unlimited */
    timeoutSeconds?: number;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Hook confirmation permission request */
export declare interface PermissionRequestHook {
    /** Optional message from the hook explaining why confirmation is needed */
    hookMessage?: string;
    /** Permission kind discriminator */
    kind: "hook";
    /** Arguments of the tool call being gated */
    toolArgs?: unknown;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Name of the tool the hook is gating */
    toolName: string;
}

/** MCP tool invocation permission request */
export declare interface PermissionRequestMcp {
    /** Arguments to pass to the MCP tool */
    args?: unknown;
    /** Permission kind discriminator */
    kind: "mcp";
    /** Whether this MCP tool is read-only (no side effects) */
    readOnly: boolean;
    /** Name of the MCP server providing the tool */
    serverName: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Internal name of the MCP tool */
    toolName: string;
    /** Human-readable title of the MCP tool */
    toolTitle: string;
}

/** Memory operation permission request */
export declare interface PermissionRequestMemory {
    /** Whether this is a store or vote memory operation */
    action?: PermissionRequestMemoryAction;
    /** Source references for the stored fact (store only) */
    citations?: string;
    /** Vote direction (vote only) */
    direction?: PermissionRequestMemoryDirection;
    /** The fact being stored or voted on */
    fact: string;
    /** Permission kind discriminator */
    kind: "memory";
    /** Reason for the vote (vote only) */
    reason?: string;
    /** Topic or subject of the memory (store only) */
    subject?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** Whether this is a store or vote memory operation */
export declare type PermissionRequestMemoryAction = "store" | "vote";

/** Vote direction (vote only) */
export declare type PermissionRequestMemoryDirection = "upvote" | "downvote";

/** File or directory read permission request */
export declare interface PermissionRequestRead {
    /** Human-readable description of why the file is being read */
    intention: string;
    /** Permission kind discriminator */
    kind: "read";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Path of the file or directory being read */
    path: string;
    /** True when the model has requested to run this search outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the search runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. */
    requestSandboxBypass?: boolean;
    /** Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. */
    requestSandboxBypassReason?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/**
 * The result of requesting permissions.
 */
declare type PermissionRequestResult = {
    readonly kind: "approved";
    readonly managedApprovalHandled?: boolean;
} | {
    readonly kind: "approved-for-session";
    readonly approval: Extract<SessionApproval, {
        kind: UserToolPermissionRequest["kind"];
    }>;
    readonly managedApprovalHandled?: boolean;
} | {
    readonly kind: "approved-for-location";
    readonly approval: Extract<SessionApproval, {
        kind: UserToolPermissionRequest["kind"];
    }>;
    readonly locationKey: string;
    readonly managedApprovalHandled?: boolean;
} | {
    readonly kind: "cancelled";
    readonly reason?: string;
} | {
    readonly kind: "denied-by-rules";
    rules: ReadonlyArray<Rule>;
} | {
    readonly kind: "denied-no-approval-rule-and-could-not-request-from-user";
} | {
    readonly kind: "denied-interactively-by-user";
    readonly feedback?: string;
    readonly forceReject?: boolean;
} | {
    readonly kind: "denied-by-content-exclusion-policy";
    readonly path: string;
    readonly message: string;
} | {
    readonly kind: "denied-by-permission-request-hook";
    readonly message?: string;
    readonly interrupt?: boolean;
};

/** Indicates whether the permission decision was applied; false when the request was already resolved. */
declare interface PermissionRequestResult_2 {
    /** Whether the permission request was handled successfully */
    success: boolean;
}

/** Shell command permission request */
export declare interface PermissionRequestShell {
    /** Whether the UI can offer session-wide approval for this command pattern */
    canOfferSessionApproval: boolean;
    /** Parsed command segments, including arguments, used for managed policy matching */
    commandSegments?: PermissionRequestShellCommandSegment[];
    /** Parsed command identifiers found in the command text */
    commands: PermissionRequestShellCommand[];
    /** The complete shell command text to be executed */
    fullCommandText: string;
    /** Whether the command includes a file write redirection (e.g., > or >>) */
    hasWriteFileRedirection: boolean;
    /** Human-readable description of what the command intends to do */
    intention: string;
    /** Permission kind discriminator */
    kind: "shell";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** File paths that may be read or written by the command */
    possiblePaths: string[];
    /** URLs that may be accessed by the command */
    possibleUrls: PermissionRequestShellPossibleUrl[];
    /** True when the model has requested to run this command outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the command runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. */
    requestSandboxBypass?: boolean;
    /** Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. */
    requestSandboxBypassReason?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** Optional warning message about risks of running this command */
    warning?: string;
}

/** A parsed command identifier in a shell permission request, including whether it is read-only. */
export declare interface PermissionRequestShellCommand {
    /** Command identifier (e.g., executable name) */
    identifier: string;
    /** Whether this command is read-only (no side effects) */
    readOnly: boolean;
}

/** A parsed shell command segment used for argument-aware managed policy matching. */
export declare interface PermissionRequestShellCommandSegment {
    /** Full text of this command segment, including arguments */
    fullCommandText: string;
    /** Command identifier (e.g., executable name) */
    identifier: string;
}

/** A URL that may be accessed by a command in a shell permission request. */
export declare interface PermissionRequestShellPossibleUrl {
    /** URL that may be accessed by the command */
    url: string;
}

/** URL access permission request */
export declare interface PermissionRequestUrl {
    /** Human-readable description of why the URL is being accessed */
    intention: string;
    /** Permission kind discriminator */
    kind: "url";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Immediately preceding URL when this request is for a redirect target */
    redirectedFrom?: string;
    /** True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. */
    requestSandboxBypass?: boolean;
    /** Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. */
    requestSandboxBypassReason?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
    /** URL to be fetched */
    url: string;
}

/** File write permission request */
export declare interface PermissionRequestWrite {
    /** Whether the UI can offer session-wide approval for file write operations */
    canOfferSessionApproval: boolean;
    /** Unified diff showing the proposed changes */
    diff: string;
    /** Path of the file being written to */
    fileName: string;
    /** Human-readable description of the intended file change */
    intention: string;
    /** Permission kind discriminator */
    kind: "write";
    /** Whether managed policy requires a human response and forbids host auto-approval */
    managedApprovalRequired?: boolean;
    /** Complete new file contents for newly created files */
    newFileContents?: string;
    /** True when a built-in file tool (apply_patch / str_replace_editor) asked to write a path the sandbox filesystem policy would block, and the host opted in via sandbox.allowBypass. This is a request, not a grant: the write happens unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. */
    requestSandboxBypass?: boolean;
    /** Justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. */
    requestSandboxBypassReason?: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

declare interface PermissionResponseResolution {
    resolved: boolean;
    requestContext?: PermissionRequestContext;
}

declare interface PermissionResponseResult {
    success: boolean;
    requestContext?: PermissionRequestContext;
}

/** The result of the permission request */
export declare type PermissionResult = PermissionApproved | PermissionApprovedForSession | PermissionApprovedForLocation | PermissionCancelled | PermissionDeniedByRules | PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser | PermissionDeniedInteractivelyByUser | PermissionDeniedByContentExclusionPolicy | PermissionDeniedByPermissionRequestHook;

/** A permission approval or denial rule matched against a tool request, identified by a rule kind with an optional argument value. */
export declare interface PermissionRule {
    /** Argument value matched against the request, or null when the rule kind has no argument (e.g. 'read', 'write', 'memory'). */
    argument: string | null;
    /** The rule kind, such as Shell or GitHubMCP */
    kind: string;
}

/** A permission approval or denial rule matched against a tool request, identified by a rule kind with an optional argument value. */
declare interface PermissionRule_2 {
    /** Argument value matched against the request, or null when the rule kind has no argument (e.g. 'read', 'write', 'memory'). */
    argument: string | null;
    /** The rule kind, such as Shell or GitHubMCP */
    kind: string;
}

/** If specified, replaces the session's approved/denied permission rules. Omit to leave the current rules unchanged. */
declare interface PermissionRulesSet {
    /** Rules that auto-approve matching requests */
    approved: PermissionRule_2[];
    /** Rules that auto-deny matching requests */
    denied: PermissionRule_2[];
}

/** Current or requested allow-all mode. */
declare type PermissionsAllowAllMode = "off" | "on" | "auto";

/** Permissions change details carrying the aggregate allow-all transition. */
export declare interface PermissionsChangedData {
    /** Allow-all mode after the change */
    allowAllPermissionMode?: PermissionAllowAllMode;
    /** Aggregate allow-all flag after the change */
    allowAllPermissions: boolean;
    /** Allow-all mode before the change */
    previousAllowAllPermissionMode?: PermissionAllowAllMode;
    /** Aggregate allow-all flag before the change */
    previousAllowAllPermissions: boolean;
}

/** Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all transition. */
declare interface PermissionsChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Permissions change details carrying the aggregate allow-all transition. */
    data: PermissionsChangedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.permissions_changed". */
    type: "session.permissions_changed";
}
export { PermissionsChangedEvent }
export { PermissionsChangedEvent as SessionPermissionsChangedEvent }

/**
 * Configuration for permissions handling.
 *
 * For CCA, permissions requests are not required.
 */
declare type PermissionsConfig = {
    requestRequired: false;
} | {
    requestRequired: true;
    request: RequestPermissionFn;
};

/** Content-exclusion policy supplied to `session.permissions.configure`, with rules, last-updated data, and scope. */
declare interface PermissionsConfigureAdditionalContentExclusionPolicy {
    last_updated_at: unknown;
    rules: PermissionsConfigureAdditionalContentExclusionPolicyRule[];
    /** Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` enumeration. */
    scope: PermissionsConfigureAdditionalContentExclusionPolicyScope;
    [key: string]: unknown;
}

/** Single content-exclusion rule supplied to `session.permissions.configure`, with paths, match conditions, and source. */
declare interface PermissionsConfigureAdditionalContentExclusionPolicyRule {
    ifAnyMatch?: string[];
    ifNoneMatch?: string[];
    paths: string[];
    /** Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. */
    source: PermissionsConfigureAdditionalContentExclusionPolicyRuleSource;
    [key: string]: unknown;
}

/** Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. */
declare interface PermissionsConfigureAdditionalContentExclusionPolicyRuleSource {
    name: string;
    type: string;
}

/** Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` enumeration. */
declare type PermissionsConfigureAdditionalContentExclusionPolicyScope = "repo" | "all";

/** Patch of permission policy fields to apply (omit a field to leave it unchanged). */
declare interface PermissionsConfigureParams {
    /** If specified, replaces the host-supplied GitHub Content Exclusion policies on the session (combined with natively-discovered policies when evaluating tool/file access). Omit to leave the current policies unchanged. */
    additionalContentExclusionPolicies?: PermissionsConfigureAdditionalContentExclusionPolicy[];
    /** If specified, sets whether path/URL read permission requests are auto-approved. Omit to leave the current value unchanged. */
    approveAllReadPermissionRequests?: boolean;
    /** If specified, sets whether tool permission requests are auto-approved without prompting. Omit to leave the current value unchanged. */
    approveAllToolPermissionRequests?: boolean;
    /** If specified, replaces the session's path-permission policy. The runtime constructs the appropriate PathManager based on these inputs (rooted at the session's working directory). Omit to leave the current path policy unchanged. */
    paths?: PermissionPathsConfig;
    /** If specified, replaces the session's approved/denied permission rules. Omit to leave the current rules unchanged. */
    rules?: PermissionRulesSet;
    /** If specified, replaces the session's URL-permission policy. The runtime constructs a fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy unchanged. */
    urls?: PermissionUrlsConfig;
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsConfigureResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** The native session-owned permission service. */
declare type PermissionService = Omit<NativePermissionService, "request"> & {
    request(request: PermissionRequest_2): Promise<PermissionRequestResult>;
};

/** Indicates whether the operation succeeded. */
declare interface PermissionsFolderTrustAddTrustedResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** No parameters. */
declare interface PermissionsGetAllowAllRequest {
}

/** Tool approval to persist and apply */
declare type PermissionsLocationsAddToolApprovalDetails = PermissionsLocationsAddToolApprovalDetailsCommands | PermissionsLocationsAddToolApprovalDetailsRead | PermissionsLocationsAddToolApprovalDetailsWrite | PermissionsLocationsAddToolApprovalDetailsMcp | PermissionsLocationsAddToolApprovalDetailsMcpSampling | PermissionsLocationsAddToolApprovalDetailsMemory | PermissionsLocationsAddToolApprovalDetailsCustomTool | PermissionsLocationsAddToolApprovalDetailsExtensionManagement | PermissionsLocationsAddToolApprovalDetailsFactory | PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess;

/** Location-persisted tool approval details for specific command identifiers. */
declare interface PermissionsLocationsAddToolApprovalDetailsCommands {
    /** Command identifiers covered by this approval. */
    commandIdentifiers: string[];
    /** Approval scoped to specific command identifiers. */
    kind: "commands";
}

/** Location-persisted tool approval details for a custom tool, keyed by tool name. */
declare interface PermissionsLocationsAddToolApprovalDetailsCustomTool {
    /** Approval covering a custom tool. */
    kind: "custom-tool";
    /** Custom tool name. */
    toolName: string;
}

/** Location-persisted tool approval details for extension-management operations, optionally narrowed by operation. */
declare interface PermissionsLocationsAddToolApprovalDetailsExtensionManagement {
    /** Approval covering extension lifecycle operations such as enable, disable, or reload. */
    kind: "extension-management";
    /** Optional operation identifier; when omitted, the approval covers all extension management operations. */
    operation?: string;
}

/** Location-persisted tool approval details for an extension's permission-gated capability access, keyed by extension name. */
declare interface PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess {
    /** Extension name. */
    extensionName: string;
    /** Approval covering an extension's request to access a permission-gated capability. */
    kind: "extension-permission-access";
}

/** Location-persisted factory approval, optionally narrowed by approval key. */
declare interface PermissionsLocationsAddToolApprovalDetailsFactory {
    /** Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. */
    approvalKey?: string;
    /** Approval covering factory operations. */
    kind: "factory";
}

/** Location-persisted tool approval details for an MCP server tool, or all tools when `toolName` is null. */
declare interface PermissionsLocationsAddToolApprovalDetailsMcp {
    /** Approval covering an MCP tool. */
    kind: "mcp";
    /** MCP server name. */
    serverName: string;
    /** MCP tool name, or null to cover every tool on the server. */
    toolName: string | null;
}

/** Location-persisted tool approval details for MCP sampling requests from a server. */
declare interface PermissionsLocationsAddToolApprovalDetailsMcpSampling {
    /** Approval covering MCP sampling requests for a server. */
    kind: "mcp-sampling";
    /** MCP server name. */
    serverName: string;
}

/** Location-persisted tool approval details for writes to long-term memory. */
declare interface PermissionsLocationsAddToolApprovalDetailsMemory {
    /** Approval covering writes to long-term memory. */
    kind: "memory";
}

/** Location-persisted tool approval details for read-only filesystem operations. */
declare interface PermissionsLocationsAddToolApprovalDetailsRead {
    /** Approval covering read-only filesystem operations. */
    kind: "read";
}

/** Location-persisted tool approval details for filesystem write operations. */
declare interface PermissionsLocationsAddToolApprovalDetailsWrite {
    /** Approval covering filesystem write operations. */
    kind: "write";
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsLocationsAddToolApprovalResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** Scope and add/remove instructions for modifying session- or location-scoped permission rules. */
declare interface PermissionsModifyRulesParams {
    /** Rules to add to the scope. Applied before `remove`/`removeAll`. */
    add?: PermissionRule_2[];
    /** Specific rules to remove from the scope. Ignored when `removeAll` is true. */
    remove?: PermissionRule_2[];
    /** When true, removes every rule currently in the scope (after any `add` is applied). Useful for clearing the location scope wholesale. */
    removeAll?: boolean;
    /** Whether the change applies to ephemeral session-scoped rules (cleared at session end) or to location-scoped rules persisted via the location-permissions config file. */
    scope: PermissionsModifyRulesScope;
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsModifyRulesResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** Whether the change applies to ephemeral session-scoped rules (cleared at session end) or to location-scoped rules persisted via the location-permissions config file. */
declare type PermissionsModifyRulesScope = "session" | "location";

/** Indicates whether the operation succeeded. */
declare interface PermissionsNotifyPromptShownResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsPathsAddResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** No parameters; returns the session's allow-listed directories. */
declare interface PermissionsPathsListRequest {
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsPathsUpdatePrimaryResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** No parameters; returns currently-pending permission requests for the session. */
declare interface PermissionsPendingRequestsRequest {
}

/** Clears session-scoped tool permission approvals, and optionally the location-scoped ones. */
declare interface PermissionsResetSessionApprovalsRequest {
    /** Whether location-scoped approvals are cleared too. Defaults to `true`. */
    includeLocation?: boolean;
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsResetSessionApprovalsResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** Allow-all mode to apply for the session. */
declare interface PermissionsSetAllowAllRequest {
    /** Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. */
    enabled?: boolean;
    /** Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM auto-approval; `off` disables both. */
    mode?: PermissionsAllowAllMode;
    /** Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session resolves a default judge model: `gpt-5.5` for CAPI sessions and the session's active model for BYOK sessions. */
    model?: string;
    /** Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. */
    source?: PermissionsSetAllowAllSource;
}

/** Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. */
declare type PermissionsSetAllowAllSource = "cli_flag" | "slash_command" | "autopilot_confirmation" | "rpc";

/** Allow-all toggle for tool permission requests, with an optional telemetry source. */
declare interface PermissionsSetApproveAllRequest {
    /** Whether to auto-approve all tool permission requests */
    enabled: boolean;
    /** Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. */
    source?: PermissionsSetApproveAllSource;
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsSetApproveAllResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. */
declare type PermissionsSetApproveAllSource = "cli_flag" | "slash_command" | "autopilot_confirmation" | "rpc";

/** Toggles whether permission prompts should be bridged into session events for this client. */
declare interface PermissionsSetRequiredRequest {
    /** Whether the client wants `permission.requested` events bridged from the session-owned permission service. CLI clients that render prompt UI set this to `true` for as long as their listener is mounted; headless callers leave it unset (the default is `false`). */
    required: boolean;
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsSetRequiredResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** Indicates whether the operation succeeded. */
declare interface PermissionsUrlsSetUnrestrictedModeResult {
    /** Whether the operation succeeded */
    success: boolean;
}

/** If specified, replaces the session's URL-permission policy. The runtime constructs a fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy unchanged. */
declare interface PermissionUrlsConfig {
    /** Initial list of allowed URL/domain patterns. Patterns may include path components. Ignored when `unrestricted` is true. */
    initialAllowed?: string[];
    /** If true, the runtime allows access to all URLs without prompting. Initial allow-list is ignored when this is true. */
    unrestricted?: boolean;
}

/** Whether the URL-permission policy should run in unrestricted mode. */
declare interface PermissionUrlsSetUnrestrictedModeParams {
    /** Whether to allow access to all URLs without prompting. Toggles the runtime's URL-permission policy in place. */
    enabled: boolean;
}

/** Binary result returned by a tool for the model */
export declare interface PersistedBinaryImage {
    /** Base64-encoded binary data */
    data: string;
    /** Human-readable description of the binary data */
    description?: string;
    /** Optional metadata from the producing tool. */
    metadata?: Record<string, unknown>;
    /** MIME type of the binary data */
    mimeType: string;
    /** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
    type: PersistedBinaryImageType;
}

/** Binary result type discriminator. Use "image" for images and "resource" for other binary data. */
export declare type PersistedBinaryImageType = "image" | "resource";

/** A model-facing binary result as persisted: full inline data, a size-omitted marker, or a deduplicated asset reference */
export declare type PersistedBinaryResult = PersistedBinaryImage | OmittedBinaryResult | BinaryAssetReference;

declare interface PersistedMcpToolSnapshot {
    serverName: string;
    tools: readonly Readonly<LenientToolInfo>[];
}

declare type PersistedMcpToolSnapshots = Record<string, PersistedMcpToolSnapshot>;

/** Optional message to echo back to the caller. */
declare interface PingRequest {
    /** Optional message to echo back */
    message?: string;
}

/** Server liveness response, including the echoed message, current server timestamp, and protocol version. */
declare interface PingResult {
    /** Echoed message (or default greeting) */
    message: string;
    /** Server protocol version number */
    protocolVersion: number;
    /** ISO 8601 timestamp when the server handled the ping */
    timestamp: string;
}

/** Plan file operation details indicating what changed */
export declare interface PlanChangedData {
    /** The type of operation performed on the plan file */
    operation: PlanChangedOperation;
}

/** Session event "session.plan_changed". Plan file operation details indicating what changed */
declare interface PlanChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Plan file operation details indicating what changed */
    data: PlanChangedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.plan_changed". */
    type: "session.plan_changed";
}
export { PlanChangedEvent }
export { PlanChangedEvent as SessionPlanChangedEvent }

/** The type of operation performed on the plan file */
export declare type PlanChangedOperation = "create" | "update" | "delete";

/** Existence, contents, and resolved path of the session plan file. */
declare interface PlanReadResult {
    /** The content of the plan file, or null if it does not exist */
    content: string | null;
    /** Whether the plan file exists in the workspace */
    exists: boolean;
    /** Absolute file path of the plan file, or null if workspace is not enabled */
    path: string | null;
}

/** Todo rows read from the session SQL database. Empty when no session database is available. */
declare interface PlanReadSqlTodosResult {
    /** Rows from the session SQL todos table, ordered by creation time and id. */
    rows: PlanSqlTodosRow[];
}

/** Todo rows + dependency edges read from the session SQL database. */
declare interface PlanReadSqlTodosWithDependenciesResult {
    /** Edges from the session SQL todo_deps table. Empty when no database, no todo_deps table, or the SELECT failed. Read independently from `rows`, so a broken todo_deps table does not affect the rows result and vice versa. */
    dependencies: PlanSqlTodoDependency[];
    /** Rows from the session SQL todos table, ordered by creation time and id. Empty when no database, no todos table, or the SELECT failed. */
    rows: PlanSqlTodosRow[];
}

/** A single dependency edge read from the session SQL `todo_deps` table, indicating that one todo must complete before another. */
declare interface PlanSqlTodoDependency {
    /** ID of the todo it depends on. */
    dependsOn: string;
    /** ID of the todo that has the dependency. */
    todoId: string;
}

/** A single todo row read from the session SQL `todos` table. All fields are optional because the SQL schema is best-effort and the agent may not have populated every column. */
declare interface PlanSqlTodosRow {
    /** Todo description. */
    description?: string;
    /** Todo identifier. */
    id?: string;
    /** Todo status. */
    status?: string;
    /** Todo title. */
    title?: string;
}

/** Replacement contents to write to the session plan file. */
declare interface PlanUpdateRequest {
    /** The new content for the plan file */
    content: string;
}

/** Session plugin metadata, with name, marketplace, optional version, and enabled state. */
declare interface Plugin_2 {
    /** Whether the plugin is currently enabled */
    enabled: boolean;
    /** Marketplace the plugin came from */
    marketplace: string;
    /** Plugin name */
    name: string;
    /** Installed version */
    version?: string;
}

declare interface PluginActivationDecision {
    readonly plugin: InstalledPlugin;
    readonly active: boolean;
    readonly source?: PluginActivationSource;
    readonly reason: PluginActivationReason;
    readonly persisted: boolean;
}

declare type PluginActivationReason = "global-enabled" | "global-disabled-or-absent" | "repository-enabled" | "repository-disabled" | "direct-install" | "explicit-directory" | "ambient-disabled" | "plugin-dir-only" | "duplicate-cache-path";

declare type PluginActivationSource = "global" | "repository" | "direct" | "plugin-directory";

/** Result of installing a plugin. */
declare interface PluginInstallResult {
    /** Set when the install path is deprecated (e.g. direct repo / URL / local installs). Callers should surface this to end users. */
    deprecationWarning?: string;
    /** The newly installed plugin's metadata */
    plugin: InstalledPluginInfo;
    /** Optional post-install message provided by the plugin (e.g. setup instructions) */
    postInstallMessage?: string;
    /** Number of skills discovered and installed from the plugin */
    skillsInstalled: number;
}

/** Plugins installed for the session, with their enabled state and version metadata. */
declare interface PluginList {
    /** Installed plugins */
    plugins: Plugin_2[];
}

/** Plugins installed in user/global state. */
declare interface PluginListResult {
    /** Installed plugins */
    plugins: InstalledPluginInfo[];
}

/** Plugin names (or specs) to disable. */
declare interface PluginsDisableRequest {
    /** Plugin names or "plugin@marketplace" specs to disable. Unknown names are ignored. Non-marketplace direct installs cannot be disabled via this API; uninstall them instead. Plugin-owned MCP servers are stopped in active sessions immediately; other plugin contributions remain available until each session reloads plugins. */
    names: string[];
}

/** Plugin names (or specs) to enable. */
declare interface PluginsEnableRequest {
    /** Plugin names or "plugin@marketplace" specs to enable. Unknown names are ignored. Non-marketplace direct installs are always enabled and cannot be toggled via this API. */
    names: string[];
}

/** Plugin source and optional working directory for relative-path resolution. */
declare interface PluginsInstallRequest {
    /** Plugin install spec. Accepts the same forms as the CLI: "plugin@marketplace" (marketplace install), "owner/repo" or "owner/repo:subpath" (GitHub direct), an http/https/ssh URL, or a local path. Direct (non-marketplace) installs are deprecated and will produce a deprecationWarning in the result. */
    source: string;
    /** Working directory used to resolve relative local paths in `source`. Defaults to the server's current working directory. */
    workingDirectory?: string;
}

/** Marketplace source and optional working directory for relative-path resolution. */
declare interface PluginsMarketplacesAddRequest {
    /** Marketplace source. Accepts the same forms as the CLI: "owner/repo" or "owner/repo#ref" (GitHub), an http/https/ssh URL (optionally with #ref), a git scp-style URL (user@host:path), or a local path. The marketplace's own name (from its manifest) is used as the registration key. */
    source: string;
    /** Working directory used to resolve relative local paths in `source`. Defaults to the server's current working directory. */
    workingDirectory?: string;
}

/** Name of the marketplace whose plugin catalog to fetch. */
declare interface PluginsMarketplacesBrowseRequest {
    /** Marketplace name to browse */
    name: string;
}

/** Optional marketplace name; omit to refresh all. */
declare type PluginsMarketplacesRefreshRequest = {
    name?: string;
};

/** Name of the marketplace to remove and an optional force flag. */
declare interface PluginsMarketplacesRemoveRequest {
    /** When true, also uninstall every plugin sourced from this marketplace. When false (default), removal is a no-op if any plugin from this marketplace is installed and the dependent plugin names are returned in the result. */
    force?: boolean;
    /** Marketplace name to remove */
    name: string;
}

/** Optional flags controlling which side effects the reload performs. */
declare type PluginsReloadRequest = {
    deferRepoHooks?: boolean;
    reloadCustomAgents?: boolean;
    reloadExtensions?: boolean;
    reloadHooks?: boolean;
    reloadMcp?: boolean;
};

/** Name (or spec) of the plugin to uninstall. */
declare interface PluginsUninstallRequest {
    /** Stable source identity for a direct (non-marketplace) install. Disambiguates uninstall when multiple installed plugins share the same name. */
    directSourceId?: string | null;
    /** Plugin name or "plugin@marketplace" spec to uninstall. When ambiguous, prefer the fully-qualified spec. */
    name: string;
}

/** Name (or spec) of the plugin to update. */
declare interface PluginsUpdateRequest {
    /** Plugin name or "plugin@marketplace" spec to update. */
    name: string;
}

/** Per-plugin result from updating all plugins, with versions, skills installed, success flag, and optional error. */
declare interface PluginUpdateAllEntry {
    /** Error message (failure only) */
    error?: string;
    /** Marketplace the plugin came from. Empty string ("") for direct installs. */
    marketplace: string;
    /** Plugin name that was updated */
    name: string;
    /** Version after the update, when available */
    newVersion?: string;
    /** Previously installed version, when available */
    previousVersion?: string;
    /** Number of skills installed after the update (success only) */
    skillsInstalled?: number;
    /** Whether the update succeeded for this plugin */
    success: boolean;
}

/** Result of updating all installed plugins. */
declare interface PluginUpdateAllResult {
    /** Per-plugin update results in deterministic order. */
    results: PluginUpdateAllEntry[];
}

/** Result of updating a single plugin. */
declare interface PluginUpdateResult {
    /** Version after the update, when reported by the plugin manifest */
    newVersion?: string;
    /** Version that was previously installed, when available */
    previousVersion?: string;
    /** Number of skills discovered and installed after the update */
    skillsInstalled: number;
}

declare type PossiblePath = string;

declare type PossibleUrl = {
    readonly url: string;
};

declare type PostRequestContext = {
    /**
     * An identifier for the completion with tools call. This can be used for logging
     * and tracing purposes.
     */
    readonly callId: string | undefined;
    /**
     * The current turn.
     */
    readonly turn: number;
    /**
     * Information about the model being called.
     */
    readonly modelInfo: CompletionWithToolsModel;
    /**
     * The parsed response messages from the model.
     */
    readonly responseMessages: ChatCompletionMessageParam[];
    /**
     * The current {@link GetCompletionWithToolsOptions}
     */
    readonly getCompletionWithToolsOptions: GetCompletionWithToolsOptions | undefined;
};

/**
 * Result type for postRequest processors.
 * Currently empty as processors signal retries by throwing errors that are caught
 * by onRequestError processors. Reserved for future use.
 */
declare type PostRequestResult = Record<string, never>;

declare type PostToolExecutionContext = {
    /**
     * The current turn.
     */
    readonly turn: number;
    /**
     * What tool call was executed.
     */
    readonly toolCall: CopilotChatCompletionMessageToolCall;
    /**
     * The result of the tool call. Can be modified in place by the processor.
     */
    readonly toolResult: ToolResultExpanded;
    /**
     * Information about the model being called.
     */
    readonly modelInfo: CompletionWithToolsModel;
};

/** Call the Auto Intent proxy (`POST /models/session/intent`) for the given prompt. */
export declare function predictAutoIntent(args: PredictIntentArgs): Promise<AutoIntentResult>;

declare type PredictIntentArgs = AcquireArgs & {
    sessionToken: string;
    prompt: string;
    /** Clean prior user messages, oldest-to-newest. CAPI owns windowing and assembly. */
    previousUserMessages?: string[];
    availableModels: string[];
    hasImage: boolean;
    /** Multi-turn routing intent (`anchor` on the first turn, `drift_check` thereafter). */
    routingIntent?: string;
    /** Turns elapsed since the current anchor, for the server's drift telemetry. */
    turnsSinceAnchor?: number;
    /** The current skip-window size, for the server's drift telemetry. */
    currentSkipWindow?: number;
    /** The anchor capability vector (JSON), for the server's drift telemetry. */
    anchorCapVectorJson?: string;
};

declare type PreRequestContext = {
    /**
     * An identifier for the completion with tools call. This can be used for logging
     * and tracing purposes.
     */
    readonly callId: string | undefined;
    /**
     * The current turn.
     */
    readonly turn: number;
    /**
     * The current retry attempt.
     */
    readonly retry: number;
    /**
     * The messages that will be sent to the model for the request.
     * If modifying them, do so in place.
     */
    readonly messages: ChatCompletionMessageParam[];
    /**
     * The tool definitions that will be sent to the model for the request.
     * These should not be modified.
     */
    readonly toolDefinitions: ChatCompletionTool[];
    /**
     * Information about the model being called.
     */
    readonly modelInfo: CompletionWithToolsModel;
    /**
     * The current {@link GetCompletionWithToolsOptions}
     */
    readonly getCompletionWithToolsOptions: GetCompletionWithToolsOptions | undefined;
    /** Opaque partition key for native token-count caches. */
    readonly tokenCacheScope?: string;
    /**
     * A client that can be used to make additional LLM calls (e.g., for compaction)
     * without interfering with the active request transport.
     */
    readonly client: Client;
    /**
     * The rich tool objects with callbacks, needed for nested LLM calls.
     */
    readonly tools: Tool[];
    /**
     * Adds a message to persisted conversation history without necessarily
     * sending it on the current request. Used by response-budget state.
     */
    readonly addHiddenHistoryMessage?: (message: ChatCompletionMessageParam) => void;
    /** Adds a message to the current model request. */
    readonly addRequestMessage?: (message: ChatCompletionMessageParam) => void;
    /** Removes request messages matching the predicate. */
    readonly omitRequestMessages?: (predicate: (message: ChatCompletionMessageParam) => boolean) => void;
    /** Disables tools for the current request. */
    readonly disableTools?: () => void;
};

/**
 * Preserve override: a no-op that opts a section out of a group remove.
 * When a group is removed, any member section with an explicit leaf-level entry
 * (including "preserve") in the same config is excluded from the group removal.
 */
declare interface PreserveSectionOverride {
    action: "preserve";
}

declare type PreToolsExecutionContext = {
    /**
     * The current turn.
     */
    readonly turn: number;
    /**
     * What tool calls are being executed.
     */
    readonly toolCalls: CopilotChatCompletionMessageToolCall[];
    /**
     * Information about the model being called.
     */
    readonly modelInfo: CompletionWithToolsModel;
    /**
     * Results already produced by earlier pre-tools processors for this same
     * batch. Later processors can skip these calls to preserve hook ordering.
     */
    readonly preComputedResults?: ReadonlyMap<string, ToolResultExpanded>;
};

/**
 * Pre-tools execution procesors can either return nothing, or results for one or more
 * of the tools to be executed. These results will be given to the model in lieu of
 * performing the tool call and obtaining a result from the tool itself.
 */
declare type PreToolsExecutionResult = void | Map<string, ToolResultExpanded>;

declare interface PrimitiveArrayAnyOfSchema extends Record<string, unknown> {
    type: "array";
    title?: string;
    description?: string;
    minItems?: number;
    maxItems?: number;
    items: {
        anyOf: Array<{
            const: string;
            title: string;
        }>;
    };
    default?: string[];
}

declare interface PrimitiveArrayEnumSchema extends Record<string, unknown> {
    type: "array";
    title?: string;
    description?: string;
    minItems?: number;
    maxItems?: number;
    items: {
        type: "string";
        enum: string[];
    };
    default?: string[];
}

declare interface PrimitiveBooleanSchema extends Record<string, unknown> {
    type: "boolean";
    title?: string;
    description?: string;
    default?: boolean;
}

declare interface PrimitiveNumberSchema extends Record<string, unknown> {
    type: "number" | "integer";
    title?: string;
    description?: string;
    minimum?: number;
    maximum?: number;
    default?: number;
}

declare type PrimitiveSchemaDefinition = PrimitiveStringEnumSchema | PrimitiveStringOneOfSchema | PrimitiveArrayEnumSchema | PrimitiveArrayAnyOfSchema | PrimitiveBooleanSchema | PrimitiveStringSchema | PrimitiveNumberSchema;

declare interface PrimitiveStringEnumSchema extends Record<string, unknown> {
    type: "string";
    title?: string;
    description?: string;
    enum: string[];
    enumNames?: string[];
    default?: string;
}

declare interface PrimitiveStringOneOfSchema extends Record<string, unknown> {
    type: "string";
    title?: string;
    description?: string;
    oneOf: Array<{
        const: string;
        title: string;
    }>;
    default?: string;
}

declare interface PrimitiveStringSchema extends Record<string, unknown> {
    type: "string";
    title?: string;
    description?: string;
    minLength?: number;
    maxLength?: number;
    format?: "email" | "uri" | "date" | "date-time";
    default?: string;
}

export declare type ProgressLine = {
    message: string;
    timestamp: number;
};

declare type ProgressToken = string | number;

export declare type PromotableAgentTask = AgentTask & {
    executionMode: "sync";
    canPromoteToBackground: true;
};

export declare type PromotableShellTask = ShellTask & {
    executionMode: "sync";
    canPromoteToBackground: true;
};

export declare type PromotableTask = PromotableAgentTask | PromotableShellTask;

declare type PromptParts = {
    /** Include AI safety instructions (prohibited actions, security policies). Defaults to true. */
    includeAISafety: boolean;
    /** Include tool-specific instructions. Defaults to true. */
    includeToolInstructions: boolean;
    /** Include parallel tool calling hints (if model supports it). Defaults to false. */
    includeParallelToolCalling: boolean;
    /** Include custom agent delegation instructions. Defaults to false. */
    includeCustomAgentInstructions: boolean;
    /** Include environment context (cwd, git root, OS, available tools). Defaults to true. */
    includeEnvironmentContext: boolean;
    /** Include the dynamic-context-board consolidation instructions (used by rem-agent). Defaults to false. */
    includeConsolidationPrompt: boolean;
    /** Controls whether output instructions should target response text or the inbox. Defaults to response_text. */
    includeOutputChannelInstructions: OutputInstructionsMode;
    /** Include the "no tmp file output" instructions for subagents that may try to dodge size limits by writing to scratch files. Defaults to true. */
    includeNoTmpFileInstructions: boolean;
    /** Include a soft, non-prescriptive preference to return findings in the response text (used for user/custom subagents that may legitimately write files). Defaults to false/omitted. */
    includeSoftFileOutputInstructions?: boolean;
    /** Include the dynamic context board summary (metadata table) in the system prompt. */
    includeDynamicContextBoard?: boolean;
    /** Include session search context block (<session_search_context>). Defaults to false. */
    includeSessionSearchContext: boolean;
    /** Include session search context block (<session_search_context>) based on the cloud session store. Defaults to false. */
    includeCloudSessionSearchContext: boolean;
};

declare interface PromptTokensDetails {
    audio_tokens?: number;
    cached_tokens?: number;
    cache_creation_tokens?: number;
}

/** A slash command registered by an SDK client. */
declare interface ProtocolCommandDefinition {
    /** Command name (without leading /). */
    name: string;
    /** Human-readable description shown in command completion UI. */
    description?: string;
}

/** Valid transport values for BYOK configuration. */
declare const PROVIDER_TRANSPORTS: readonly ["http", "websockets"];

/** Valid provider type values for BYOK configuration. */
declare const PROVIDER_TYPES: readonly ["openai", "azure", "anthropic"];

/** BYOK providers and/or models to add to the session's registry at runtime. Both fields are optional; provide providers, models, or both. */
declare interface ProviderAddRequest {
    /** BYOK model definitions to register. Each must reference a provider that is already registered or included in this same call. Selection ids (`provider/id`) must be unique across the registry. */
    models?: ProviderModelConfig_2[];
    /** Named BYOK provider connections to register, additive to any providers already in the registry. Each name must be unique across the registry and must not contain '/'. */
    providers?: NamedProviderConfig_2[];
}

/** The selectable model entries synthesized for the models added by this call. */
declare interface ProviderAddResult {
    /** Synthesized selectable model entries for the newly added BYOK models, each under its provider-qualified selection id (`provider/id`). Empty when only providers were added. */
    models: unknown[];
}

/**
 * Configuration for a custom API provider (BYOK - Bring Your Own Key).
 * When set, bypasses Copilot API authentication and uses this provider instead.
 */
export declare interface ProviderConfig {
    /** Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. */
    type?: ProviderType;
    /** Wire API format (openai/azure only). Defaults to "completions". */
    wireApi?: WireApi;
    /** Transport for OpenAI Responses requests. Defaults to "http". */
    transport?: ProviderTransport;
    /** API endpoint URL */
    baseUrl: string;
    /** API key. Optional for local providers like Ollama. */
    apiKey?: string;
    /**
     * Bearer token for authentication. Sets the Authorization header directly.
     * Use this for services requiring bearer token auth instead of API key.
     * Takes precedence over apiKey when both are set.
     */
    bearerToken?: string;
    /** Azure-specific options */
    azure?: ProviderConfigAzure;
    /**
     * Well-known model ID used for configuration and capability lookup.
     * When set, agent behavior config (tools, reasoning, prompts) and token limits
     * are inferred from this model instead of the wire model.
     * Defaults to `COPILOT_MODEL` / `--model` when not explicitly set.
     */
    modelId?: string;
    /**
     * The model identifier sent to the provider API for inference (the "wire" model).
     * This is what your provider knows (e.g., a custom fine-tune name or Azure
     * deployment), as opposed to `modelId` which is the well-known base model
     * used for internal capability/config lookups.
     * Defaults to `COPILOT_MODEL` / `--model` when not explicitly set.
     */
    wireModel?: string;
    /** Maximum prompt/input tokens for the model. */
    maxPromptTokens?: number;
    /** Maximum context window tokens for the model. */
    maxContextWindowTokens?: number;
    /** Maximum output tokens for the model. */
    maxOutputTokens?: number;
    /** Structured model capability overrides for this provider. */
    modelCapabilities?: ModelCapabilitiesOverride;
    /** Custom HTTP headers to include in all outbound requests to the provider. */
    headers?: Record<string, string>;
    /**
     * Originating named-provider name, propagated internally when a registry
     * BYOK model's provider is flattened into this legacy shape. Forwarded to
     * the `providerToken.getToken` callback as `providerName` so the SDK consumer
     * can resolve which provider it is acquiring a token for. Not part of the
     * public single-provider surface (the whole-session `provider` is unnamed).
     */
    providerName?: string;
    /**
     * Wire flag set when an out-of-process SDK client supplies tokens for this
     * provider via the `providerToken.getToken` callback (e.g. wrapping
     * `@azure/identity`). When set, the runtime acquires a fresh token per
     * request and applies it as an `Authorization: Bearer <token>` header (the
     * bearer/OAuth scheme, not a provider-specific API-key header such as
     * Anthropic's `x-api-key`). When set alongside `apiKey`/`bearerToken`, the
     * callback takes precedence: the static credentials are not sent and the
     * per-request token is used instead.
     */
    hasBearerTokenProvider?: boolean;
}

/** Custom model-provider configuration (BYOK). */
declare interface ProviderConfig_2 {
    /** API key. Optional for local providers like Ollama. */
    apiKey?: string;
    /** Azure-specific provider options. */
    azure?: ProviderConfigAzure_2;
    /** API endpoint URL. */
    baseUrl: string;
    /** Bearer token for authentication. Sets the Authorization header directly. Takes precedence over apiKey when both are set. */
    bearerToken?: string;
    /** When true, the SDK client supplies bearer tokens on demand: the runtime calls the client-session `providerToken.getToken` callback before each request and applies the returned token as an `Authorization: Bearer <token>` header. This is the bearer/OAuth scheme used by Azure AD / managed-identity tokens and provider OAuth access tokens (including Anthropic's), not a provider-specific API-key header such as Anthropic's `x-api-key`. The token-acquiring function itself stays on the SDK side and is never serialized; only this flag crosses the wire. When set alongside `apiKey`/`bearerToken`, the callback takes precedence: the runtime applies the token returned by `providerToken.getToken` as the `Authorization: Bearer` header for each request and does not send the static credential. */
    hasBearerTokenProvider?: boolean;
    /** Custom HTTP headers to include in all outbound requests to the provider. */
    headers?: Record<string, string>;
    /** Maximum context window tokens for the model. */
    maxContextWindowTokens?: number;
    /** Maximum output tokens for the model. */
    maxOutputTokens?: number;
    /** Maximum prompt/input tokens for the model. */
    maxPromptTokens?: number;
    /** Well-known model ID used for capability lookup. When set, agent behavior config and token limits are inferred from this model. */
    modelId?: string;
    /** Provider transport. Defaults to "http". */
    transport?: ProviderConfigTransport;
    /** Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. */
    type?: ProviderConfigType;
    /** Wire API format (openai/azure only). Defaults to "completions". */
    wireApi?: ProviderConfigWireApi;
    /** The model identifier sent to the provider API for inference (the "wire" model), as opposed to modelId which is the well-known base. */
    wireModel?: string;
}

/**
 * Azure-specific provider options, shared by {@link ProviderConfig} and
 * {@link NamedProviderConfig}.
 */
declare interface ProviderConfigAzure {
    /** API version. When set, uses the versioned deployment route. When omitted, uses the GA versionless v1 route. */
    apiVersion?: string;
}

/** Azure-specific provider options. */
declare interface ProviderConfigAzure_2 {
    /** API version. When set, uses the versioned deployment route. When omitted, uses the GA versionless v1 route. */
    apiVersion?: string;
}

/** Provider transport. Defaults to "http". */
declare type ProviderConfigTransport = "http" | "websockets";

/** Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. */
declare type ProviderConfigType = "openai" | "azure" | "anthropic";

/** Wire API format (openai/azure only). Defaults to "completions". */
declare type ProviderConfigWireApi = "completions" | "responses";

/** A snapshot of the provider endpoint the session is currently configured to talk to. */
declare interface ProviderEndpoint {
    /** A credential the caller should use with this endpoint. Omitted only when the endpoint accepts unauthenticated requests. */
    apiKey?: string;
    /** Base URL to pass to the LLM client library. */
    baseUrl: string;
    /** HTTP headers the caller must include on every outbound request. */
    headers: Record<string, string>;
    /** Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. */
    sessionToken?: ProviderSessionToken;
    /** Transport to be used for provider requests. */
    transport?: ProviderEndpointTransport;
    /** Provider family. Matches the `type` field of a BYOK provider config. */
    type: ProviderEndpointType;
    /** Wire API to be used, when required for the provider type. */
    wireApi?: ProviderEndpointWireApi;
}

/** Transport to be used for provider requests. */
declare type ProviderEndpointTransport = "http" | "websockets";

/** Provider family. Matches the `type` field of a BYOK provider config. */
declare type ProviderEndpointType = "openai" | "azure" | "anthropic";

/** Wire API to be used, when required for the provider type. */
declare type ProviderEndpointWireApi = "completions" | "responses";

/** Optional model identifier to scope the endpoint snapshot to. */
declare type ProviderGetEndpointRequest = {
    modelId?: string;
};

/**
 * A BYOK model definition that references a {@link NamedProviderConfig} by name
 * and is added to the session's selectable model list.
 *
 * Each model has three identities:
 *  - `id`: the **provider-local** model id, unique within its provider. The
 *    session-wide **selection id** — what appears in the model list and is passed
 *    to `switchTo` — is the provider-qualified `provider/id` (e.g. `acme/claude`).
 *    Because selection ids are provider-qualified, they never collide with bare
 *    CAPI ids (a CAPI model keeps its bare id, served by the implicit default
 *    provider), so BYOK models never shadow CAPI models.
 *  - `modelId`: the well-known **behavior** base model used for capability/config
 *    lookup (tools, reasoning, prompts, advisor, image handling, limits).
 *    Defaults to `id`.
 *  - `wireModel`: the model name actually **sent to the provider API** for
 *    inference. Defaults to `id`.
 */
declare interface ProviderModelConfig {
    /**
     * Provider-local model id, unique within its provider. The session-wide
     * selection id is the provider-qualified `provider/id`.
     */
    id: string;
    /** Name of the {@link NamedProviderConfig} that serves this model. */
    provider: string;
    /** The model name sent to the provider API for inference. Defaults to `id`. */
    wireModel?: string;
    /** Well-known base model id used for behavior/capability/config lookup. Defaults to `id`. */
    modelId?: string;
    /** Display name for model pickers. Defaults to the provider-qualified selection id (`provider/id`). */
    name?: string;
    /** Maximum prompt/input tokens for the model. */
    maxPromptTokens?: number;
    /** Maximum context window tokens for the model. */
    maxContextWindowTokens?: number;
    /** Maximum output tokens for the model. */
    maxOutputTokens?: number;
    /** Optional capability overrides (vision, tool_calls, reasoning, etc.) for the synthesized model. */
    capabilities?: ModelCapabilitiesOverride;
}

/** A BYOK model definition referencing a named provider. */
declare interface ProviderModelConfig_2 {
    /** Optional capability overrides (vision, tool_calls, reasoning, etc.). */
    capabilities?: ModelCapabilitiesOverride_2;
    /** Provider-local model id, unique within its provider. The session-wide selection id (shown in the model list and passed to switchTo) is the provider-qualified `provider/id`. */
    id: string;
    /** Maximum context window tokens for the model. */
    maxContextWindowTokens?: number;
    /** Maximum output tokens for the model. */
    maxOutputTokens?: number;
    /** Maximum prompt/input tokens for the model. */
    maxPromptTokens?: number;
    /** Well-known base model id used for behavior/capability/config lookup. Defaults to `id`. */
    modelId?: string;
    /** Display name for model pickers. Defaults to the provider-qualified selection id (`provider/id`). */
    name?: string;
    /** Name of the NamedProviderConfig that serves this model. */
    provider: string;
    /** The model name sent to the provider API for inference. Defaults to `id`. */
    wireModel?: string;
}

/** Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. */
declare interface ProviderSessionToken {
    /** When the token expires, if known. Callers should refresh by calling `getEndpoint` again before this time, or reactively on any 401/403 response from `baseUrl`. */
    expiresAt?: string;
    /** HTTP header name the token must be sent under. */
    header: string;
    /** The model the token is bound to, when applicable. When set, the token is only valid for requests against this model. */
    model?: string;
    /** The short-lived token value. */
    token: string;
}

/** Asks the SDK client to acquire a bearer token for a BYOK provider whose config set `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; the runtime does no caching, so this is sent once per request. */
declare interface ProviderTokenAcquireRequest {
    /** Name of the BYOK provider needing a token. For the legacy whole-session `provider` this is the implicit provider name; for named providers it is `NamedProviderConfig.name`. */
    providerName: string;
}

/** A bearer token supplied by the SDK client for a BYOK provider. The runtime sets it as `Authorization: Bearer <token>` on the outbound request and does no caching; the SDK consumer owns token caching and refresh. */
declare interface ProviderTokenAcquireResult {
    /** The bearer token value (without the `Bearer ` prefix). */
    token: string;
}

declare type ProviderTransport = (typeof PROVIDER_TRANSPORTS)[number];

declare type ProviderType = (typeof PROVIDER_TYPES)[number];

/** Attachment union accepted by push input, covering files, directories, GitHub objects, blobs, snippets, and extension context. */
declare type PushAttachment = PushAttachmentFile | PushAttachmentDirectory | PushAttachmentSelection | PushAttachmentGitHubReference | PushAttachmentGitHubCommit | PushAttachmentGitHubRelease | PushAttachmentGitHubActionsJob | PushAttachmentGitHubRepository | PushAttachmentGitHubFileDiff | PushAttachmentGitHubTreeComparison | PushAttachmentGitHubUrl | PushAttachmentGitHubFile | PushAttachmentGitHubSnippet | PushAttachmentBlob | ExtensionContextPushInput;

/** Blob attachment with inline base64-encoded data */
declare interface PushAttachmentBlob {
    /** Base64-encoded content */
    data: string;
    /** User-facing display name for the attachment */
    displayName?: string;
    /** MIME type of the inline data */
    mimeType: string;
    /** Attachment type discriminator */
    type: "blob";
}

/** Directory attachment */
declare interface PushAttachmentDirectory {
    /** User-facing display name for the attachment */
    displayName: string;
    /** Absolute directory path */
    path: string;
    /** Attachment type discriminator */
    type: "directory";
}

/** File attachment */
declare interface PushAttachmentFile {
    /** User-facing display name for the attachment */
    displayName: string;
    /** Optional line range to scope the attachment to a specific section of the file */
    lineRange?: PushAttachmentFileLineRange;
    /** Absolute file path */
    path: string;
    /** Attachment type discriminator */
    type: "file";
}

/** Optional line range to scope the attachment to a specific section of the file */
declare interface PushAttachmentFileLineRange {
    /** End line number (1-based, inclusive) */
    end: number;
    /** Start line number (1-based) */
    start: number;
}

/** Pointer to a GitHub Actions job. */
declare interface PushAttachmentGitHubActionsJob {
    /** Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. */
    conclusion?: string;
    /** Job id within the workflow run */
    jobId: number;
    /** Display name of the job */
    jobName: string;
    /** Repository the workflow run belongs to */
    repo: PushGitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_actions_job";
    /** URL to the job on GitHub */
    url: string;
    /** Display name of the workflow the job ran in */
    workflowName: string;
}

/** Pointer to a GitHub commit. */
declare interface PushAttachmentGitHubCommit {
    /** First line of the commit message */
    message: string;
    /** Full commit SHA */
    oid: string;
    /** Repository the commit belongs to */
    repo: PushGitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_commit";
    /** URL to the commit on GitHub */
    url: string;
}

/** Pointer to a file in a GitHub repository at a specific ref. */
declare interface PushAttachmentGitHubFile {
    /** Repository-relative path to the file */
    path: string;
    /** Git ref the file is read at (branch, tag, or commit SHA) */
    ref: string;
    /** Repository the file lives in */
    repo: PushGitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_file";
    /** URL to the file on GitHub */
    url: string;
}

/** Pointer to a single-file diff. At least one of `head` and `base` must be present. */
declare interface PushAttachmentGitHubFileDiff {
    /** File location on the base side of the diff. Absent for additions. */
    base?: PushAttachmentGitHubFileDiffSide;
    /** File location on the head side of the diff. Absent for deletions. */
    head?: PushAttachmentGitHubFileDiffSide;
    /** Attachment type discriminator */
    type: "github_file_diff";
    /** URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL) */
    url: string;
}

/** One side of a file diff (head or base) */
declare interface PushAttachmentGitHubFileDiffSide {
    /** Repository-relative path to the file */
    path: string;
    /** Git ref (branch, tag, or commit SHA) the file is read at */
    ref: string;
    /** Repository the file lives in */
    repo: PushGitHubRepoRef;
}

/** GitHub issue, pull request, or discussion reference */
declare interface PushAttachmentGitHubReference {
    /** Issue, pull request, or discussion number */
    number: number;
    /** Type of GitHub reference */
    referenceType: PushAttachmentGitHubReferenceType;
    /** Current state of the referenced item (e.g., open, closed, merged) */
    state: string;
    /** Title of the referenced item */
    title: string;
    /** Attachment type discriminator */
    type: "github_reference";
    /** URL to the referenced item on GitHub */
    url: string;
}

/** Type of GitHub reference */
declare type PushAttachmentGitHubReferenceType = "issue" | "pr" | "discussion";

/** Pointer to a GitHub release. */
declare interface PushAttachmentGitHubRelease {
    /** Human-readable release name */
    name: string;
    /** Repository the release belongs to */
    repo: PushGitHubRepoRef;
    /** Git tag the release is anchored to */
    tagName: string;
    /** Attachment type discriminator */
    type: "github_release";
    /** URL to the release on GitHub */
    url: string;
}

/** Pointer to a GitHub repository. */
declare interface PushAttachmentGitHubRepository {
    /** Short description of the repository */
    description?: string;
    /** Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. */
    ref?: string;
    /** Repository pointer */
    repo: PushGitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_repository";
    /** URL to the repository on GitHub */
    url: string;
}

/** Pointer to a line range inside a file in a GitHub repository. */
declare interface PushAttachmentGitHubSnippet {
    /** Line range the snippet covers */
    lineRange: PushAttachmentFileLineRange;
    /** Repository-relative path to the file */
    path: string;
    /** Git ref the file is read at (branch, tag, or commit SHA) */
    ref: string;
    /** Repository the file lives in */
    repo: PushGitHubRepoRef;
    /** Attachment type discriminator */
    type: "github_snippet";
    /** URL to the snippet on GitHub (with line anchor) */
    url: string;
}

/** Pointer to a comparison between two git revisions. */
declare interface PushAttachmentGitHubTreeComparison {
    /** Base side of the comparison */
    base: PushAttachmentGitHubTreeComparisonSide;
    /** Head side of the comparison */
    head: PushAttachmentGitHubTreeComparisonSide;
    /** Attachment type discriminator */
    type: "github_tree_comparison";
    /** URL to the comparison on GitHub */
    url: string;
}

/** One side of a tree comparison (head or base) */
declare interface PushAttachmentGitHubTreeComparisonSide {
    /** Repository the revision belongs to */
    repo: PushGitHubRepoRef;
    /** Git revision (branch, tag, or commit SHA) */
    revision: string;
}

/** Generic GitHub URL reference. */
declare interface PushAttachmentGitHubUrl {
    /** Attachment type discriminator */
    type: "github_url";
    /** URL to the GitHub resource */
    url: string;
}

/** Code selection attachment from an editor */
declare interface PushAttachmentSelection {
    /** User-facing display name for the selection */
    displayName: string;
    /** Absolute path to the file containing the selection */
    filePath: string;
    /** Position range of the selection within the file */
    selection: PushAttachmentSelectionDetails;
    /** The selected text content */
    text: string;
    /** Attachment type discriminator */
    type: "selection";
}

/** Position range of the selection within the file */
declare interface PushAttachmentSelectionDetails {
    /** End position of the selection */
    end: PushAttachmentSelectionDetailsEnd;
    /** Start position of the selection */
    start: PushAttachmentSelectionDetailsStart;
}

/** End position of the selection */
declare interface PushAttachmentSelectionDetailsEnd {
    /** End character offset within the line (0-based) */
    character: number;
    /** End line number (0-based) */
    line: number;
}

/** Start position of the selection */
declare interface PushAttachmentSelectionDetailsStart {
    /** Start character offset within the line (0-based) */
    character: number;
    /** Start line number (0-based) */
    line: number;
}

/** Pointer to a GitHub repository. */
declare interface PushGitHubRepoRef {
    /** Numeric GitHub repository id */
    id?: number;
    /** Repository name (without owner) */
    name: string;
    /** Repository owner login (user or organization) */
    owner: string;
}

/** Inputs for starting a deferred-idle drain. */
declare interface QueueBeginDeferredIdleDrainRequest {
    /** Whether the host still has active background work. */
    activeBackgroundWork: boolean;
}

/** Whether a deferred-idle drain should run. */
declare interface QueueBeginDeferredIdleDrainResult {
    /** True when the host should run finishDeferredIdleDrain asynchronously. */
    shouldDrain: boolean;
}

/** Internal filter for consuming queued system notifications. */
declare interface QueueConsumeSystemNotificationsRequest {
    /** Opaque runtime-owned filter object. */
    filter: unknown;
}

/** Queued-command response indicating the host executed the command, with an optional flag to stop queue processing. */
declare interface QueuedCommandHandled {
    /** The host actually executed the queued command. */
    handled: true;
    /** When true, the runtime will not process subsequent queued commands until a new request comes in. */
    stopProcessingQueue?: boolean;
}

/**
 * Represents a queued slash command to be executed.
 */
declare interface QueuedCommandItem {
    kind: "command";
    /** The full command string including the slash, e.g., "/compact" or "/model gpt-4" */
    command: string;
}

/** Queued-command response indicating the host did not execute the command and the queue may continue. */
declare interface QueuedCommandNotHandled {
    /** The host did not execute the queued command. Unblocks the queue without claiming the command was processed (e.g. when the handler threw before completing). */
    handled: false;
}

/** Result of the queued command execution. */
declare type QueuedCommandResult = QueuedCommandHandled | QueuedCommandNotHandled;

/** Result type for queued slash commands. */
declare type QueuedCommandResult_2 = {
    handled: true;
    stopProcessingQueue?: boolean;
} | {
    handled: false;
};

/** Inputs for marking session.idle deferred in native state. */
declare interface QueueDeferSessionIdleRequest {
    /** Whether the deferred idle was caused by an aborted foreground turn. */
    aborted: boolean;
}

/**
 * A unified queue item that can represent either a user message or a slash command.
 * Used to support queueing slash commands alongside messages in FIFO order.
 */
declare type QueuedItem = QueuedMessageItem | QueuedMessagesItem | QueuedCommandItem | QueuedModelChangeItem | QueuedResumePendingItem;

/**
 * Represents a queued user message to be processed by the agentic loop.
 */
declare interface QueuedMessageItem {
    kind: "message";
    options: SendOptions;
}

/**
 * Represents a batch of user messages appended to history and processed in a
 * single agent turn. Used by `session.sendMessages` to append zero or more user
 * messages (in order) before one model submission. An empty `items` array runs
 * exactly one turn over the existing history without appending a new message.
 */
export declare interface QueuedMessagesItem {
    kind: "messages";
    /** The user messages to append, in order. May be empty. */
    items: SendOptions[];
    /**
     * Turn-level request headers for the model submission. These apply to empty
     * and non-empty batches, taking precedence over the primary message's own
     * `requestHeaders`.
     */
    turnRequestHeaders?: Record<string, string>;
}

/**
 * Represents a queued model change to be applied after the current turn.
 */
declare interface QueuedModelChangeItem {
    kind: "model_change";
    model: string;
    reasoningEffort?: ReasoningEffort;
    reasoningSummary?: ReasoningSummary_2;
    modelCapabilitiesOverrides?: ModelCapabilitiesOverride;
    contextTier?: ContextTier_3;
    verbosity?: Verbosity_2;
}

/**
 * Represents an internal wake-up to continue processing after a late permission
 * or external tool response was durably recorded.
 */
declare interface QueuedResumePendingItem {
    kind: "resume_pending";
}

/** Parameters for duplicating a queued item. */
declare interface QueueDuplicateAtRequest {
    id: string;
}

/** Result of duplicating a queued item. */
declare interface QueueDuplicateAtResult {
    /** Fresh stable opaque id assigned to the duplicate. */
    id: string;
}

/** Result of enqueueing the resume-pending wake item. */
declare interface QueueEnqueueResumePendingResult {
    /** True when a wake item was newly queued. */
    queued: boolean;
}

/** Inputs for completing a deferred-idle drain. */
declare interface QueueFinishDeferredIdleDrainRequest {
    /** Whether the host still has active background work. */
    activeBackgroundWork: boolean;
    /** Whether native queued work remains. */
    hasPending: boolean;
}

/** Action selected by the native deferred-idle drain. */
declare interface QueueFinishDeferredIdleDrainResult {
    /** Whether the deferred idle was caused by an aborted foreground turn. */
    aborted: boolean;
    /** One of none, processQueue, or emitSessionIdle. */
    action: string;
}

/** Whether the native queue has pending work. */
declare interface QueueHasPendingResult {
    /** True when queued or immediate native work is pending. */
    hasPending: boolean;
}

/** Parameters for inserting a queued message at a public visible position. */
declare interface QueueInsertAtRequest {
    message: QueueInsertMessage;
    /** Zero-based position in the public visible queue. Values outside the queue clamp to an end. */
    position: number;
}

/** Result of inserting a queued message. */
declare interface QueueInsertAtResult {
    /** Fresh stable opaque id assigned to the inserted item. */
    id: string;
}

/** Serializable message fields accepted by queue.insertAt. */
declare interface QueueInsertMessage {
    /** Optional explicit agent mode. When omitted, the session's current mode is assigned. */
    agentMode?: SendAgentMode;
    /** Optional attachments for the message. */
    attachments?: Attachment_2[];
    /** Whether the message is billable. */
    billable?: boolean;
    /** Accepted for internal SendOptions compatibility but ignored; delivery is derived from current session activity. */
    delivery?: string;
    /** Optional user-facing display text. */
    displayPrompt?: string;
    /** Accepted for SendOptions compatibility but ignored; inserted items always use queued delivery semantics. */
    mode?: SendMode;
    /** Accepted for SendOptions compatibility but ignored; the requested public position controls placement. */
    prepend?: boolean;
    /** The user message text. */
    prompt: string;
    /** Per-turn request headers. */
    requestHeaders?: Record<string, string>;
    /** Required tool name for the turn, when any. */
    requiredTool?: string;
    /** Optional provenance source. `system` is rejected: it would hide the inserted row from `pendingItems` and make it unaddressable while still executing, so inserted items must stay visible. */
    source?: string;
    /** Accepted for SendOptions compatibility but ignored; insertion scheduling is controlled by the queue drain state. */
    wait?: boolean;
}

/** Parameters for moving a queued item by stable id. */
declare interface QueueMoveItemRequest {
    /** Stable opaque queued-item id. */
    id: string;
    /** Zero-based target position in the public visible queue. Values outside the queue clamp to an end. */
    toPosition: number;
}

/** Result of moving a queued item. */
declare interface QueueMoveItemResult {
    /** True when the item changed position; false when it was already at the requested position. */
    changed: boolean;
}

/** User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. */
declare interface QueuePendingItems {
    /** Agent mode stored on this queued entry, as stamped when it was enqueued. Items without an explicit mode report interactive. This is not necessarily the mode that will constrain the turn: a plan or autopilot session applies its own write gate, continuation loop and permission posture to every drained item regardless of the mode stored here. */
    agentMode: SendAgentMode;
    /** Human-readable text to display for this queue entry in the UI */
    displayText: string;
    /** Stable opaque id for the canonical queued item. Batch rows share one id. */
    id: string;
    /** Whether this item is a queued user message or a queued slash command / model change */
    kind: QueuePendingItemsKind;
}

/** Whether this item is a queued user message or a queued slash command / model change */
declare type QueuePendingItemsKind = "message" | "command";

/** Snapshot of the session's pending queued items and immediate-steering messages. */
declare interface QueuePendingItemsResult {
    /** Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. */
    items: QueuePendingItems[];
    /** Display text for messages currently in the immediate steering queue (interjections sent during a running turn). */
    steeringMessages: string[];
}

/** Parameters for removing a queued item by stable id. */
declare interface QueueRemoveAtRequest {
    id: string;
}

/** Result of removing a queued item. */
declare interface QueueRemoveAtResult {
    /** True when the addressed item was removed. */
    removed: boolean;
}

/** Indicates whether a user-facing pending item was removed. */
declare interface QueueRemoveMostRecentResult {
    /** True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. */
    removed: boolean;
}

/** Parameters for steering a queued message into a live turn. */
declare interface QueueSendNowRequest {
    id: string;
}

/** Result of trying to steer a queued message into a live turn. */
declare interface QueueSendNowResult {
    /** True when the item was accepted into the steering lane; false when no main turn was live. */
    steered: boolean;
}

/** Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. */
declare interface QueueSetDrainPausedRequest {
    paused: boolean;
}

/** Internal snapshot of native queue state for local session orchestration. */
declare interface QueueSnapshotResult {
    /** Insertion orders for queued items, aligned with `items`. */
    itemOrders?: number[];
    /** User-facing pending items in FIFO order. */
    items: QueuePendingItems[];
    /** Insertion orders for immediate steering messages, aligned with `steeringMessages`. */
    steeringMessageOrders?: number[];
    /** Immediate steering messages waiting for an active turn. */
    steeringMessages: string[];
}

/** Parameters for editing a single queued message. */
declare interface QueueUpdateTextRequest {
    displayPrompt?: string;
    id: string;
    prompt: string;
}

/** Result of editing a queued message. */
declare interface QueueUpdateTextResult {
    /** True when the stored text changed. */
    updated: boolean;
}

/** Logger that queues log messages until a real logger is set */
export declare class QueuingProxyLogger implements Logger, Disposable_2 {
    private initialQueue;
    private initialQueueResolvers;
    private logWriter;
    /** A writer's path is fixed for its lifetime; out of process reading it is a round trip. */
    private cachedOutputPath;
    private writePromise;
    /** Sets the log writer and flushes any queued log messages.
     * Should only be called once per process (except in tests).
     */
    setLogWriter(logWriter: LogWriter): void;
    /** Waits for all queued log messages to be written.
     *
     * If no {@link LogWriter} has been set yet, there is nothing that can drain
     * the queue, so `flush()` resolves immediately rather than blocking on the
     * initial (writer-gated) promise. Without this guard a caller that flushes
     * during shutdown before ever wiring a writer — e.g. a subcommand that owns
     * its own {@link ShutdownService} — would hang forever (github/copilot-cli#4011).
     *
     * A writer that can no longer reach its sink neither fails nor stalls this
     * call: see {@link FLUSH_TIMEOUT_MS}.
     */
    flush(): Promise<void>;
    /** Alias for Disposable interface */
    dispose(): Promise<void>;
    outputPath(): string | undefined;
    private logToLevel;
    private writeTo;
    info(message: string): void;
    debug(message: string): void;
    warning(message: string): void;
    error(message: string | Error): void;
    log(message: string): void;
    isDebug(): boolean;
    shouldLog(_level: RunnerLogLevel): boolean;
    notice(message: string | Error): void;
    startGroup(name: string, _?: RunnerLogLevel): void;
    endGroup(_?: RunnerLogLevel): void;
}

declare type QuotaSnapshot = {
    /**
     * Whether or not it's an unlimited entitlement.
     */
    isUnlimitedEntitlement: boolean;
    /**
     * The number of requests included in the entitlement, or "-1" for unlimited
     * entitlement, so that the user/client can understand how much they get each
     * month/period; the value is an integer
     */
    entitlementRequests: number;
    /**
     * The count of requests used so far in this month/period, so that the
     * user/client can understand how much of their entitlement they have used;
     * the value is an integer
     */
    usedRequests: number;
    /**
     * Indicates whether usage is allowed once quota is exhausted, so that the
     * user/client can understand if they can continue usage at a pay-per-request
     * rate when entitlement is exhausted; the value is boolean
     */
    usageAllowedWithExhaustedQuota: boolean;
    /**
     * The count of additional usage requests made so far in this month/period, so that
     * the user/client can understand how much they have spent in pay-per-request
     * charges so far this month/period; the value is a decimal
     */
    overage: number;
    /**
     * Indicates whether additional usage is allowed once quota is exhausted, so that the
     * user/client can understand if they can continue usage at a pay-per-request
     * rate when entitlement is exhausted; the value is boolean
     */
    overageAllowedWithExhaustedQuota: boolean;
    /**
     * The percentage of the entitlement remaining at the snapshot timestamp, so
     * that the user/client can understand how much they have remaining and their
     * rate of usage; the value is a decimal
     */
    remainingPercentage: number;
    /**
     * The date when the quota resets, so that the user/client can know when they
     * next receive their entitlement; the value is an RFC3339 formatted UTC date;
     * if the entitlement is unlimited, this value is not included in the snapshot
     */
    resetDate?: Date;
    /**
     * True when {@link resetDate} was synthesized as a fallback rather than
     * taken from an authoritative wire value (the CAPI header path falls back to
     * `now + 1 month` when `rst` is absent). Consumers that surface a reset
     * countdown should suppress it when this is `true` so an estimated reset is
     * never presented as authoritative. The API/user-endpoint path leaves
     * `resetDate` undefined when absent, so it never sets this flag.
     */
    resetDateEstimated?: boolean;
    /**
     * Whether the user currently has quota available for use.
     * When `false` (and the entitlement is not unlimited), the user is blocked
     * from making further requests until quota resets.
     */
    hasQuota?: boolean;
    /**
     * Whether this quota snapshot uses token-based billing (TBB).
     * When `true`, the snapshot represents an AI-credits based allocation
     * rather than a fixed premium-request count.
     */
    tokenBasedBilling?: boolean;
    overageEntitlement?: number;
};

declare type QuotaSnapshotsByType = Record<string, QuotaSnapshot>;

declare type ReadInboxEntryOptions = {
    entryId?: string;
    markAsRead?: boolean;
};

/**
 * A permission request for reading file or directory contents.
 */
declare type ReadPermissionRequest = {
    readonly kind: "read";
    /** The intention of the edit operation, e.g. "Read file" or "List directory" */
    readonly intention: string;
    /** The path of the file or directory being read */
    readonly path: string;
    /**
     * True when the model has requested to run this search outside the sandbox
     * (it set `requestSandboxBypass: true` and the host opted in via
     * `sandbox.allowBypass`). This is a request, not a grant: the search runs
     * unsandboxed only if the user approves this permission request. Hosts
     * should highlight the elevated risk in the approval UI.
     */
    readonly requestSandboxBypass?: boolean;
    /**
     * Model-provided justification for the sandbox-bypass request
     * ({@link requestSandboxBypass}). Only meaningful when
     * `requestSandboxBypass` is true.
     */
    readonly requestSandboxBypassReason?: string;
    /** Managed policy requires an explicit human response for this read. */
    readonly managedApprovalRequired?: boolean;
    readonly autoApproval?: AutoApproval;
};

/**
 * Reasoning effort level for models that support it.
 * "none" is a client-side signal to disable reasoning and is accepted even
 * for "auto" and models that do not expose provider effort levels. Other
 * well-known values include "low", "medium", "high", "xhigh", and "max", but
 * custom providers may accept additional values.
 */
declare type ReasoningEffort = string;

/** Re-export ReasoningEffortOption as ReasoningEffortLevel for backwards compatibility */
declare type ReasoningEffortLevel = ReasoningEffortOption;

declare type ReasoningEffortOption = ReasoningEffort;

declare type ReasoningMessageParam = {
    /**
     * An ID or encrypted value that allows the model to restore
     */
    reasoning_opaque?: string;
    /**
     * Human-readable text describing the model's thinking process.
     */
    reasoning_text?: string;
    /**
     * An encrypted representation of the model's internal state
     */
    encrypted_content?: string | undefined | null;
};

declare type ReasoningMessageParam_2 = {
    reasoning_opaque?: string;
    reasoning_text?: string;
    encrypted_content?: string | undefined | null;
};

/**
 * Resolved state of the three-arm reasoning-summaries experiment
 * ({@link DefinedExpFlags.REASONING_SUMMARIES_OFF_BY_DEFAULT}). Two booleans derived from a
 * single flag value so an invalid "hint without a hidden default" combination cannot be expressed.
 */
declare interface ReasoningSummariesArmState {
    /** Whether reasoning summaries start hidden (treatment arms B and C). */
    readonly offByDefault: boolean;
    /** Whether the "ctrl+t show reasoning" footer hint is surfaced while summaries are hidden (arm B only). */
    readonly hintEnabled: boolean;
}

/** Reasoning summary mode used for model calls, if applicable (e.g. "none", "concise", "detailed") */
export declare type ReasoningSummary = "none" | "concise" | "detailed";

/**
 * Reasoning summary mode for models that support configurable reasoning summaries.
 * Use "none" to suppress summary output regardless of whether reasoning is enabled.
 */
declare type ReasoningSummary_2 = "none" | "concise" | "detailed";

/** Reasoning summary mode to request for supported model clients */
declare type ReasoningSummary_3 = "none" | "concise" | "detailed";

/** A reference linking a session to an external entity. */
declare interface RefRow {
    session_id: string;
    ref_type: "commit" | "pr" | "issue";
    ref_value: string;
    turn_index?: number;
    created_at?: string;
}

/** Event type to register consumer interest for, used by runtime gating logic. */
declare interface RegisterEventInterestParams {
    /** The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. */
    eventType: string;
}

/** Opaque handle representing an event-type interest registration. */
declare interface RegisterEventInterestResult {
    /** Opaque handle for this registration. Pass to releaseInterest to release. Each call to registerInterest produces a fresh handle, even when the same eventType is registered multiple times. */
    handle: string;
}

/** Params to attach an extension loader's tools to a session. */
declare interface RegisterExtensionToolsParams {
    /** In-process ExtensionLoader handle (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, extension discovery/launch moves entirely into the runtime — the CLI passes pure config (search paths, disabled ids) via SessionOptions instead. */
    loader: unknown;
    /** Optional registration options. */
    options?: SessionsRegisterExtensionToolsOnSessionOptions;
    /** Session to register extension tools on. */
    sessionId: string;
}

/** Handle for releasing the extension tool registration. */
declare interface RegisterExtensionToolsResult {
    /** In-process unsubscribe function (CLI-only optimization). Marked internal: replaced by an explicit `extensions.unregister` RPC in the SDK migration. */
    unsubscribe: unknown;
}

declare interface RelatedTaskMetadata {
    taskId: string;
}

/** Opaque handle previously returned by `registerInterest` to release. */
declare interface ReleaseEventInterestParams {
    /** Handle returned by a previous `registerInterest` call. Idempotent: releasing an unknown or already-released handle is a no-op (returns success). When the last outstanding handle for an event type is released, the runtime reverts to its 'no consumer' code path for that event type. */
    handle: string;
}

/** Configuration accepted by {@link Session.reloadMcpServers}. */
declare type ReloadMcpServersConfig = {
    mcpServers: Record<string, MCPServerConfig>;
    disabledServers?: string[];
    enabledServers?: string[];
    mcp3pEnabled?: boolean;
    configFilter?: McpConfigFilter;
    statusCallback?: ServerStatusCallback;
    githubMcpToolOptions?: Required<GitHubMcpConfigOptions>;
    githubMcpUserOverride?: boolean;
    /** Optional secret store for resolving ${secret:...} placeholders (CLI only). */
    secretStore?: McpSecretStoreInterface;
    /** Optional already-resolved active GitHub token for stdio MCP arg GITHUB_TOKEN expansion. */
    activeGitHubToken?: string;
    /** Whether the new host should use the persisted tool snapshot cache. Defaults to true. */
    useCachedToolSnapshots?: boolean;
};

/** Configuration for the runtime-managed remote-control singleton. */
declare interface RemoteControlConfig {
    /** Reattach to an existing MC session without creating a new one. */
    existingMcSession?: RemoteControlConfigExistingMcSession;
    /** Whether the user explicitly requested remote (vs. implicit session-sync). Controls warning surfacing for missing-repo cases. */
    explicit: boolean;
    /** Whether remote export should be enabled. */
    remote: boolean;
    /** When true, suppresses timeline messages on successful setup. */
    silent: boolean;
    /** Whether the MC session may steer the local session (write mode). */
    steerable: boolean;
    /** Existing Mission Control task ID to attach the exported session to. */
    taskId?: string;
}

/** Reattach to an existing MC session without creating a new one. */
declare interface RemoteControlConfigExistingMcSession {
    /** Existing MC session ID to reattach to. */
    mcSessionId: string;
    /** Existing MC task ID for the reattached session. */
    mcTaskId: string;
}

/** State of the runtime-managed remote-control singleton. */
declare type RemoteControlStatus = RemoteControlStatusOff | RemoteControlStatusConnecting | RemoteControlStatusActive | RemoteControlStatusError;

/** Remote control is connected to a local session. */
declare interface RemoteControlStatusActive {
    /** Session id remote control is pointed at. */
    attachedSessionId: string;
    /** True while a read-only/session-sync export is deferred, awaiting the first `user.message` before its MC session exists. Marked internal: this field is excluded from the public SDK surface and is populated only on the CLI in-process path. */
    awaitingFirstMessage?: boolean;
    /** MC frontend URL for this session, when known. */
    frontendUrl?: string;
    /** Whether the MC session may steer this session. */
    isSteerable: boolean;
    /** In-process prompt-manager handle (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, the same bidirectional prompt-routing handshake is expressed via dedicated remote-control RPCs (register/resolve) rather than a shared in-process object. */
    promptManager?: unknown;
    /** Remote control state tag: active. */
    state: "active";
}

/** Remote control is in the middle of initial setup. */
declare interface RemoteControlStatusConnecting {
    /** Session id the connection is attaching to. */
    attachedSessionId: string;
    /** Remote control state tag: connecting. */
    state: "connecting";
}

/** The last setup attempt failed. The singleton is otherwise off. */
declare interface RemoteControlStatusError {
    /** Session id the failing setup attempt targeted, when known. */
    attachedSessionId?: string;
    /** Human-readable error message from the last setup attempt. */
    error: string;
    /** Remote control state tag: setup failed. */
    state: "error";
}

/** Remote control is not connected. */
declare interface RemoteControlStatusOff {
    /** Remote control state tag: not connected. */
    state: "off";
}

/** Wrapper for the singleton's current status. */
declare interface RemoteControlStatusResult {
    /** State of the runtime-managed remote-control singleton. */
    status: RemoteControlStatus;
}

/** Outcome of a stopRemoteControl call. */
declare interface RemoteControlStopResult {
    /** State of the runtime-managed remote-control singleton. */
    status: RemoteControlStatus;
    /** Whether the singleton was actually torn down by this call. */
    stopped: boolean;
}

/** Outcome of a transferRemoteControl call. */
declare interface RemoteControlTransferResult {
    /** State of the runtime-managed remote-control singleton. */
    status: RemoteControlStatus;
    /** Whether the rebinding actually happened. */
    transferred: boolean;
}

/** Optional remote session mode ("off", "export", or "on"); defaults to enabling both export and remote steering. */
declare interface RemoteEnableRequest {
    /** Per-session remote mode. "off" disables remote, "export" exports session events to GitHub without enabling remote steering, "on" enables both export and remote steering. */
    mode?: RemoteSessionMode;
}

/** GitHub URL for the session and a flag indicating whether remote steering is enabled. */
declare interface RemoteEnableResult {
    /** Whether remote steering is enabled */
    remoteSteerable: boolean;
    /** GitHub frontend URL for this session */
    url?: string;
}

/** New remote-steerability state to persist as a `session.remote_steerable_changed` event. */
declare interface RemoteNotifySteerableChangedRequest {
    /** Whether the session now supports remote steering via GitHub. The runtime persists this as a `session.remote_steerable_changed` event so resume/replay sees the up-to-date capability. */
    remoteSteerable: boolean;
}

/** Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. */
declare interface RemoteNotifySteerableChangedResult {
}

/**
 * Optional host-side fallback for routing Mission Control steer responses
 * (ask_user / exit_plan_mode / permission / elicitation) when no
 * `PromptManager` entry was registered locally.
 */
declare interface RemotePromptFallback {
    findUserInputRequestIdByPromptId(promptId: string): (string & {}) | "already-resolved" | undefined;
    findElicitationRequestIdByPromptId(promptId: string): (string & {}) | "already-resolved" | undefined;
    findExitPlanModeRequestIdByPromptId(promptId: string): (string & {}) | "already-resolved" | undefined;
    findPermissionByPromptId(promptId: string): {
        requestId: string;
        promptRequest: PermissionPromptRequest_2;
    } | "already-resolved" | undefined;
    respondToUserInput(requestId: string, response: {
        answer: string;
        wasFreeform: boolean;
        dismissed?: boolean;
    }): boolean;
    tryRespondToElicitation(requestId: string, response: ElicitResult): boolean;
    respondToExitPlanMode(requestId: string, response: ExitPlanModeResponse): boolean;
    respondToPermission(requestId: string, response: PermissionPromptResponse, decisionContext?: PermissionDecisionContext): boolean;
}

export declare class RemoteSession extends Session<RemoteSessionMetadata> {
    readonly isRemote: true;
    get repository(): {
        name: string;
        owner: string;
        branch: string;
    };
    get remoteSessionIds(): string[];
    get pullRequestNumber(): number | undefined;
    get resourceId(): string | undefined;
    get taskType(): RemoteTaskType | undefined;
    get staleAt(): Date | undefined;
    get state(): string | undefined;
    constructor(coreServices: CoreServices, options: SessionOptions & {
        repository: {
            name: string;
            owner: string;
            branch: string;
        };
        remoteSessionIds: string[];
        pullRequestNumber?: number;
        resourceId?: string;
        taskType?: RemoteTaskType;
        staleAt?: Date;
        state?: string;
    });
    setAgentPrompt(_id: string, _prompt: string): Promise<void>;
    /**
     * Schema-shaped wrapper for remote `send` invoked by the JSON-RPC dispatcher.
     * `wait: true` waits for Mission Control to acknowledge the steer request.
     * It does not wait for the remote agent loop to finish processing.
     */
    sendForSchema(params: SendParams): {
        messageId: string;
    } | Promise<{
        messageId: string;
    }>;
    /**
     * Schema-shaped wrapper for `abort` invoked by the JSON-RPC dispatcher.
     * Adapts the `Promise<void>` shape of {@link abort} into the
     * `{success, error?}` shape declared by `sessionApiSchema.abort`,
     * catching errors and returning them in-band rather than throwing.
     */
    abortForSchema(params: {
        reason?: AbortReason;
    }): Promise<{
        success: boolean;
        error?: string;
    }>;
    send(options: SendOptions): Promise<void>;
    /**
     * Multi-message sibling of {@link send} for remote sessions. Not supported
     * yet: remote turns are driven by Mission Control, which has no batch-steer
     * primitive and no way to run a turn over the existing history with no new
     * content, so this cannot honor the `session.sendMessages` contract (append
     * all messages in order, then run exactly one turn — including the empty
     * batch, which must still run one turn). Rather than silently approximating
     * it (per-message steers, and a no-op for an empty batch — which would look
     * like success while doing something materially different), we throw so
     * callers don't assume batch/single-turn semantics that don't hold here.
     */
    sendMessages(_items: SendOptions[]): Promise<void>;
    /**
     * Schema-shaped wrapper for {@link sendMessages} invoked by the JSON-RPC
     * dispatcher. RemoteSession does not support batch/single-turn semantics
     * (see {@link sendMessages}), so this throws synchronously instead of
     * inheriting the base wrapper. The base wrapper's fire-and-forget path would
     * otherwise swallow the rejection into a background `.catch()` and return a
     * misleading `{ messageIds }` success over the wire, contradicting the
     * `session.sendMessages` contract that remote-backed sessions return an error.
     */
    sendMessagesForSchema(_params: SendMessagesParams): {
        messageIds: string[];
    } | Promise<{
        messageIds: string[];
    }>;
    abort(_params?: {
        reason?: AbortReason;
    }): Promise<void>;
    sendSystemNotification(message: string, kind: SystemNotification | undefined, options?: {
        passive?: PassivePolicy;
    }): void;
    interruptMainTurn(_options?: {
        flushQueued?: boolean;
    }): Promise<{
        interrupted: boolean;
    }>;
    cancelAllBackgroundAgents(): number;
    shutdown(params?: ShutdownParams): Promise<void>;
    suspend(): Promise<void>;
    ephemeralQuery(): Promise<string>;
    compactHistory(_customInstructions?: string, _trigger?: ClientCompactionTrigger, _tokenLimit?: number): Promise<CompactionResult>;
    getMetadata(): RemoteSessionMetadata;
}

/** Remote session connection result. */
declare interface RemoteSessionConnectionResult {
    /** Metadata for a connected remote session. */
    metadata: ConnectedRemoteSessionMetadata;
    /** SDK session ID for the connected remote session. */
    sessionId: string;
}

export declare interface RemoteSessionMetadata extends SessionMetadata {
    readonly repository: {
        owner: string;
        name: string;
        branch: string;
    };
    readonly remoteSessionIds: string[];
    readonly pullRequestNumber?: number;
    readonly resourceId?: string;
    readonly isRemote: true;
    readonly taskType?: RemoteTaskType;
    readonly staleAt?: Date;
    readonly state?: string;
}

/** GitHub repository the remote session belongs to. */
declare interface RemoteSessionMetadataRepository {
    /** Branch associated with the remote session. */
    branch: string;
    /** Repository name. */
    name: string;
    /** Repository owner. */
    owner: string;
}

/** Whether the remote task originated from CCA or CLI `--remote`. */
declare type RemoteSessionMetadataTaskType = "cca" | "cli";

/** Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). */
declare interface RemoteSessionMetadataValue {
    /** Most recent working directory context. */
    context?: SessionContext_2;
    /** Always true for remote sessions. */
    isRemote: true;
    /** Last-modified time as an ISO 8601 timestamp. */
    modifiedTime: string;
    /** Optional human-friendly name set via /rename. */
    name?: string;
    /** Pull request number associated with the session. */
    pullRequestNumber?: number;
    /** Backing remote session IDs (most recent first). */
    remoteSessionIds: string[];
    /** GitHub repository the remote session belongs to. */
    repository: RemoteSessionMetadataRepository;
    /** Original remote resource identifier (task ID or PR node ID). */
    resourceId?: string;
    /** Stable session identifier. */
    sessionId: string;
    /** Deadline (ISO 8601) at which a CLI remote session becomes stale without further heartbeats. */
    staleAt?: string;
    /** Session creation time as an ISO 8601 timestamp. */
    startTime: string;
    /** Server-side task state returned by GitHub. */
    state?: string;
    /** Short summary of the session, when one has been derived. */
    summary?: string;
    /** Whether the remote task originated from CCA or CLI `--remote`. */
    taskType?: RemoteSessionMetadataTaskType;
}

/** Per-session remote mode. "off" disables remote, "export" exports session events to GitHub without enabling remote steering, "on" enables both export and remote steering. */
declare type RemoteSessionMode = "off" | "export" | "on";

/** Repository context for the remote session. */
declare interface RemoteSessionRepository {
    /** Optional branch associated with the remote session. */
    branch?: string;
    /** Repository name. */
    name: string;
    /** Repository owner or organization login. */
    owner: string;
}

/**
 * A remote skill loaded from sweagentd (org/enterprise skills).
 * Content is fetched lazily when the skill is invoked.
 */
declare interface RemoteSkill extends SkillBase {
    /** Remote skills always have source "remote". */
    source: "remote";
    /** Relative path to SKILL.md within the source repository (e.g., ".github/skills/foo/SKILL.md"). */
    relativePath: string;
    /** Relative path to the skill's directory within the source repository. */
    relativeDir: string;
    /** Lazy content loader - must be called to fetch skill content on-demand. */
    fetchContent: () => Promise<string>;
}

/** Notifies that the session's remote steering capability has changed */
export declare interface RemoteSteerableChangedData {
    /** Whether this session now supports remote steering via GitHub */
    remoteSteerable: boolean;
}

/** Session event "session.remote_steerable_changed". Notifies that the session's remote steering capability has changed */
declare interface RemoteSteerableChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Notifies that the session's remote steering capability has changed */
    data: RemoteSteerableChangedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.remote_steerable_changed". */
    type: "session.remote_steerable_changed";
}
export { RemoteSteerableChangedEvent }
export { RemoteSteerableChangedEvent as SessionRemoteSteerableChangedEvent }

export declare type RemoteTaskType = "cca" | "cli";

declare class RepoChangeSet {
    private handle;
    private constructor();
    static create(git: GitHandlerContract, repoLocation: string, baseCommit: string, abortSignal?: AbortSignal): Promise<RepoChangeSet>;
    static create(repoLocation: string, baseCommit: string, abortSignal?: AbortSignal): Promise<RepoChangeSet>;
    getFileRanges(): RunnerFileRange[];
    getChangedFiles(): Set<string>;
    getChangedFilesSince(previous: RepoChangeSet): Set<string>;
    dispose(): void;
    [Symbol.dispose](): void;
    private requireHandle;
}

declare type RepoHostType = NonNullable<RuntimeNative.GitRepoIdentifierInfo["hostType"]>;

/**
 * Optional callback for requesting user permission when a preToolUse hook returns `"ask"`.
 * Returns a {@link PermissionRequestResult} indicating whether the tool call was approved or denied
 * (for example, via an `"approved"` vs `"denied"` kind).
 */
export declare type RequestHookPermissionFn = (request: PermissionRequest_2) => Promise<PermissionRequestResult>;

declare type RequestId = string | number;

declare interface RequestMeta {
    progressToken?: ProgressToken;
    "io.modelcontextprotocol/related-task"?: RelatedTaskMetadata;
    [key: string]: unknown;
}

declare type RequestPermissionFn = (permission: PermissionRequest_2) => Promise<PermissionRequestResult>;

declare type ResolveArgs = {
    authInfo: AuthInfo;
    integrationId: string;
    sessionId: string;
    logger: RunnerLoggerContract_2;
    onSessionToken?: (token: string) => void;
};

/**
 * Resolve a GitHub token into a full AuthInfo by calling `fetchCopilotUser`.
 * Extracted as a standalone function for per-session auth in SDK server mode.
 *
 * The network validation is cached, so repeated create/resolve calls with the same
 * token skip the `/copilot_internal/user` round-trip. The cache is
 * stale-while-revalidate: once an entry passes its TTL the cached value is still
 * returned immediately while it refreshes in the background, so only the first
 * (cold) resolution of a given token blocks on the network.
 *
 * This function also backs freshness-sensitive shared APIs (`SDKServer.account.getQuota`,
 * `modelsApi.list`) that read `copilotUser` directly. Callers that need live data
 * — e.g. quota reads, where a cached value could show outdated remaining-request
 * counts — should pass `{ skipCache: true }` to bypass the cache and fetch fresh.
 *
 * Server-to-server tokens (`ghs_`) and OpenShell proxy resolver placeholders
 * are short-circuited before the cache: `fetchCopilotUser` would 403 for `ghs_`
 * tokens, and placeholder tokens are not authenticated until rewritten at the
 * HTTP transport layer. In both cases a synthetic `CopilotUserResponse` is built
 * from the host.
 *
 * The resolution, cache, and short-circuits are implemented in the Rust runtime
 * (`resolve_auth_info`); this is a thin shim that applies the default host and
 * User-Agent and parses the serialized `AuthInfo`.
 *
 * @param token A GitHub token (PAT, fine-grained, OAuth, server-to-server, or OpenShell placeholder).
 * @param host  Optional GitHub host URL. Defaults to `getGithubUri()`.
 * @param options.skipCache When true, bypass the cache entirely: fetch a fresh
 *   `copilotUser` without reading or populating the cache. Use for freshness-sensitive
 *   reads.
 * @returns A `TokenAuthInfo` with populated `copilotUser` for the token's identity.
 * @throws Error if the token is invalid or the API call fails. Validation now runs
 *   in the Rust runtime, so a failed `fetchCopilotUser` surfaces as a plain `Error`
 *   whose message mirrors the previous `GitHubApiError.message` (e.g.
 *   `Failed to fetch Copilot user info: 401 Unauthorized...`). The `GitHubApiError`
 *   class and its structured `status`/`responseMessage` fields do not cross the
 *   napi boundary; callers propagate the error rather than branching on its type.
 */
export declare function resolveAuthInfoFromToken(token: string, host?: string, options?: {
    skipCache?: boolean;
}): Promise<AuthInfo>;

export declare function resolveAutopilotObjectivesFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

export declare function resolveCompactSystemPromptFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

/** An account-scoped managed-settings snapshot resolved without a session. */
export declare interface ResolvedManagedSettingsSnapshot {
    /**
     * The account identity (host + login) this snapshot was resolved for, or
     * `undefined` when unauthenticated (device-MDM-only resolution). Clients can
     * key a per-account cache on this value.
     */
    account: string | undefined;
    /**
     * The resolved managed settings and their source/precedence — the identical
     * payload carried by the `session.managed_settings_resolved` event, so a
     * client can drive the same UI before any session exists.
     */
    resolved: ManagedSettingsResolvedData;
}

/**
 * The result of resolving which model (and optional client-option tweaks)
 * to use for an agent invocation.
 */
declare interface ResolvedModel {
    /** The model ID to use (e.g. "claude-sonnet-4.6", "gpt-5.3-codex"). */
    model: string;
    /** Optional client-option overrides layered on top of the model's default config. */
    clientOptionOverrides?: Partial<ClientOptions>;
}

/**
 * Backend-tagged result of resolving a user-selected model id to the backend that
 * will actually serve it. The backend is determined by the *selection id*: a
 * provider-qualified id (`provider/model`, naming a registered BYOK provider) is
 * served by that provider; every bare id is served by CAPI (the implicit default
 * provider). Because qualified and bare ids occupy disjoint namespaces, the backend
 * is unambiguous from the selection id alone — there is no shadowing and no need to
 * re-derive a backend from the resolved wire string.
 */
export declare type ResolvedModelBackend = {
    backend: "capi";
    id: string;
} | {
    backend: "byok";
    /** Provider-qualified selection id (registry key, model-list entry id, switchTo target). */
    id: string;
    /** Name of the {@link NamedProviderConfig} that serves this model. */
    providerName: string;
    /** Well-known base model id used for behavior/capability/config lookup. */
    behaviorModelId: string;
    /** Model name sent to the provider API for inference. */
    wireModel: string;
    /** Legacy-shaped provider config (named provider connection + model wire/limits). */
    providerConfig: ProviderConfig;
    /** Synthesized model metadata (capabilities/limits) for this BYOK model. */
    modelMetadata: Model;
};

declare interface ResolvedScheduledPrompt {
    readonly prompt: string;
    readonly displayPrompt?: string;
    readonly mode?: SessionMode_2;
}

export declare function resolveExpFlag(featureFlagService: IFeatureFlagService | undefined, expFlag: ExpFlagKey, featureFlag: FeatureFlag, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

export declare function resolveExpStringFlag(featureFlagService: IFeatureFlagService | undefined, expFlag: ExpFlagKey): Promise<string | undefined>;

export declare function resolveFeatureFlags(isStaff: boolean, isExperimental: boolean, isTeam: boolean, options?: FeatureFlagResolutionOptions): FeatureFlags;

export declare function resolveNoViewLineNumbersFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

/**
 * Synchronous `Override`-semantics read of `WORKTREE_DEFAULT_BRANCH`.
 *
 * The flag is registered with an ExP mapping, but the flag snapshot published to
 * the UI (`getAllFlags()`) carries only statically resolved values -- the ExP
 * assignment is folded in by the async {@link IFeatureFlagService.getFlag}
 * accessor, which synchronous consumers (the slash-command dependency build)
 * cannot await. Mirror `Override` off the live ExP snapshot instead: a server
 * assignment wins in both directions, otherwise fall back to the static
 * (team-availability / env / config) value. The service notifies its listeners
 * once ExP assignments land, so consumers re-resolve on the next render.
 */
export declare function resolveWorktreeDefaultBranchEnabled(featureFlagService: Pick<IFeatureFlagService, "getAllExpFlagsSync"> | undefined, staticFlagEnabled: boolean): boolean;

declare interface ResourceContent extends BaseContentBlock {
    type: "resource";
    resource: ResourceContents;
}

declare type ResourceContents = TextResourceContents | BlobResourceContents;

declare interface ResourceLinkContent extends BaseContentBlock {
    type: "resource_link";
    uri: string;
    name: string;
    description?: string;
    mimeType?: string;
    size?: number;
    title?: string;
    icons?: Array<{
        src: string;
        mimeType?: string;
        sizes?: string[];
        theme?: "light" | "dark";
    }>;
}

/**
 * An event that is emitted by the `Client` which contains the final response from the LLM.
 */
declare type ResponseEvent = {
    kind: "response";
    turn?: number;
    callId?: string;
    modelCall?: ModelCallParam;
    response: ChatCompletionMessage;
};

declare interface ResponseInputTokensDetails {
    audio_tokens?: number;
    cached_tokens?: number;
    cache_write_tokens?: number;
}

declare type ResponseLimitsEventState = "active" | "final" | "exhausted" | "blocked";

declare type ResponseLimitsStatus = ResponseLimitsStatusResult;

/**
 * Event emitted by the native response-limits pre-request stage when its
 * decision produces a status timeline update. The host re-emits it via
 * `emitResponseLimitsStatus` (`session.info` + telemetry), keeping emission
 * host-side and consistent with all other events while the limits decision and
 * its request effects run natively. The `status` / `state` shapes are
 * structurally compatible with `ResponseLimitsStatus` / `ResponseLimitsEventState`
 * in `src/core/session.ts` (declared inline to avoid a model→core import cycle).
 */
declare type ResponseLimitsStatusEvent = {
    kind: "response_limits_status";
    turn: number;
    status: {
        aiCreditsUsed?: number;
        aiCreditsRemaining?: number;
        maxAiCredits?: number;
        isLimitsExhausted: boolean;
        isFinalModelCall: boolean;
    };
    state: "active" | "final" | "exhausted" | "blocked";
    message: string;
};

declare type ResponsesMessageStatus = "in_progress" | "completed" | "incomplete";

declare interface ResponseTextConfig {
    format?: JsonObject;
    verbosity?: ResponseVerbosity | null;
}

declare type ResponseVerbosity = "low" | "medium" | "high";

/** Session resume metadata including current context and event count */
export declare interface ResumeData {
    /** Whether the session was already in use by another client at resume time */
    alreadyInUse?: boolean;
    /** Updated working directory and git context at resume time */
    context?: WorkingDirectoryContext;
    /** Context tier currently selected at resume time; null when no tier is active */
    contextTier?: ContextTier | null;
    /** When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false or omitted, pending work is normally marked as interrupted unless the resume passively joined live work owned by another client; sessionWasActive distinguishes that case. */
    continuePendingWork?: boolean;
    /** Total number of persisted events in the session at the time of resume */
    eventCount: number;
    /** On-disk byte size of the session's persisted events.jsonl file at resume time; omitted when the file does not exist or cannot be stat'd */
    eventsFileSizeBytes?: number;
    /** Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") */
    reasoningEffort?: string;
    /** Reasoning summary mode used for model calls, if applicable (e.g. "none", "concise", "detailed") */
    reasoningSummary?: ReasoningSummary;
    /** Whether this session supports remote steering via GitHub */
    remoteSteerable?: boolean;
    /** ISO 8601 timestamp when the session was resumed */
    resumeTime: string;
    /** Model currently selected at resume time */
    selectedModel?: string;
    /** Session limits currently configured at resume time; null when no limits are active */
    sessionLimits?: SessionLimitsConfig | null;
    /** True when this resume passively joined a session that already had live work running in the runtime - an agent turn, a native queue run, a queued resume continuation, or an in-flight send (for example, an extension joining a session another client was actively driving). False (or omitted) when the session had no live work or when the resume explicitly abandoned pending work, including cold resumes and suspended sessions that remain resident in memory. */
    sessionWasActive?: boolean;
    /** Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") */
    verbosity?: Verbosity;
}

/** Session event "session.resume". Session resume metadata including current context and event count */
declare interface ResumeEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session resume metadata including current context and event count */
    data: ResumeData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.resume". */
    type: "session.resume";
}
export { ResumeEvent }
export { ResumeEvent as SessionResumeEvent }

/**
 * Outcome of attempting to (re-)enable rewind file-change tracking while
 * resuming an existing session.
 *
 * - `enabled` — a rewind manager is installed and tracking is live.
 * - `unsupported` — the session can never track file changes (it is a subagent
 *   session, or it has no local session-state directory), so an explicit
 *   opt-in is a caller contract violation and is surfaced as an error.
 * - `no-prior-capture` — the session predates tracking: it already has root
 *   turns whose file preimages were never captured, so tracking cannot be
 *   started mid-history. Callers degrade to an untracked resume, since this is
 *   the shape of every session created before rewind tracking existed.
 */
export declare type ResumeFileChangeTrackingOutcome = "enabled" | "unsupported" | "no-prior-capture";

/**
 * Retrieves available models based on availability, policies, and integration
 * including capabilities and billing information, which may be cached from
 * previous calls.
 *
 * Returns two lists derived from the same CAPI response:
 * - `models`: the **session-visible / selectable** list. For OAuth callers this
 *   is the picker subset (`model_picker_enabled: true`). For HMAC callers
 *   (CCA/Actions runtime, which is not user-facing model-picking) this remains
 *   the whole filtered list (picker-disabled models included). On both paths,
 *   reserved subagent-only models (`SUBAGENT_ONLY_MODELS`) are always excluded —
 *   they must never reach a user-facing model list. This is what virtually
 *   all consumers (the `/model` picker, `--model` validation, custom-agent/SDK
 *   selection, `models.list`, ACP) should use.
 * - `unfilteredModels`: the **whole** filtered list (picker-disabled AND
 *   subagent-only models included), used for internal-only purposes:
 *   utility-model selection (e.g. session naming) and entitlement capture of the
 *   reserved subagent-only models for the built-in search subagent.
 *   `EXCLUDED_MODELS` and subscription-tier filtering still apply to non-staff
 *   users; only picker and policy filtering are omitted.
 *
 * Both lists are in order of preference to be the default model for new sessions
 * where the first model is the most preferred. They can be empty if no models
 * are available.
 */
export declare function retrieveAvailableModels(authInfo: AuthInfo, copilotUrl: string | undefined, integrationId: string, sessionId: string, logger: RunnerLoggerContract_2, featureFlagService?: IFeatureFlagService, options?: {
    skipCache?: boolean;
}): Promise<{
    models: Model[];
    unfilteredModels: Model[];
    copilotUrl: string | undefined;
    quotaSnapshots?: QuotaSnapshotsByType;
}>;

declare interface RewindUserTurn {
    eventId: string;
    userMessage: string;
    timestamp: string;
    isAutopilotContinuation: boolean;
}

/**
 * A Rule defines a pattern for matching permission requests.
 *
 * It is unfortunately generically named because it is intended to match across
 * different types of tool uses, e.g. `Shell(touch)` or `GitHubMCP(list_issues)`,
 * `view(.env-secrets)`
 */
declare type Rule = {
    /**
     * The kind of rule that should be matched e.g. `Shell` or `GitHubMCP`.
     */
    readonly kind: string;
    /**
     * If null, matches all arguments to the kind.
     */
    readonly argument: string | null;
};

declare interface RunFactoryApi {
    run(name: string, options: {
        args: unknown;
        limits?: FactoryLimits;
        toolCallId?: string;
    }): Promise<FactoryRunResult>;
    resume(runId: string, options: {
        limits?: FactoryLimits;
        toolCallId?: string;
    }): Promise<{
        factoryName: string;
        run: FactoryRunResult;
    }>;
    getRun(runId: string): Promise<{
        factoryName: string;
        run: FactoryRunResult;
    }>;
    getMetadataSnapshot?(): FactoryMeta[];
}

/** Options controlling factory invocation. */
declare interface RunOptions {
    /** Per-invocation resource ceiling overrides. */
    limits?: FactoryRunLimits;
    /** Run identifier whose journal and progress should seed this resumed run. */
    resumeFromRunId?: string;
}

declare type RuntimeNativeModule = typeof RuntimeNative;

declare type RuntimeSandboxSettingsConfig = Omit<RuntimeNative.SandboxConfig, "enabled"> & {
    enabled?: boolean;
};

declare type RuntimeSessionDatabaseHandle = InstanceType<typeof RuntimeNative.SessionDatabaseHandle>;

declare type RuntimeSettings = RuntimeSettings_2;

declare type RuntimeSettings_2 = {
    version?: string;
    api?: {
        aipSweAgent?: {
            token?: string;
        };
        anthropic?: {
            baseUrl?: string;
            bearerToken?: string;
            key?: string;
        };
        copilot?: {
            autoMode?: boolean;
            azureKeyVaultUri?: string;
            capiSessionToken?: string;
            hmacKey?: string;
            integrationId?: string;
            previousSessionIds?: string[];
            sessionId?: string;
            token?: string;
            traceParent?: string;
            url?: string;
            useSessions?: boolean;
        };
        github?: {
            mcpServerToken?: string;
        };
        openai?: {
            apiKey?: string;
            azure?: {
                apiVersion?: string;
                bearerToken?: string;
                url?: string;
            };
            azureKeyVaultUri?: string;
            azureSecretName?: string;
            baseUrl?: string;
            url?: string;
        };
    };
    builtInAgents?: {
        rubberDuck?: boolean;
        rubberDuckAutoInvoke?: boolean;
    };
    blackbird?: {
        auth?: {
            metisApiKey?: string;
            modelBasedRetrievalToken?: string;
        };
        backfillScoreThreshold?: number;
        mode?: "initial-search" | "tool";
        repoNwo?: string;
    };
    clientName?: string;
    configDir?: string;
    workingDirectory?: string;
    experiments?: {
        [key: string]: string;
    };
    featureFlags?: {
        [key: string]: boolean | undefined;
    };
    github?: {
        host?: string;
        hostProtocol?: string;
        owner?: {
            id?: number;
            name?: string;
        };
        repo?: {
            branch?: string;
            commit?: string;
            id?: number;
            name?: string;
            readWrite?: boolean;
            signCommits?: boolean;
        };
        pr?: {
            commitCount?: number;
        };
        secretScanningUrl?: string;
        serverUrl?: string;
        token?: string;
        uploadsUrl?: string;
        user?: {
            actorId?: number;
            actorLogin?: string;
            email?: string;
            name?: string;
        };
    };
    job?: {
        builtInToolAvailability?: {
            createPullRequest?: boolean;
            reportProgress?: boolean;
        };
        eventType?: string;
        isTriggerJob?: boolean;
        nonce?: string;
    };
    logs?: {
        eventsLogDir?: string;
        eventsLogIncludesSubagents?: boolean;
    };
    lsp?: {
        clientName: string;
    };
    onlineEvaluation?: {
        disableOnlineEvaluation?: boolean;
        enableOnlineEvaluationOutputFile?: boolean;
    };
    problem?: {
        action?: "fix" | "fix-pr-comment" | "task";
        contentFilterMode?: ContentFilterMode;
        customAgentName?: string;
        statement?: string;
    };
    service?: {
        agent?: {
            defaultReasoningEffort?: string;
            model?: string;
            modelFamily?: string;
            requestHeaders?: Record<string, string>;
            retryPolicy?: ClientRetryPolicy;
            [key: string]: unknown;
        };
        callback?: {
            url?: string;
        };
        instance?: {
            id?: string;
        };
        tools?: {
            [toolName: string]: {
                [key: string]: unknown;
            } | undefined;
        };
    };
    swebench_base_commit?: string;
    testEnableVoteTool?: boolean;
    testInjectedMemories?: string;
    testInjectedSessionSearchContext?: string;
    testInjectedScopedMemories?: {
        repoMemories?: string;
        repoName?: string;
        storeToolDefinitionVersion?: string;
        userLogin?: string;
        userMemories?: string;
    };
    testVoteToolEnabled?: boolean;
    timeoutMs?: number;
    startTimeMs?: number;
    tools?: {
        bash?: {
            defaultTimeout?: number;
        };
        largeOutput?: {
            enabled?: boolean;
            maxSizeBytes?: number;
            outputDir?: string;
        };
        memory?: {
            storeEnabled?: boolean;
            voteEnabled?: boolean;
        };
        validation?: {
            advisory?: {
                enabled?: boolean;
            };
            codeql?: {
                enabled?: boolean;
            };
            codeReview?: {
                enabled?: boolean;
                model?: string;
            };
            dependabotTimeout?: number;
            secretScanning?: {
                enabled?: boolean;
            };
            timeout?: number;
        };
        [key: string]: unknown;
    };
    trajectory?: {
        outputFile?: string;
    };
};

declare type RuntimeSettingsInput = RuntimeSettings_2;

declare type RuntimeSettingsSecretName = "githubToken" | "copilotToken" | "copilotHmacKey" | "copilotIntegrationId" | "copilotSessionId" | "copilotTraceParent" | "jobNonce" | "aipSweAgentToken" | "githubMcpServerToken";

declare type RustMcpToolDescriptor = Omit<Tool, "callback"> & {
    toolId: string;
    serverName?: string;
    mcpServerName?: string;
    filterMode?: ContentFilterMode;
};

/** Sampling request completion notification signaling UI dismissal */
export declare interface SamplingCompletedData {
    /** Request ID of the resolved sampling request; clients should dismiss any UI for this request */
    requestId: string;
}

/** Session event "sampling.completed". Sampling request completion notification signaling UI dismissal */
export declare interface SamplingCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Sampling request completion notification signaling UI dismissal */
    data: SamplingCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "sampling.completed". */
    type: "sampling.completed";
}

/** Data-only request for sampling inference — no CLI/UI concerns. */
declare interface SamplingInferenceRequest {
    /** The MCP server name that initiated the request. */
    serverName: string;
    /** The JSON-RPC request ID from the MCP protocol. */
    requestId: string | number;
    /** System prompt from the MCP sampling request. */
    systemPrompt: string;
    /** Conversation messages converted from MCP SamplingMessage format. */
    messages: ChatCompletionMessageParam[];
    /** Maximum number of output tokens requested by the MCP server. */
    maxTokens: number;
}

declare interface SamplingMessage {
    role: "user" | "assistant";
    content: SamplingMessageContentBlock | SamplingMessageContentBlock[];
    _meta?: Record<string, unknown>;
}

declare type SamplingMessageContentBlock = TextContent_2 | ImageContent_2 | AudioContent_2 | ToolUseContent | ToolResultContent | ResourceLinkContent | ResourceContent;

/** Sampling request from an MCP server; contains the server name and a requestId for correlation */
export declare interface SamplingRequestedData {
    /** The JSON-RPC request ID from the MCP protocol */
    mcpRequestId: unknown;
    /** Unique identifier for this sampling request; used to respond via session.respondToSampling() */
    requestId: string;
    /** Name of the MCP server that initiated the sampling request */
    serverName: string;
    [key: string]: unknown;
}

/** Session event "sampling.requested". Sampling request from an MCP server; contains the server name and a requestId for correlation */
export declare interface SamplingRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Sampling request from an MCP server; contains the server name and a requestId for correlation */
    data: SamplingRequestedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "sampling.requested". */
    type: "sampling.requested";
}

/** Resolved sandbox configuration. */
declare interface SandboxConfig {
    /** Whether to auto-add the current working directory to readwritePaths. Default: true. */
    addCurrentWorkingDirectory?: boolean;
    /** Whether to auto-grant read access to common developer-tool caches, registries, and toolchains in their default home locations (cargo, go, npm, Maven, and more), plus read-write access to (and, on Unix, up-front creation of) the scratch caches builds write on every run (go-build, ccache, sccache, Gradle caches, Cargo lock/tracker files), so builds work without extra configuration; a relocated CARGO_HOME additionally gets its Cargo lock files granted read-write. Default: true (enabled by default; set to false to opt out). */
    allowDevToolAccess?: boolean;
    /** Credential-injection capability flags. */
    auth?: SandboxConfigAuth;
    /** Whether sandboxing is enabled for the session. */
    enabled: boolean;
    /** User-managed sandbox policy fragment merged into the auto-discovered base policy. */
    userPolicy?: SandboxConfigUserPolicy;
}

/** Credential-injection capability flags applied while the sandbox is enabled. */
declare interface SandboxConfigAuth {
    /** Whether to export `GH_TOKEN` so the `gh` CLI authenticates inside the sandbox without the OS keyring the sandbox blocks. Default: false (opt-in). */
    gh?: boolean;
    /** Whether to inject git credentials as an `http.<url>.extraheader` so authenticated HTTPS git works inside the sandbox without the shell-based credential helper the sandbox blocks. github.com is served by the Copilot token; every other forge (Azure DevOps, GitHub Enterprise Server, GitLab, ...) by a credential the host resolves from the user's own helper before the sandbox is applied. Default: false (opt-in). */
    git?: boolean;
}

/** User-managed sandbox policy fragment merged into the auto-discovered base policy. */
declare interface SandboxConfigUserPolicy {
    /** Deprecated legacy location for `seatbelt`; read only when the top-level `seatbelt` is absent. */
    experimental?: SandboxConfigUserPolicyExperimental;
    /** Filesystem rules to merge into the base policy. */
    filesystem?: SandboxConfigUserPolicyFilesystem;
    /** Network rules to merge into the base policy. */
    network?: SandboxConfigUserPolicyNetwork;
    /** macOS seatbelt options to merge into the base policy. */
    seatbelt?: SandboxConfigUserPolicySeatbelt;
}

/** Platform-specific experimental policy fields. */
declare interface SandboxConfigUserPolicyExperimental {
    /** macOS seatbelt experimental options. */
    seatbelt?: SandboxConfigUserPolicyExperimentalSeatbelt;
}

/** macOS seatbelt experimental options. */
declare interface SandboxConfigUserPolicyExperimentalSeatbelt {
    /** Whether the macOS seatbelt profile may access the keychain. */
    keychainAccess?: boolean;
}

/** Filesystem rules to merge into the base policy. */
declare interface SandboxConfigUserPolicyFilesystem {
    /** Whether to clear the policy when the session exits. */
    clearPolicyOnExit?: boolean;
    /** Paths explicitly denied. */
    deniedPaths?: string[];
    /** Paths granted read-only access. */
    readonlyPaths?: string[];
    /** Paths granted read/write access. */
    readwritePaths?: string[];
}

/** Network rules to merge into the base policy. */
declare interface SandboxConfigUserPolicyNetwork {
    /** Whether traffic to local/loopback addresses is allowed. */
    allowLocalNetwork?: boolean;
    /** Whether outbound network traffic is allowed at all. */
    allowOutbound?: boolean;
    /** HTTP proxy the sandboxed process routes traffic through. Enforced on Windows and cooperative (honored by well-behaved tools, not strictly enforced) on Linux and macOS. Credentials go in the separate `username`/`password` fields. A credential-free http:// loopback proxy URL is routed through the localhost proxy automatically; an https:// or authenticated loopback URL is used as-is. */
    proxy?: SandboxConfigUserPolicyNetworkProxy;
}

/** HTTP proxy configuration for sandboxed traffic. */
declare interface SandboxConfigUserPolicyNetworkProxy {
    /** Optional password for proxy authentication, combined with the URL at spawn time. The persisted value may be a literal password, a `${secret:…}` reference resolved from the OS keychain, or a `${VAR}`/`$VAR` environment reference; it is resolved just before the sandboxed process routes through the proxy. The /sandbox dialog stores a real password in the OS keychain and persists only a `${secret:…}` placeholder (never plaintext in settings.json); the field is masked in the dialog and redacted by /settings show. */
    password?: string;
    /** Proxy URL (e.g. http://proxy.example.com:8080). The port is optional and defaults to the scheme's standard port when omitted. Credentials must not be embedded here — a `user:pass@` authority is rejected; put them in the separate `username`/`password` fields. A credential-free http:// loopback URL is routed through the localhost proxy automatically; loopback covers localhost and any *.localhost subdomain, the whole 127.0.0.0/8 range, ::1, and IPv4-mapped loopback (::ffff:127.0.0.1). An https:// URL, or one with a username/password set, is used as-is. */
    url: string;
    /** Optional username for proxy authentication. Combined with the URL (and `password`) into `user:pass@host` when the sandboxed process routes through the proxy. */
    username?: string;
}

/** macOS seatbelt-specific options. */
declare interface SandboxConfigUserPolicySeatbelt {
    /** Whether the macOS seatbelt profile may access the keychain. */
    keychainAccess?: boolean;
}

declare type SandboxExperimentalPolicy = {
    seatbelt?: SandboxSeatbeltPolicy;
    [key: string]: unknown;
};

declare type SandboxNetworkPolicy = {
    allowOutbound?: boolean;
    allowLocalNetwork?: boolean;
    /**
     * HTTP proxy for sandboxed traffic. `url` and `username` are user-facing;
     * `password` is stored securely in the OS keychain and persisted here as a
     * `${secret:…}` reference (a `${VAR}` environment-variable reference is also
     * accepted for back-compat), never the plaintext secret, and is masked in
     * the dialog. The effective policy resolves the reference, folds the
     * credentials into the URL, and auto-routes credential-free loopback URLs
     * through mxc's localhost proxy.
     */
    proxy?: SandboxProxyPolicy;
    [key: string]: unknown;
};

declare type SandboxPathPolicy = {
    readwritePaths?: string[];
    readonlyPaths?: string[];
    deniedPaths?: string[];
    clearPolicyOnExit?: boolean;
    [key: string]: unknown;
};

declare type SandboxProxyPolicy = {
    url: string;
    username?: string;
    password?: string;
};

declare type SandboxSeatbeltPolicy = {
    keychainAccess?: boolean;
    [key: string]: unknown;
};

declare type SanitizedMcpResource = {
    uri: string;
    name: string;
    title?: string;
    description?: string;
    mimeType?: string;
    size?: number;
    icons?: SanitizedMcpResourceIcon[];
    annotations?: SanitizedMcpResourceAnnotations;
    _meta?: Record<string, unknown>;
    additionalProperties?: Record<string, unknown>;
};

declare type SanitizedMcpResourceAnnotations = {
    audience?: string[];
    priority?: number;
    lastModified?: string;
    additionalProperties?: Record<string, unknown>;
};

declare type SanitizedMcpResourceIcon = {
    src: string;
    mimeType?: string;
    sizes?: string;
    theme?: string;
    additionalProperties?: Record<string, unknown>;
};

declare type SanitizedMcpResourceTemplate = {
    uriTemplate: string;
    name: string;
    title?: string;
    description?: string;
    mimeType?: string;
    icons?: SanitizedMcpResourceIcon[];
    annotations?: SanitizedMcpResourceAnnotations;
    _meta?: Record<string, unknown>;
    additionalProperties?: Record<string, unknown>;
};

/** Register an absolute-time scheduled prompt. */
declare interface ScheduleAddAtRequest {
    /** Epoch milliseconds when the prompt should fire. */
    at: number;
    /** Optional display-only prompt label. */
    displayPrompt?: string;
    /** Prompt text to enqueue when the schedule fires. */
    prompt: string;
    /** Whether the schedule should re-arm after each tick. Defaults to false. */
    recurring?: boolean;
}

/** Register a cron scheduled prompt. */
declare interface ScheduleAddCronRequest {
    /** 5-field cron expression. */
    cron: string;
    /** Optional display-only prompt label. */
    displayPrompt?: string;
    /** Prompt text to enqueue when the schedule fires. */
    prompt: string;
    /** Whether the schedule should re-arm after each tick. Defaults to true. */
    recurring?: boolean;
    /** IANA timezone for evaluating the cron expression. */
    tz?: string;
}

/** Register a relative-interval scheduled prompt. */
declare interface ScheduleAddRequest {
    /** Optional display-only prompt label. */
    displayPrompt?: string;
    /** Human-readable interval such as `30s`, `5m`, or `2h`. */
    interval: string;
    /** Prompt text to enqueue when the schedule fires. */
    prompt: string;
    /** Whether the schedule should re-arm after each tick. Defaults to true. */
    recurring?: boolean;
}

/** Result of registering or re-arming a scheduled prompt. */
declare interface ScheduleAddResult {
    /** The registered or updated schedule entry. */
    entry?: ScheduleEntry;
    /** User-facing validation error, when registration failed. */
    error?: string;
}

/** Register a self-paced scheduled prompt. */
declare interface ScheduleAddSelfPacedRequest {
    /** Optional display-only prompt label. */
    displayPrompt?: string;
    /** Prompt text to enqueue when the schedule fires. */
    prompt: string;
}

/** Scheduled prompt cancelled from the schedule manager dialog */
export declare interface ScheduleCancelledData {
    /** Id of the scheduled prompt that was cancelled */
    id: number;
}

/** Session event "session.schedule_cancelled". Scheduled prompt cancelled from the schedule manager dialog */
declare interface ScheduleCancelledEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Scheduled prompt cancelled from the schedule manager dialog */
    data: ScheduleCancelledData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.schedule_cancelled". */
    type: "session.schedule_cancelled";
}
export { ScheduleCancelledEvent }
export { ScheduleCancelledEvent as SessionScheduleCancelledEvent }

/** Scheduled prompt registered via /every or /after */
export declare interface ScheduleCreatedData {
    /** Absolute fire time (epoch milliseconds) for a one-shot calendar schedule */
    at?: number;
    /** 5-field cron expression for a recurring calendar schedule, evaluated in `tz` */
    cron?: string;
    /** Optional user-facing label shown in the timeline instead of the actual prompt (e.g. `/skill-name args` when the prompt is a skill invocation expansion) */
    displayPrompt?: string;
    /** Sequential id assigned to the scheduled prompt within the session */
    id: number;
    /** Interval between ticks in milliseconds (relative-interval schedules) */
    intervalMs?: number;
    /** Who created the schedule (`user` or `model`). Persisted so a resumed session keeps gating non-user schedules from firing skills that opted out of model invocation. Absent on entries created before this field existed; a missing origin fails closed (treated the same as a non-user origin), so such a schedule may not resolve a `disable-model-invocation` skill. */
    origin?: ScheduleOrigin;
    /** Prompt text that gets enqueued on every tick */
    prompt: string;
    /** Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`) */
    recurring?: boolean;
    /** True for a self-paced (`dynamic`) schedule: no fixed cadence; the model arms each next run via the `manage_schedule` `wakeup` action. `nextRunAt` is model-controlled rather than auto-computed. */
    selfPaced?: boolean;
    /** IANA timezone the `cron` expression is evaluated in */
    tz?: string;
}

/** Session event "session.schedule_created". Scheduled prompt registered via /every or /after */
declare interface ScheduleCreatedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Scheduled prompt registered via /every or /after */
    data: ScheduleCreatedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.schedule_created". */
    type: "session.schedule_created";
}
export { ScheduleCreatedEvent }
export { ScheduleCreatedEvent as SessionScheduleCreatedEvent }

declare type ScheduledCommandResolver = (name: string, input: string) => Promise<ResolvedScheduledPrompt | null>;

/** Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. */
declare interface ScheduleEntry {
    /** Absolute fire time (epoch milliseconds) for a one-shot calendar schedule. */
    at?: number;
    /** 5-field cron expression for a recurring calendar schedule, evaluated in `tz`. */
    cron?: string;
    /** Display-only label for the prompt as shown in the UI (e.g. `/skill-name` for a skill-invocation schedule). The actual enqueued prompt is `prompt`. */
    displayPrompt?: string;
    /** Sequential id assigned by the runtime within the session. Stable across resumes (rebuilt from the event log). */
    id: number;
    /** Interval between scheduled ticks, in milliseconds (relative-interval schedules). */
    intervalMs?: number;
    /** ISO 8601 timestamp when the next tick is scheduled to fire. */
    nextRunAt: string;
    /** Prompt text that gets enqueued on every tick. */
    prompt: string;
    /** Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`). */
    recurring: boolean;
    /** True for a self-paced (`dynamic`) schedule: no fixed cadence; the model arms each next run via the `manage_schedule` `wakeup` action. `nextRunAt` is model-controlled. */
    selfPaced?: boolean;
    /** IANA timezone the `cron` expression is evaluated in. */
    tz?: string;
}

/** Whether the session currently has an active self-paced schedule. */
declare interface ScheduleHasSelfPacedResult {
    /** True when at least one active schedule is self-paced. */
    hasSelfPaced: boolean;
}

/** Snapshot of the currently active recurring prompts for this session. */
declare interface ScheduleList {
    /** Active scheduled prompts, ordered by id. */
    entries: ScheduleEntry[];
}

/** Who created the schedule: `user` (an explicit user action such as `/every` or `/after`) or `model` (the agent via the `manage_schedule` tool). Gates whether a scheduled skill that opted out of model invocation may fire: only user-created schedules may. */
export declare type ScheduleOrigin = "user" | "model";

/** Self-paced schedule re-armed for its next run */
export declare interface ScheduleRearmedData {
    /** Id of the self-paced schedule that was re-armed */
    id: number;
    /** Absolute time (epoch milliseconds) the model armed the next run to fire */
    nextRunAt: number;
}

/** Session event "session.schedule_rearmed". Self-paced schedule re-armed for its next run */
declare interface ScheduleRearmedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Self-paced schedule re-armed for its next run */
    data: ScheduleRearmedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.schedule_rearmed". */
    type: "session.schedule_rearmed";
}
export { ScheduleRearmedEvent }
export { ScheduleRearmedEvent as SessionScheduleRearmedEvent }

/** Re-arm a self-paced scheduled prompt. */
declare interface ScheduleRearmSelfPacedRequest {
    /** Epoch milliseconds when the prompt should next fire. */
    at: number;
    /** Id of the self-paced scheduled prompt. */
    id: number;
}

/** Identifier of the scheduled prompt to remove. */
declare interface ScheduleStopRequest {
    /** Id of the scheduled prompt to remove. */
    id: number;
}

/** Remove a scheduled prompt by id. The result entry is omitted if the id was unknown. */
declare interface ScheduleStopResult {
    /** The removed entry, or omitted if no entry matched. */
    entry?: ScheduleEntry;
}

/**
 * Call-invariant configuration for native screenshot pruning. The native model
 * client prunes already-tagged screenshots in its `preRequest` stage from this
 * config. `preLeaf`/`postLeaf` encode the two `session.ts` registrations — one
 * before the JS leaf runs compaction/truncation and one after it runs vision.
 * For segmented agent pre-request flows, `preRequestInsertionIndex` lets the
 * Rust seam run the prune between the native image stage and the remaining JS
 * leaf.
 */
declare interface ScreenshotPruneConfig {
    /** Minimum tagged screenshots always retained (defaults to the native policy). */
    keep?: number;
    /** Batch interval: up to `keep + interval` may remain between prunes (defaults to the native policy). */
    interval?: number;
    /** Run the prune before the JS leaf processors (`session.ts` screenshot #1). Defaults to true. */
    preLeaf?: boolean;
    /** Run the prune after the JS leaf processors (`session.ts` screenshot #6). Defaults to true. */
    postLeaf?: boolean;
    /** Run the prune after the native image stage at the matching processor split. */
    preRequestInsertionIndex?: number;
}

/**
 * CAPI-delivered flag name that gates the CLI search subagent tool. Kept lowercase
 * to match the flag emitted by CAPI and read by `isSearchSubagentEnabled`; exported
 * as the single source of truth so consumers reference the constant instead of the
 * raw string literal. The flag's availability tier is defined in the Rust flag
 * catalog (`FEATURE_FLAGS` in runtime `feature_flags.rs`).
 */
export declare const SEARCH_SUBAGENT_FEATURE_FLAG = "copilot_swe_agent_cli_search_subagent";

/** A single FTS5 search result. */
declare interface SearchResult {
    session_id: string;
    source_type: string;
    content: string;
    rank: number;
}

/** Secret values to add to the redaction filter. */
declare interface SecretsAddFilterValuesRequest {
    /** Raw secret values to register for redaction */
    values: string[];
}

/** Confirmation that the secret values were registered. */
declare interface SecretsAddFilterValuesResult {
    /** Whether the values were successfully registered */
    ok: true;
}

/**
 * Override operation for a single system prompt section.
 * A static operation (replace, remove, append, prepend), a transform callback,
 * or a preserve marker (opt-out from group removal).
 */
declare type SectionOverride = StaticSectionOverride | TransformSectionOverride | PreserveSectionOverride;

/**
 * Batched transform callback for system prompt sections.
 * Receives a map of section IDs to their current rendered content,
 * returns a map of section IDs to their transformed content.
 */
declare type SectionTransformFn = (sections: Record<string, string>) => Promise<Record<string, string>>;

/** The UI mode the agent was in when this message was sent. Defaults to the session's current mode. */
declare type SendAgentMode = "interactive" | "plan" | "autopilot" | "shell";

/** Parameters for session.extensions.sendAttachmentsToMessage. */
declare interface SendAttachmentsToMessageParams {
    /** Attachments to push into the next user-message turn. extension_context entries take the slim shape; standard variants take their full AttachmentSchema shape. */
    attachments: PushAttachment[];
    /** Optional canvas instance binding the push for provenance. When supplied, the runtime resolves the canvas, verifies it is owned by the calling extension, and stamps canvasId/instanceId onto each extension_context entry. When omitted, no resolution runs and those fields stay unset on the attachment. */
    instanceId?: string;
}

declare type SendInboxEntryInput = {
    recipientSessionId: string;
    senderId: string;
    senderName: string;
    senderType: string;
    interactionId: string;
    summary: string;
    content: string;
};

declare type SendInboxPublisher = (input: {
    summary: string;
    content: string;
}) => Promise<SendInboxResult>;

declare type SendInboxResult = {
    status: "published";
    entryId: string;
} | {
    status: "rejected";
    reason?: string;
};

/** A single user message to append to the session as part of a `session.sendMessages` turn */
declare interface SendMessageItem {
    /** Optional attachments (files, directories, selections, blobs, GitHub references) to include with this message */
    attachments?: Attachment_2[];
    /** If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. */
    billable?: boolean;
    /** If provided, this is shown in the timeline instead of `prompt` */
    displayPrompt?: string;
    /** The user message text */
    prompt: string;
    /** If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange */
    requiredTool?: string;
    /** Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-<command-id>` for command-originated messages, `schedule-<numeric-id>` for scheduled prompts, or `agent-<agent-id>` for prompts sent by another agent. */
    source?: string;
}

declare type SendMessagesParams = SendMessagesRequest;

/** Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. */
declare interface SendMessagesRequest {
    /** The UI mode the agent was in when these messages were sent. Defaults to the session's current mode. */
    agentMode?: SendAgentMode;
    /** The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. */
    messages: SendMessageItem[];
    /** How to deliver the messages. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. */
    mode?: SendMode;
    /** If true, adds the messages to the front of the queue instead of the end */
    prepend?: boolean;
    /** Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. */
    requestHeaders?: Record<string, string>;
    /** W3C Trace Context traceparent header for distributed tracing of this agent turn */
    traceparent?: string;
    /** W3C Trace Context tracestate header for distributed tracing */
    tracestate?: string;
    /** If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. */
    wait?: boolean;
}

/** Result of sending zero or more user messages */
declare interface SendMessagesResult {
    /** Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. */
    messageIds: string[];
}

/** How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. */
declare type SendMode = "enqueue" | "immediate";

export declare interface SendOptions {
    prompt: string;
    /** If provided, this is shown in the timeline instead of prompt */
    displayPrompt?: string;
    attachments?: Attachment[];
    mode?: "enqueue" | "immediate";
    /**
     * If true, adds the message to the front of the queue instead of the end.
     * This is useful when a queued command (e.g., /plan, /review) returns an agentMessage
     * that should be processed immediately after the command, before other queued items.
     * Without this, the agentMessage would be appended to the end and processed after
     * any other items already in the queue.
     */
    prepend?: boolean;
    /**
     * If set to false, this message won't trigger a PRU (Premium Request Unit) charge.
     * User messages default to billable. Set to false to override.
     */
    billable?: boolean;
    /**
     * If set, the request will fail if the named tool is not available when this message
     * is among the user messages at the start of the current exchange (after the last
     * assistant message). Use this to guard messages that reference a specific tool.
     */
    requiredTool?: string;
    /** The agent mode active when this message was sent (interactive, plan, autopilot) */
    agentMode?: UserMessageAgentMode;
    /** Internal: recipient loop state captured before an agent message entered the task queue. */
    delivery?: UserMessageDelivery;
    /**
     * Source identifier for this message.
     * - `"user"`: explicitly attributed user prompt in a child agent session.
     * - `"system"`: runtime-generated notifications hidden from the timeline.
     * - `"autopilot"`: runtime-generated autopilot continuation.
     * - `` `command-${id}` ``: injected by a remote command with the given MC command id.
     * - `` `schedule-${id}` ``: tick from a scheduled prompt with the given registry id (e.g. `/every`).
     * - `` `agent-${id}` ``: prompt sent by another agent.
     */
    source?: SendSource;
    /** Structured metadata for system notifications. Only used when source is "system". */
    notificationKind?: SystemNotification;
    /** Revalidates and commits a deferred system notification when it is emitted. */
    notificationDelivery?: {
        isStillValid?: () => boolean;
        onDelivered: () => number | void;
    };
    /**
     * Internal: serializable handle for a deferred system notification's live
     * delivery callbacks. The native session queue persists SendOptions as plain
     * JSON, which strips the `notificationDelivery` closures; this id lets the
     * host re-hydrate them from `pendingNotificationDeliveries` when the queued
     * turn actually runs.
     */
    notificationDeliveryId?: string;
    /**
     * Custom HTTP headers to include in outbound model requests for this turn.
     * Merged with session-level provider headers: per-turn headers augment and
     * overwrite session-level headers with the same key.
     */
    requestHeaders?: Record<string, string>;
    /**
     * Marks the message as "passive" — its presence alone must not start,
     * continue, or restart the agent loop. Passive messages are delivered
     * opportunistically (bundled into model calls that are already going to
     * happen) and otherwise either deferred to the next user-driven turn
     * (`wait-for-next-turn`) or discarded (`drop`).
     *
     * Default `false` preserves existing waking behavior.
     */
    passive?: PassivePolicy;
    /** Internal: when set, an immediate message waits until this pre-request turn in the same run. */
    deferUntilPreRequestTurn?: number;
    /** Internal: run id for which deferUntilPreRequestTurn applies. */
    deferImmediateRunId?: number;
    /**
     * Internal: for background-agent completion/idle system notifications, the
     * agent's `turnHistory.length` when the notification was created. Used at
     * injection time to suppress the notification if a `read_agent` result has
     * already communicated that state to the reader (see
     * `TaskRegistry.isReadCommunicatedStateRedundant`). `notificationKind`
     * distinguishes idle vs terminal for the redundancy check.
     */
    agentNotificationTurnCount?: number;
    /**
     * Internal: for background-agent completion/idle system notifications, the
     * raw (unwrapped) notification message whose `notification` hook must be
     * fired at injection time rather than eagerly. Deferring it means a
     * redundant notification that is suppressed at injection fires neither the
     * hook nor any hook-injected context (see `fireDeferredNotificationHook`).
     */
    deferredNotificationHookMessage?: string;
}

declare type SendParams = SendRequest;

/** Parameters for sending a user message to the session */
declare interface SendRequest {
    /** The UI mode the agent was in when this message was sent. Defaults to the session's current mode. */
    agentMode?: SendAgentMode;
    /** Optional attachments (files, directories, selections, blobs, GitHub references) to include with the message */
    attachments?: Attachment_2[];
    /** If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. */
    billable?: boolean;
    /** If provided, this is shown in the timeline instead of `prompt` */
    displayPrompt?: string;
    /** How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. */
    mode?: SendMode;
    /** If true, adds the message to the front of the queue instead of the end */
    prepend?: boolean;
    /** The user message text */
    prompt: string;
    /** Custom HTTP headers to include in outbound model requests for this turn. Merged with session-level provider headers; per-turn headers augment and overwrite session-level headers with the same key. */
    requestHeaders?: Record<string, string>;
    /** If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange */
    requiredTool?: string;
    /** Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-<command-id>` for command-originated messages, `schedule-<numeric-id>` for scheduled prompts, or `agent-<agent-id>` for prompts sent by another agent. */
    source?: string;
    /** W3C Trace Context traceparent header for distributed tracing of this agent turn */
    traceparent?: string;
    /** W3C Trace Context tracestate header for distributed tracing */
    tracestate?: string;
    /** If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. */
    wait?: boolean;
}

/** Result of sending a user message */
declare interface SendResult {
    /** Unique identifier assigned to the message */
    messageId: string;
}

declare type SendSource = "user" | "system" | "autopilot" | `command-${string}` | `schedule-${number}` | `agent-${string}`;

/** Internal request for sending a system notification. */
declare interface SendSystemNotificationRequest {
    /** Optional structured notification kind. */
    kind?: unknown;
    /** Notification text to deliver to the model. */
    message: string;
    /** Internal delivery options, including passive policy. */
    options?: unknown;
}

/** Agents discovered across user, project, plugin, and remote sources. */
declare interface ServerAgentList {
    /** All discovered agents across all sources */
    agents: AgentInfo[];
}

declare interface ServerApi {
    account: {
        getAllUsers(): AccountAllUsers[] | Promise<AccountAllUsers[]>;
        getCurrentAuth(): AccountGetCurrentAuthResult | Promise<AccountGetCurrentAuthResult>;
        getQuota(params?: AccountGetQuotaRequest): AccountGetQuotaResult | Promise<AccountGetQuotaResult>;
        login(params: AccountLoginRequest): AccountLoginResult | Promise<AccountLoginResult>;
        logout(params: AccountLogoutRequest): AccountLogoutResult | Promise<AccountLogoutResult>;
    };
    agentRegistry: {
        spawn(params: AgentRegistrySpawnRequest): AgentRegistrySpawnResult | Promise<AgentRegistrySpawnResult>;
    };
    agents: {
        discover(params: AgentsDiscoverRequest): ServerAgentList | Promise<ServerAgentList>;
        getDiscoveryPaths(params: AgentsGetDiscoveryPathsRequest): AgentDiscoveryPathList | Promise<AgentDiscoveryPathList>;
    };
    commands: {
        list(): CommandList | Promise<CommandList>;
    };
    connect(params: ConnectRequest): ConnectResult | Promise<ConnectResult>;
    extensions: {
        disable(params: DiscoveredExtensionsDisableRequest): void | Promise<void>;
        discover(): DiscoveredExtensions | Promise<DiscoveredExtensions>;
        enable(params: DiscoveredExtensionsEnableRequest): void | Promise<void>;
    };
    instructions: {
        discover(params: InstructionsDiscoverRequest): ServerInstructionSourceList | Promise<ServerInstructionSourceList>;
        getDiscoveryPaths(params: InstructionsGetDiscoveryPathsRequest): InstructionDiscoveryPathList | Promise<InstructionDiscoveryPathList>;
    };
    managedSettings: {
        read(): ManagedSettingsReadResult | Promise<ManagedSettingsReadResult>;
    };
    mcp: {
        config: {
            add(params: McpConfigAddRequest): void | Promise<void>;
            disable(params: McpConfigDisableRequest): void | Promise<void>;
            enable(params: McpConfigEnableRequest): void | Promise<void>;
            list(): McpConfigList | Promise<McpConfigList>;
            reload(): void | Promise<void>;
            remove(params: McpConfigRemoveRequest): void | Promise<void>;
            update(params: McpConfigUpdateRequest): void | Promise<void>;
        };
        discover(params: McpDiscoverRequest): McpDiscoverResult | Promise<McpDiscoverResult>;
    };
    models: {
        getBuiltInCatalog(): BuiltInModelCatalog | Promise<BuiltInModelCatalog>;
        list(params?: ModelsListRequest): ModelList | Promise<ModelList>;
    };
    ping(params: PingRequest): PingResult | Promise<PingResult>;
    plugins: {
        disable(params: PluginsDisableRequest): void | Promise<void>;
        enable(params: PluginsEnableRequest): void | Promise<void>;
        install(params: PluginsInstallRequest): PluginInstallResult | Promise<PluginInstallResult>;
        list(): PluginListResult | Promise<PluginListResult>;
        marketplaces: {
            add(params: PluginsMarketplacesAddRequest): MarketplaceAddResult | Promise<MarketplaceAddResult>;
            browse(params: PluginsMarketplacesBrowseRequest): MarketplaceBrowseResult | Promise<MarketplaceBrowseResult>;
            list(): MarketplaceListResult | Promise<MarketplaceListResult>;
            refresh(params?: PluginsMarketplacesRefreshRequest): MarketplaceRefreshResult | Promise<MarketplaceRefreshResult>;
            remove(params: PluginsMarketplacesRemoveRequest): MarketplaceRemoveResult | Promise<MarketplaceRemoveResult>;
        };
        uninstall(params: PluginsUninstallRequest): void | Promise<void>;
        update(params: PluginsUpdateRequest): PluginUpdateResult | Promise<PluginUpdateResult>;
        updateAll(): PluginUpdateAllResult | Promise<PluginUpdateAllResult>;
    };
    registerExtensionLaunchProvider(): void | Promise<void>;
    runtime: {
        shutdown(): void | Promise<void>;
    };
    secrets: {
        addFilterValues(params: SecretsAddFilterValuesRequest): SecretsAddFilterValuesResult | Promise<SecretsAddFilterValuesResult>;
    };
    sessionFs: {
        setProvider(params: SessionFsSetProviderRequest): SessionFsSetProviderResult | Promise<SessionFsSetProviderResult>;
    };
    sessions: {
        bulkDelete(params: SessionsBulkDeleteRequest): SessionBulkDeleteResult | Promise<SessionBulkDeleteResult>;
        checkInUse(params: SessionsCheckInUseRequest): SessionsCheckInUseResult | Promise<SessionsCheckInUseResult>;
        close(params: SessionsCloseRequest): SessionsCloseResult | Promise<SessionsCloseResult>;
        configureSessionExtensions(params: ConfigureSessionExtensionsParams): void | Promise<void>;
        connect(params: ConnectRemoteSessionParams): RemoteSessionConnectionResult | Promise<RemoteSessionConnectionResult>;
        delete(params: SessionsDeleteRequest): void | Promise<void>;
        enrichMetadata(params: SessionsEnrichMetadataRequest): SessionEnrichMetadataResult | Promise<SessionEnrichMetadataResult>;
        findByPrefix(params: SessionsFindByPrefixRequest): SessionsFindByPrefixResult | Promise<SessionsFindByPrefixResult>;
        findByTaskId(params: SessionsFindByTaskIDRequest): SessionsFindByTaskIDResult | Promise<SessionsFindByTaskIDResult>;
        fork(params: SessionsForkRequest): SessionsForkResult | Promise<SessionsForkResult>;
        getBoardEntryCount(params: SessionsGetBoardEntryCountRequest): SessionsGetBoardEntryCountResult | Promise<SessionsGetBoardEntryCountResult>;
        getEventFilePath(params: SessionsGetEventFilePathRequest): SessionsGetEventFilePathResult | Promise<SessionsGetEventFilePathResult>;
        getLastForContext(params: SessionsGetLastForContextRequest): SessionsGetLastForContextResult | Promise<SessionsGetLastForContextResult>;
        getMetadata(params: SessionsGetMetadataRequest): SessionsGetMetadataResult | Promise<SessionsGetMetadataResult>;
        getPersistedRemoteSteerable(params: SessionsGetPersistedRemoteSteerableRequest): SessionsGetPersistedRemoteSteerableResult | Promise<SessionsGetPersistedRemoteSteerableResult>;
        getRemoteControlStatus(): RemoteControlStatusResult | Promise<RemoteControlStatusResult>;
        getSizes(): SessionSizes | Promise<SessionSizes>;
        list(params?: SessionsListRequest): SessionList | Promise<SessionList>;
        listNonEmptySessionIds(params: SessionsListNonEmptySessionIdsRequest): SessionsListNonEmptySessionIdsResult | Promise<SessionsListNonEmptySessionIdsResult>;
        loadDeferredRepoHooks(params: SessionsLoadDeferredRepoHooksRequest): SessionLoadDeferredRepoHooksResult | Promise<SessionLoadDeferredRepoHooksResult>;
        open(params: SessionOpenParams): SessionOpenResult | Promise<SessionOpenResult>;
        pruneOld(params: SessionsPruneOldRequest): SessionPruneResult | Promise<SessionPruneResult>;
        registerExtensionToolsOnSession(params: RegisterExtensionToolsParams): RegisterExtensionToolsResult | Promise<RegisterExtensionToolsResult>;
        releaseLock(params: SessionsReleaseLockRequest): SessionsReleaseLockResult | Promise<SessionsReleaseLockResult>;
        reloadPluginHooks(params: SessionsReloadPluginHooksRequest): SessionsReloadPluginHooksResult | Promise<SessionsReloadPluginHooksResult>;
        save(params: SessionsSaveRequest): SessionsSaveResult | Promise<SessionsSaveResult>;
        setAdditionalPlugins(params: SessionsSetAdditionalPluginsRequest): SessionsSetAdditionalPluginsResult | Promise<SessionsSetAdditionalPluginsResult>;
        setRemoteControlSteering(params: SessionsSetRemoteControlSteeringRequest): RemoteControlStatusResult | Promise<RemoteControlStatusResult>;
        startRemoteControl(params: SessionsStartRemoteControlRequest): RemoteControlStatusResult | Promise<RemoteControlStatusResult>;
        stopRemoteControl(params?: SessionsStopRemoteControlRequest): RemoteControlStopResult | Promise<RemoteControlStopResult>;
        transferRemoteControl(params: SessionsTransferRemoteControlRequest): RemoteControlTransferResult | Promise<RemoteControlTransferResult>;
    };
    skills: {
        config: {
            setDisabledSkills(params: SkillsConfigSetDisabledSkillsRequest): void | Promise<void>;
        };
        discover(params: SkillsDiscoverRequest): ServerSkillList | Promise<ServerSkillList>;
        getDiscoveryPaths(params: SkillsGetDiscoveryPathsRequest): SkillDiscoveryPathList | Promise<SkillDiscoveryPathList>;
    };
    tools: {
        list(params: ToolsListRequest): ToolList | Promise<ToolList>;
    };
    user: {
        settings: {
            get(): UserSettingsGetResult | Promise<UserSettingsGetResult>;
            reload(): void | Promise<void>;
            set(params: UserSettingsSetRequest): UserSettingsSetResult | Promise<UserSettingsSetResult>;
        };
    };
}

declare type ServerConnectionStatus = "connected" | "failed" | "needs-auth" | "pending" | "disabled" | "not_configured";

declare interface ServerFailureInfo {
    error: Error;
    timestamp: number;
}

/** Instruction sources discovered across user, repository, and plugin sources. */
declare interface ServerInstructionSourceList {
    /** All discovered instruction sources */
    sources: InstructionSource[];
}

/** Server-side skill metadata, including name, description, source, enabled/invocable state, path, project path, and argument hint. */
declare interface ServerSkill {
    /** Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field */
    argumentHint?: string;
    /** Canonical slash command name used to invoke the skill, without the leading '/' */
    commandName?: string;
    /** Description of what the skill does */
    description: string;
    /** Whether the skill is currently enabled (based on global config) */
    enabled: boolean;
    /** Unique identifier for the skill */
    name: string;
    /** Absolute path to the skill file */
    path?: string;
    /** The project path this skill belongs to (only for project/inherited skills) */
    projectPath?: string;
    /** Source location type (e.g., project, personal-copilot, plugin, builtin) */
    source: SkillSource_2;
    /** Whether the skill can be invoked by the user as a slash command */
    userInvocable: boolean;
}

/** Skills discovered across global and project sources. */
declare interface ServerSkillList {
    /** Messages for skills that failed to load (e.g. malformed SKILL.md). Empty when host skills are excluded so host-local paths are not disclosed to multitenant callers. */
    errors?: string[];
    /** All discovered skills across all sources */
    skills: ServerSkill[];
}

/**
 * Interface for reporting server connection status changes.
 * Implement this interface to receive notifications when servers start connecting,
 * connect successfully, or fail to connect.
 */
declare interface ServerStatusCallback {
    onServerStatus(serverName: string, event: ServerStatusEvent): void;
}

/**
 * Server status event types for the status callback.
 */
declare type ServerStatusEvent = {
    status: "starting";
} | {
    status: "connected";
} | {
    status: "failed";
    error: Error;
    stderrDetail?: string;
} | {
    status: "needs-auth";
};

declare type ServerToolData = CopilotChatCompletionMessageParam["serverTools"];

/**
 * Neutral, provider-agnostic representation of server-side ("hosted") tool use
 * that must be round-tripped verbatim on subsequent turns.
 */
declare type ServerToolData_2 = {
    provider: "openai-responses";
    items?: unknown[];
    functionCallNamespaces?: Record<string, string>;
} | {
    provider: "anthropic-messages";
    rawContentBlocks: unknown[];
    advisorModel?: string;
};

export declare type ServiceLogEntry = {
    timestamp: number;
    message: string;
};

/**
 * A single line in a service's server log.
 */
declare type ServiceLogEntry_2 = {
    /** When this line was recorded (ms since epoch). */
    timestamp: number;
    /** Human-readable milestone or forwarded server message. */
    message: string;
};

/**
 * A single line in a service's append-only server log. Both the UI
 * (a `/tasks`-style log drill-in) and the agent (via `read_agent`) read from
 * this same stream. The log is a live tail of the server's whole lifetime, not
 * just its initialization.
 */
declare interface ServiceLogLine {
    /** When this line was recorded. */
    timestamp: number;
    /** Human-readable log message (a milestone or a forwarded server message). */
    message: string;
}

export declare type ServiceTask = {
    type: "service";
    id: string;
    serviceKind: string;
    serviceId: string;
    description: string;
    status: BackgroundTaskStatus;
    ready: boolean;
    phase?: string;
    percentage?: number;
    startedAt: number;
    completedAt?: number;
    error?: string;
    log: ServiceLogEntry[];
};

/**
 * A long-lived background service (e.g. an LSP server) whose initialization the
 * user and agent want to observe. Unlike {@link BackgroundTask}, a service is
 * not a discrete unit of work that completes — it starts, becomes {@link ready},
 * and then stays alive for the rest of the session. Intentionally kept out of
 * the `BackgroundTask` union so it does not appear in `/tasks` and is not
 * counted as an in-flight task; it is surfaced through the dedicated `/lsp`
 * panel instead.
 */
declare type ServiceTask_2 = {
    type: "service";
    id: string;
    /** Broad category, e.g. `"lsp"`. */
    serviceKind: string;
    /** Stable identifier of the service instance, e.g. the LSP server id. */
    serviceId: string;
    description: string;
    status: BackgroundTaskStatus_2;
    /** Whether initialization has finished and the service can serve requests. */
    ready: boolean;
    /** Current phase, e.g. "extracting MSBuild config", "indexing symbols", "ready". */
    phase?: string;
    /** Initialization progress 0–100 when reported. */
    percentage?: number;
    startedAt: number;
    completedAt?: number;
    /** Error message when initialization failed. */
    error?: string;
    /** Append-only server log. */
    log: ServiceLogEntry_2[];
};

/** Narrowed entry type for service tasks. */
declare type ServiceTaskEntry = TaskEntryBase & ServiceTaskFields;

/**
 * Fields specific to long-lived background services (e.g. LSP servers) whose
 * initialization the user and agent want to observe.
 *
 * Unlike agents and shells, a service is not a discrete unit of work that
 * "completes": it starts, becomes {@link ready}, and then stays alive serving
 * requests for the rest of the session. The lifecycle is mapped onto the shared
 * {@link TaskStatus} without introducing a new status value:
 * - `running`   — starting / initializing / indexing (see `phase`/`percentage`)
 * - `idle`      — initialized and ready to serve requests (`ready === true`)
 * - `failed`    — initialization failed (see `error`)
 * - `completed` — the underlying service has shut down
 */
declare interface ServiceTaskFields {
    type: "service";
    /** Broad category of the service, e.g. `"lsp"`. */
    serviceKind: string;
    /** Stable identifier of the service instance, e.g. the LSP server id. */
    serviceId: string;
    /**
     * Cache key of the underlying instance when one exists, e.g. the LSP
     * client's `${serverId}-${projectRoot}` key. Lets distinct instances that
     * share a {@link serviceId} (the same language server against two project
     * roots) be told apart so their ids/logs don't merge.
     */
    clientKey?: string;
    /** Human-readable current phase, e.g. "extracting MSBuild config", "indexing symbols". */
    phase?: string;
    /** Initialization progress 0–100 when the service reports it. */
    percentage?: number;
    /** Whether the service has finished initialization and is ready to serve requests. */
    ready: boolean;
    /** Error message when initialization failed. */
    error?: string;
    /**
     * Bounded tail of the server log (lifecycle milestones + forwarded server
     * messages). Capped by the native registry: once full, the oldest
     * lines are evicted from the front and {@link droppedLogCount} is bumped so
     * read cursors remain stable in absolute terms.
     */
    log: ServiceLogLine[];
    /**
     * Number of log lines evicted from the front of {@link log} over the life of
     * the service. Equals the absolute index of `log[0]`, so the absolute index
     * of `log[i]` is `droppedLogCount + i`. Read cursors ({@link lastReadLogIndex}
     * and `read_agent`'s `since_turn`) are absolute and survive eviction.
     */
    droppedLogCount: number;
    /** Last absolute log index returned by read_agent's default incremental cursor. */
    lastReadLogIndex?: number;
}

/**
 * Abstract base class for sessions.
 *
 * The runtime conformance of this class to {@link sessionApiSchema} is
 * verified at test time by `test/core/sharedApi/sessionSchemaImplValidation.test.ts`,
 * which walks top-level entries of the Rust-emitted dispatch table and
 * asserts that each resolved impl member exists on the `LocalSession` and
 * `RemoteSession` prototypes. Other concrete descendants (for example
 * `LocalRpcSession` and `RelaySession`) are not inspected by that test.
 * Compile-time enforcement via
 * `implements ApiSchemaToImplementation<typeof sessionApiSchema>` was removed
 * because the inferred type for the schema literal exceeds TypeScript's
 * TS7056 declaration-emit limit (the schema has 30+ namespaces of deeply
 * nested Zod types). Per-namespace conformance is still enforced statically
 * via the typed factory return on each `readonly X = sessionXApi(this)`
 * assignment below.
 */
export declare abstract class Session<SM extends SessionMetadata = SessionMetadata> {
    private readonly backgroundWorkPredicates;
    /**
     * Discriminates local vs remote sessions without requiring `instanceof`
     * checks against the runtime classes. CLI and other consumers should
     * branch on this field rather than importing `LocalSession` /
     * `RemoteSession` (which are runtime internals).
     */
    abstract readonly isRemote: boolean;
    /**
     * Whether a semantically remote session may use native shared API handlers.
     * Mission Control sessions fall through to their remote host by default.
     */
    protected get allowRemoteNativeHandlers(): boolean;
    /** Whether `name.set()` persists a rename for this session type. */
    get supportsRename(): boolean;
    readonly gitHubAuth: SessionGitHubAuthApi;
    private readonly canvasProviderHost;
    readonly canvas: SessionCanvasRuntimeApi;
    readonly factory: SessionFactoryApi;
    readonly model: SessionModelApi;
    readonly mode: SessionModeApi;
    readonly name: SessionNameApi;
    readonly plan: SessionPlanApi;
    readonly workspaces: SessionWorkspaceApi;
    readonly fleet: SessionFleetApi;
    readonly agent: SessionAgentApi;
    readonly skills: SessionSkillsApi;
    readonly mcp: SessionMcpApi & {
        oauth: SessionMcpOauthApi;
        headers: SessionMcpHeadersApi;
        apps: SessionMcpAppsApi;
        resources: SessionMcpResourcesApi;
    };
    readonly plugins: SessionPluginsApi;
    readonly options: SessionOptionsApi;
    readonly lsp: SessionLspApi;
    readonly extensions: SessionExtensionsApi;
    readonly tasks: SessionTasksApi;
    readonly tools: SessionToolsApi;
    readonly commands: SessionCommandsApi;
    readonly completions: SessionCompletionsApi;
    readonly debug: SessionDebugApi;
    readonly telemetry: SessionTelemetryApi;
    private readonly directAutoModeSwitchHandles;
    readonly ui: SessionUiApi;
    readonly permissions: SessionPermissionsApi;
    readonly log: SessionLogApi["log"];
    readonly metadata: SessionMetadataApi;
    readonly history: SessionHistoryApi;
    readonly contentExclusion: SessionContentExclusionApi;
    readonly instructions: SessionInstructionsApi;
    readonly limitPrediction: SessionLimitPredictionApi;
    readonly eventLog: SessionEventsApi;
    readonly provider: SessionProviderApi;
    readonly queue: SessionQueueApi;
    readonly settings: SessionSettingsApi;
    readonly usage: SessionUsageApi;
    readonly visibility: SessionVisibilityApi;
    protected disposeCanvas(): void;
    private remoteDelegate;
    readonly remote: SessionRemoteApi;
    /**
     * Internal: installs a remote-steering delegate on an existing session.
     * Used by SDK server paths that obtain a session via construction first
     * and need to wire the delegate after the fact (e.g., the preloaded
     * `--resume=<id>` flow). Construction-time injection via
     * `SessionOptions.remoteDelegate` is preferred for fresh sessions.
     */
    setRemoteDelegate(delegate: SessionRemoteDelegate): void;
    /**
     * Lazily resolves the Mission Control session ID for this session, when the
     * session is connected to Mission Control (remote control). Returns
     * undefined for purely local sessions. Installed by the session manager
     * that owns the remote-control exporter; read each time the system prompt
     * is rebuilt so a late-arriving (asynchronously created) Mission Control
     * session ID is picked up on the next turn. Used to emit the
     * `Copilot-Session` git trailer.
     */
    private missionControlSessionIdProvider?;
    /**
     * Installs the {@link missionControlSessionIdProvider}. Called by the
     * session manager once the session is registered so the prompt builder can
     * read the current Mission Control session ID.
     */
    setMissionControlSessionIdProvider(provider: () => string | undefined): void;
    protected get missionControlSessionId(): string | undefined;
    /**
     * Best-effort waiter that lets the Mission Control session ID resolve before
     * the turn's system prompt is built. In deferred remote-export mode the MC
     * session is created lazily on the first `user.message`, which races (and
     * loses) against first-turn prompt construction, so the `Copilot-Session`
     * trailer would be missing on first-turn commits. Installed by the session
     * manager alongside {@link missionControlSessionIdProvider}.
     */
    private missionControlSessionIdReadyWaiter?;
    /** Installs the {@link missionControlSessionIdReadyWaiter}. */
    setMissionControlSessionIdReadyWaiter(waiter: (timeoutMs: number) => Promise<void>): void;
    /**
     * Await (up to `timeoutMs`) for the Mission Control session ID to become
     * available before building the system prompt. No-op when no waiter is
     * installed or the ID is already resolvable.
     */
    protected ensureMissionControlSessionIdReady(timeoutMs: number): Promise<void>;
    readonly schedule: SessionScheduleApi;
    /**
     * Per-session schedule registry. Owns timer state for `/every` and any
     * future scheduling primitives. Always created so the schema's
     * `session.schedule.{list,add,stop}` methods work without a separate gate;
     * the `manage_schedule` tool exposure is gated by
     * {@link SessionOptions.manageScheduleEnabled} instead.
     *
     * Constructor-body assigned (not field-initialized) so the registry's
     * shutdown subscription wires onto a fully-initialized event-handler map.
     */
    private shellNotifier;
    private readonly userRequestedShellAbortControllers;
    private installedPluginsRef;
    private mcpServersRef;
    private executeUserRequestedShellForApi;
    private watchUserRequestedShellCancellation;
    private cancelUserRequestedShellForApi;
    readonly shell: ShellApi;
    /**
     * Internal: installs a shell-output notifier on an existing session.
     * Used by SDK server paths that obtain a session via construction first
     * and need to wire the notifier after the fact (e.g., the in-memory
     * SESSION_RESUME path for active/foreground/preloaded sessions, where
     * the resumed session was constructed before the resuming connection's
     * SHELL_OUTPUT/SHELL_EXIT notification sender existed).
     * Construction-time injection via {@link SessionOptions.shellNotifier} is
     * preferred for fresh sessions.
     */
    setShellNotifier(notifier: ShellNotificationSender): void;
    /** Optional permission service for centralized permission handling.
     *  SDK sessions lazily initialize a session-owned service via ensurePermissionService().
     *  Frontends configure it via configurePermissionService() and observe its
     *  prompts via the `permission.requested` session event. */
    protected _permissionService: PermissionService | undefined;
    protected _permissionServiceInitPromise: Promise<PermissionService> | undefined;
    private permissionServicePathManager?;
    private permissionServiceUrlManager?;
    /**
     * Whether permission-request events are currently bridged to consumers — i.e.
     * the latest value passed to {@link SessionPermissionsApi.setRequired}. Exposed
     * (read-only) so callers that temporarily toggle this flag can restore the prior
     * value instead of clobbering it. In particular, the SDK server's
     * extension-permission-access gate uses this to avoid disabling permission events
     * that an external authority (e.g. the CLI foreground) enabled directly when an
     * extension load is cancelled — see {@link SDKServer} and
     * `extension-permission-access.test.ts`.
     */
    get permissionEventsEnabled(): boolean;
    /** Configure how a lazily created session-owned permission service should behave. */
    configurePermissionService(options: {
        approveAllToolPermissionRequests?: boolean;
        approveAllReadPermissionRequests?: boolean;
        autoApprovalPermissionRequests?: boolean;
        rules?: {
            approved: ReadonlyArray<Rule>;
            denied: ReadonlyArray<Rule>;
        };
        pathManager?: PathManager;
        urlManager?: UrlManager;
    }): void;
    private configurePermissionsFromApi;
    /**
     * Best-effort: create and allow the installed-plugins directory so plugin
     * file reads don't trigger a directory-access permission prompt.
     *
     * Guard against symlink escape: only add if the resolved path is exactly
     * `<resolved copilot home>/installed-plugins`.
     */
    private autoAllowInstalledPluginsDir;
    getPathManager(): Promise<PathManager>;
    /**
     * Apply enterprise managed settings to this session.
     *
     * Enforcement lives in the permission engine: the verbatim managed
     * `permissions` slice is forwarded to the permission service, which
     * interprets it as a ceiling that caps escalation (approve-all, unrestricted
     * paths/URLs) at decision time. The stored escalation intent is left
     * untouched, so lifting the policy restores it automatically — no revoke
     * pass is needed. `bypassPermissionsDisabledByPolicy` is a thin UX mirror of
     * the engine's verdict used by the per-API escalation gate's thrown errors.
     *
     * @param options.failClosed When `true`, force bypass-permissions disabled
     * even if `settings` does not request it (policy undetermined). Expressed by
     * forwarding a synthetic locked slice so the engine still does the
     * interpreting.
     */
    applyManagedSettings(settings: ManagedSettings | undefined, options?: {
        failClosed?: boolean;
        permissions?: ManagedPermissionsSlice;
    }): void;
    getManagedSettings(): ManagedSettings | undefined;
    /**
     * The effective enterprise-managed `sandbox` floor in force for this
     * session, resolved from whichever channel delivered it.
     *
     * Two channels exist and only one is ever populated: SDK hosts that opt into
     * {@link SessionOptions.enableManagedSettings} get the applied snapshot
     * {@link getManagedSettings} reads, while the CLI fetches managed settings
     * through its own app-level flow and pushes the raw server + device layers
     * in via {@link applyManagedMcpPolicyLayers} without ever populating that
     * snapshot. Reading only the snapshot would therefore miss the floor the CLI
     * actually enforces (through `SessionOptions.sandboxConfig`).
     *
     * Awaits both channels' resolution first, mirroring
     * `resolveDefaultMcpPolicyOptions`: managed settings arrive asynchronously,
     * so answering before they land would report "no floor" for a policy that
     * is about to be enforced. Both waits are already released on teardown, so
     * neither can hang the caller.
     *
     * This reports what policy *asks for*, which is not the same as what the
     * session *enforces* — see {@link isSandboxEnabled}. Applying managed
     * settings never rewrites `sandboxConfig`, so the two can disagree.
     */
    getEffectiveManagedSandbox(): Promise<ManagedSettings["sandbox"] | undefined>;
    /**
     * Whether OS-level command sandboxing is actually in force for this session:
     * the resolved `sandboxConfig` that gates shell spawns, after any
     * enterprise-managed floor the host applied when it built the session
     * options (see `resolveFlooredSandboxConfig`). `undefined` when the host
     * configured no sandbox for this session.
     *
     * Distinct from {@link getEffectiveManagedSandbox}, which reports the policy
     * rather than its enforcement. {@link applyManagedSettings} writes the
     * managed-settings scalar and permission state but never updates
     * `sandboxConfig`, so a host that receives a managed floor without folding
     * it into the session options has policy that asks for a sandbox and a
     * session that runs without one. `/sandbox status` reports this value so it
     * can never claim commands are isolated when they are not.
     */
    isSandboxEnabled(): boolean | undefined;
    /**
     * The session's resolved sandbox config, serialized — the same JSON the
     * shell path hands the effective-policy builder, so `/sandbox policy` can
     * resolve it into the grant/denial sets the OS sandbox actually enforces.
     * `undefined` when the host configured no sandbox for this session.
     *
     * Returned as raw JSON rather than a parsed object because every consumer
     * passes it straight back across the FFI boundary.
     */
    getSandboxConfigJson(): string | undefined;
    beginManagedSettingsResolution(options?: {
        permissions?: boolean;
    }): void;
    applyManagedMcpPolicyLayers(serverResponse: ManagedSettings | undefined, deviceResponse: ManagedSettings | undefined, serverFetchFailed: boolean, deviceLoadFailed: boolean, deviceSandboxFloor?: ManagedSettings["sandbox"]): void;
    expectManagedMcpPolicy(): void;
    expectManagedPermissionPolicy(): void;
    protected updateManagedMcpPolicyLayers(serverResponse: ManagedSettings | undefined, deviceResponse: ManagedSettings | undefined, serverFetchFailed: boolean, deviceLoadFailed: boolean, deviceSandboxFloor?: ManagedSettings["sandbox"]): void;
    protected beginInterimManagedMcpFailClosed(): void;
    private pushComposedManagedMcpPolicyToHosts;
    protected composeManagedMcpPolicy(): ManagedMcpPolicy;
    protected composedManagedMcpHostOptions(): {
        managedAllowedMcpServerLists?: ManagedMcpServerMatcher[][];
        managedDeniedMcpServers?: ManagedMcpServerMatcher[];
    };
    protected trustedDefaultServerNames(mcpServers: Record<string, MCPServerConfig> | undefined): string[];
    isBypassPermissionsDisabledByPolicy(): boolean;
    /**
     * Await the in-flight self-fetch of managed settings, if any. Used by the
     * session manager to ensure enterprise policy is applied before the first turn.
     */
    ensureManagedSettingsApplied(): Promise<void>;
    private ingestAndApplyManagedSettings;
    private applyRetainedManagedSettings;
    private getManagedSettingsLayers;
    private emitManagedSettingsResolved;
    /**
     * Replace the non-persisted SDK client layer at a create/resume boundary.
     * Enforcement applies immediately, but the startup snapshot is emitted only
     * after the SDK server installs forwarding for the requesting connection.
     *
     * @internal
     */
    replaceClientManagedSettingsForStartup(settings: ClientManagedSettings | undefined): void;
    /** @internal */
    beginClientManagedSettingsResumeTransaction(settings: ClientManagedSettings | undefined): void;
    /** @internal */
    commitClientManagedSettingsResumeTransaction(): boolean;
    /** @internal */
    rollbackClientManagedSettingsResumeTransaction(): void;
    /** @internal */
    getManagedSettingsResolvedSnapshotData(): Extract<SessionEvent, {
        type: "session.managed_settings_resolved";
    }>["data"];
    /** @internal */
    createManagedSettingsResolvedSnapshotEvent(): Extract<SessionEvent, {
        type: "session.managed_settings_resolved";
    }>;
    /** @internal */
    emitManagedSettingsResolvedSnapshot(): void;
    /**
     * (Re)start the hourly managed-settings refresh timer for this session.
     *
     * Long-running sessions periodically re-fetch and re-apply enterprise policy
     * so changes made after the session started (e.g. an org enabling
     * bypass-disable) take effect without a restart. Idempotent: any existing
     * timer is cleared first, so an account switch that re-triggers the fetch
     * simply restarts the cadence. The timer is `unref`'d so it never keeps the
     * process alive on its own.
     */
    private startManagedSettingsRefreshTimer;
    /** Stop the hourly managed-settings refresh timer, if running. */
    protected clearManagedSettingsRefreshTimer(): void;
    /**
     * Periodic refresh tick: re-fetch and re-apply managed settings for the
     * current account. Unlike the bootstrap trigger it does NOT pre-emptively
     * fail closed for the in-flight window — policy is already applied, so a
     * transient revoke of an approved escalation every hour would be wrong. The
     * ingest still fails closed on an actual fetch failure via
     * {@link ingestAndApplyManagedSettings}.
     *
     * Bypasses the persistent server-policy cache read (`bypassCacheRead`) so the
     * hourly tick always re-fetches from the network and refreshes the cache,
     * guaranteeing policy changes propagate even when overlapping sessions keep
     * the cache warm.
     */
    private refreshManagedSettings;
    /**
     * Emit the SDK-consumable `session.managed_settings_enforced` event when a
     * user/host attempt to turn on a bypass-permissions escalation is refused or
     * capped by enterprise policy, so clients can explain *why* the action was
     * governed. Called only from the escalation gates (never from silent policy
     * application), so it always corresponds to a concrete blocked attempt.
     *
     * Emitted ephemerally, mirroring `session.managed_settings_resolved`: the
     * managed-settings surface is a live snapshot, and firing on the bootstrap
     * apply path could precede `session.start`.
     */
    reportBypassPermissionsEnforced(escalation: ManagedSettingsEnforcedEscalation): void;
    setAllowAllPermissions(enabled: boolean, source?: PermissionsSetAllowAllSource): Promise<EscalationApplyResult>;
    /**
     * Enable or disable advisory LLM auto-approval ("auto" allow-all mode).
     * Unlike `setAllowAllPermissions`, this keeps normal prompt paths active and
     * attaches an LLM safety recommendation to each request instead of blanket
     * approving. Enabling is gated behind the experimental `AUTO_APPROVAL`
     * feature flag; disabling is always allowed.
     */
    setAutoApprovalPermissions(enabled: boolean, model?: string): Promise<EscalationApplyResult>;
    /**
     * Selects the default model for the auto-approval safety judge. CAPI sessions
     * pin the judge to {@link DEFAULT_CAPI_AUTO_APPROVAL_JUDGE_MODEL} for a
     * consistent, capable reviewer regardless of the user's main model. BYOK
     * sessions have no CAPI catalog to draw from, so this returns `undefined` and
     * the runtime falls back to the session's active model. BYOK is detected with
     * the same predicate the rest of the class uses, so registry-based selections
     * (which leave `byokProvider` unset) are covered too.
     */
    private resolveAutoApprovalJudgeModel;
    /**
     * Re-apply the persisted allow-all posture ("on" = bypass all prompts, or
     * "auto" = advisory LLM auto-approval) when resuming a session, so a resumed
     * session keeps the permission mode the user established instead of silently
     * dropping back to prompting (and, in autopilot, re-showing the confirmation
     * dialog). The projection rebuild in `fromEvents` resets session-scoped
     * permission state to the restricted default; this restores it.
     *
     * Applied silently — no `session.permissions_changed` emit — mirroring the
     * mode reseed in `fromEvents`. The restored engine state is read back by every
     * client via `getAllowAll()` / `isAllowAllPermissionsActive()`, so interactive,
     * `-p`, and server/acp resume paths all converge without client-specific wiring.
     *
     * Guarded so an enterprise `disableBypassPermissionsMode` policy is honored,
     * and "auto" is only restored when the `AUTO_APPROVAL` feature flag that could
     * have established it is still enabled.
     */
    private restoreAllowAllPermissionsForResume;
    /**
     * Emit `session.permissions_changed` only if the aggregate `isAllowAllPermissionsActive()`
     * value transitioned. No-op when the call did not change effective state (e.g. re-enabling
     * an already-enabled allow-all). Mirrors the transition-only emit pattern of the
     * `currentMode` setter above.
     *
     * Caveat: only `setAllowAllPermissions` funnels through this helper today. Other callers
     * that mutate `approveAllToolPermissionRequests` directly (e.g. `configurePermissionService`,
     * `sessionApi.setApproveAll`) bypass the event. A future pass will route all
     * allow-all writers through canonical setters that emit on transition.
     */
    private emitPermissionsChangedIfTransitioned;
    getAllowAllPermissionStatus(): {
        runtimeOverride: boolean;
        baseline: {
            tools: boolean;
            paths: boolean;
            urls: boolean;
        };
    };
    /**
     * True when allow-all is fully active: either a runtime `/allow-all on`
     * override is installed, or the session baseline unrestricts all three
     * dimensions (tools, paths, and URLs). A partial baseline flag such as
     * `--allow-all-tools` (tools only) is deliberately NOT reported as active,
     * since paths and URLs remain restricted; callers that want the tool-only
     * signal should read `getAllowAllPermissionStatus().baseline.tools`.
     */
    isAllowAllPermissionsActive(): boolean;
    isAutoApprovalPermissionsActive(): boolean;
    getAllowAllMode(): "off" | "on" | "auto";
    /** Called when a permission prompt is actually shown. Overridden by LocalSession to fire hooks. */
    notifyPermissionPrompt(_message: string): void;
    /**
     * Resolve a creation-time additional directory against this session's working
     * directory using the session filesystem's path convention. Absolute paths
     * pass through unchanged; relative paths are anchored to the working
     * directory rather than the launcher's `process.cwd()`.
     */
    private resolveAdditionalDirectory;
    /**
     * Eagerly apply creation-time additional directories at session bootstrap so
     * the file-access grants and the model-facing directory list are in place
     * before the first turn (rather than lazily on the first tool use). No-op
     * when none were supplied; otherwise ensures the native permission service is
     * initialized and adds each directory to its path manager.
     */
    applyInitialAdditionalDirectories(): Promise<void>;
    /** Ensure the SDK-facing permission service exists for this session. */
    ensurePermissionService(): Promise<PermissionService>;
    /** Get the permission service if one has been configured for this session. */
    getPermissionService(): PermissionService | undefined;
    /**
     * Optional callback to flush pending I/O (e.g., buffered events from SessionWriter)
     * before destructive operations like truncation. Set by the session manager.
     */
    private _flushCallback?;
    /** Register a callback to flush pending writes. Called by session manager during setup. */
    setFlushCallback(cb: (options?: {
        force?: boolean;
    }) => Promise<void>): void;
    /**
     * Optional callback registered by {@link LocalSessionManager} that re-loads user, plugin,
     * and (optionally) repo hooks for this session and applies them via `updateOptions`. Used
     * by {@link sessionApi}.reload so SDK-driven plugin install/uninstall reflects
     * immediately in the active session's hook set. Remote sessions and tests can leave it
     * unset — `reloadPluginHooks` becomes a no-op.
     */
    private _pluginHookReloader?;
    /**
     * Register the plugin-hook reloader used by `session.plugins.reload`. Called by the
     * session manager (typically {@link LocalSessionManager}) once after session creation /
     * resume so subsequent SDK reload calls can refresh hooks without round-tripping through
     * the manager-level `sessions.reloadPluginHooks` RPC.
     */
    setPluginHookReloader(cb: (deferRepoHooks?: boolean) => Promise<void>): void;
    /**
     * Re-load user, plugin, and (optionally) repo hooks for this session and apply them.
     * No-op when no reloader has been registered (e.g. remote sessions or test doubles).
     */
    reloadPluginHooks(deferRepoHooks?: boolean): Promise<void>;
    private reloadPlugins;
    /** Flush any pending writes to disk. No-op if no flush callback is registered. */
    flushPendingWrites(options?: {
        force?: boolean;
    }): Promise<void>;
    /** The current agent mode for this session. Emits session.mode_changed on change. */
    get currentMode(): SessionMode;
    set currentMode(mode: SessionMode);
    /**
     * Change the session mode. Subclasses override this to propagate the
     * change to a remote peer (in addition to applying it locally). Callers
     * should prefer this over assigning to `currentMode` directly when the
     * change originates from a user/SDK action that should also reach a
     * connected remote peer.
     */
    changeMode(mode: SessionMode): void;
    /**
     * Whether the plan-mode write gate should hard-block mutating tool calls for
     * this session. Active when the session is itself in plan mode, or when it is
     * a subagent that inherited the gate from a plan-mode parent. Consumed by the
     * the native model loop.
     */
    isPlanModeWriteGateActive(): boolean;
    readonly sessionId: string;
    protected readonly nativeSessionId: string;
    /**
     * The session ID of a "parent" interactive session that spawned this
     * session (e.g., a detached headless rem-agent run launched on
     * shutdown). When set, telemetry from this session is reported under
     * the parent's session_id so all activity rolls up as part of the
     * same user-perceived session, while persistence still uses this
     * session's own sessionId.
     */
    get detachedFromSpawningParentSessionId(): string | undefined;
    get startTime(): Date;
    get modifiedTime(): Date;
    /** Native session identity used by session-owned permission and content-exclusion proxies. */
    get permissionSessionId(): string;
    get summary(): string | undefined;
    /** The user-provided session name (set via `--name`), available immediately without waiting for workspace init. */
    get initialName(): string | undefined;
    /** Get the resolved feature flags for this session */
    get resolvedFeatureFlags(): FeatureFlags | undefined;
    get featureFlags(): FeatureFlags | undefined;
    set featureFlags(value: FeatureFlags | undefined);
    get authInfo(): AuthInfo | undefined;
    set authInfo(value: AuthInfo | undefined);
    get byokProvider(): ProviderConfig | undefined;
    set byokProvider(value: ProviderConfig | undefined);
    get toolSearchOverride(): SessionToolSearchOptions | undefined;
    set toolSearchOverride(value: SessionToolSearchOptions | undefined);
    /**
     * The SDK-supplied per-session provider-native web-search option. Unlike
     * {@link toolSearchOverride}, this value is COPIED INTO CHILD SESSIONS at
     * construction whenever the child's own options are silent (see
     * `createSubagentSession`), so a consumer's opt-out reaches every subagent.
     */
    get webSearchOverride(): SessionWebSearchOptions | undefined;
    set webSearchOverride(value: SessionWebSearchOptions | undefined);
    get eventsLogIncludesSubagents(): boolean;
    set eventsLogIncludesSubagents(value: boolean);
    protected get genericClientDiscoveredToolNames(): Set<string>;
    get workingDir(): string;
    get resolvedFeatureFlagService(): IFeatureFlagService;
    /**
     * True when the feature-flag service was supplied by the session creator
     * and is not owned by the session. Externally managed services own their
     * own assignment lifecycle, so SDK-injected `expAssignments` cannot be
     * applied to them via {@link applyInjectedExpAssignments}.
     */
    get isFeatureFlagServiceExternallyManaged(): boolean;
    /**
     * Applies SDK-injected assignments when this session owns its feature
     * flag service. Returns `false` when the owned service is unavailable
     * (externally managed or disposed); use
     * {@link isFeatureFlagServiceExternallyManaged} to distinguish.
     */
    applyInjectedExpAssignments(assignments: CopilotExpAssignmentResponse): boolean;
    /** Whether experimental mode is enabled for this session */
    get isExperimentalMode(): boolean;
    set isExperimentalMode(value: boolean);
    /** Whether host git operations are enabled for this session */
    get hostGitOperationsEnabled(): boolean;
    /** Find the git root, returning a not-found result when host git operations are disabled. */
    protected findGitRoot(): Promise<GitRootResult>;
    /** Whether this session was already in use by another client at start/resume time */
    get alreadyInUse(): boolean;
    set alreadyInUse(alreadyInUse: boolean);
    /** Whether the main agent turn is currently active. */
    isAgentTurnActive(): boolean;
    /**
     * Check if the session is currently processing queued items.
     * Returns true when native queue processing is actively running (e.g., during
     * an autopilot continuation that was started as fire-and-forget).
     */
    isProcessingMessages(): boolean;
    /**
     * Whether a resume-pending continuation has been queued but has not started
     * running yet. The flag is set when the wake is enqueued and cleared as the
     * continuation turn begins, so it covers the window where the native queue
     * holds the continuation but `isProcessing`/turn-active are both still
     * false. Cold resumes rebuild the session from events with the flag reset,
     * so it only ever reports work queued in this runtime.
     */
    isResumePendingWakeQueued(): boolean;
    /**
     * Whether a `session.send` has been dispatched to the native layer but has
     * not yet returned. Rust does not establish the processing flag until it
     * takes the send, so this covers the window where a turn is starting but
     * no native liveness scalar reports it yet. Mirrors the
     * `isProcessing || pendingNativeSendCount > 0` idiom the idle-drain path
     * already uses. Sessions with no native send path report false.
     */
    get hasPendingNativeSend(): boolean;
    /**
     * True when this session is acting as a subagent of another session.
     *
     * Subagents are an implementation detail: their lifecycle is observed via
     * `subagent.started` / `subagent.completed` / `subagent.failed` on the
     * parent, not via session-level events or hooks. Callers should use this
     * predicate to skip emitting session-lifecycle events (`session.start`,
     * `session.shutdown`) and firing session-lifecycle hooks (`sessionStart`,
     * `sessionEnd`) for subagent sessions.
     */
    isSubagentSession(): boolean;
    /**
     * Stable identifier for the conversation lineage this session belongs to.
     *
     * Forking copies the source event log verbatim — the session id is rewritten
     * but event ids are not — so a session and every fork taken from it resolve
     * to the same value while their session ids differ. BYOK Responses requests
     * derive their prompt cache key from this so a fork keeps the parent's
     * prompt-cache affinity instead of starting cold.
     *
     * A subagent has its own native session and therefore its own event log, so
     * its root event is unique to it. Anchoring there would split every sibling
     * of a fan-out onto a separate cache shard despite sharing the parent's
     * session id and a byte-identical system-prompt/tool prefix, so a subagent
     * resolves this from the log it was handed at creation — the parent's, or
     * transitively the root ancestor's. Resolving on each read rather than
     * capturing a value at creation keeps a subagent spawned before its parent
     * recorded any event in step with the parent once the parent has a lineage.
     * A log with no structural event yields `undefined` and the key falls back
     * to the shared session id — the behavior siblings had before lineages
     * existed.
     */
    protected getPromptCacheLineageId(): string | undefined;
    /**
     * Get the per-session autopilot objective registry, lazily creating it on first access.
     * Used by `/autopilot <objective>` and objective-aware autopilot continuation.
     */
    getAutopilotObjectiveRegistry(): AutopilotObjectiveRegistry;
    /**
     * Resolve the effective autopilot continuation config for a session.
     *
     * The default is decided centrally, by client kind, rather than at each
     * session-construction call site. There are many such call sites (SDK
     * create, SDK resume, `--resume` preload, remote connect, managed-server
     * bootstrap, ACP), and requiring every one to remember the option has
     * already produced a silent regression where SDK/app autopilot sessions
     * never continued. Defaulting here means a missed call site fails safe.
     *
     * - `sdk` / `acp`: enabled. These hosts have no continuation loop of their
     *   own, which is the gap this driver exists to close.
     * - `cli`: disabled. The TUI drives continuation through
     *   `useAutopilotContinuation`, which owns Escape-to-cancel, cost display
     *   and plan-mode guards; enabling both would continue twice per turn.
     * - subagents: always disabled, regardless of client kind. A subagent is a
     *   delegated unit of work owned by the parent's task tool -- it finishes
     *   and hands results back, and the *parent's* loop decides whether the
     *   overall objective needs another turn. Subagents inherit `clientKind`
     *   from their parent, so without this they would inherit the driver too
     *   and re-prompt themselves after finishing. The CLI hook never applied to
     *   subagents either, so this keeps hosts consistent with the TUI.
     *
     * An explicit `autopilotContinuation` option always wins for a top-level
     * session, so any host can opt in or out.
     */
    protected static resolveAutopilotContinuationConfig(config: AutopilotContinuationConfig | undefined, clientKind: SessionClientKind | undefined, isSubagent: boolean): AutopilotContinuationConfig;
    /**
     * Initialize the session-level autopilot continuation driver. When enabled,
     * the session observes turn completion in autopilot mode and re-prompts the
     * agent, replacing the host-specific continuation loops.
     */
    protected initAutopilotContinuation(config?: AutopilotContinuationConfig): void;
    /**
     * Subscribe the autopilot task-span accumulator. Records eligible user
     * messages (the opening request plus later steering) for the current span so
     * the completion reviewer can verify the `task_complete` summary against the
     * full request. Eligibility mirrors the completion-telemetry judge: a
     * user-typed, non-empty message that is neither an autopilot-continuation nor
     * a sourced/injected message (skill/agent/system). The span is cleared on any
     * real completion (`task_complete` outcome other than `continue`); a steering
     * message appends to the open span rather than resetting it, so it is tracked
     * separately from the per-turn continuation state (which resets on every
     * user message). Skipped for subagents, which never run the reviewer.
     */
    private initAutopilotTaskSpanAccumulator;
    /**
     * Whether the session-level autopilot continuation driver is enabled.
     * Hosts can check this to avoid running their own continuation loop.
     */
    get autopilotContinuationEnabled(): boolean;
    /**
     * Reset autopilot continuation state for a new user-initiated turn.
     * Called when a non-continuation message arrives to restart the counter.
     */
    resetAutopilotContinuationState(): void;
    /** Whether the current user is on token-based billing (pay per token, not per premium request). */
    private isTokenBasedBillingUser;
    /**
     * Attempt an autopilot continuation turn. Called before `emitSessionIdle()`
     * to intercept the idle and keep the autopilot loop going.
     *
     * @returns `true` if a continuation message was enqueued (idle should NOT
     * be emitted), `false` if the session should emit idle normally.
     */
    protected tryAutopilotContinuation(aborted: boolean): boolean;
    /** Token limits for the currently selected model, including custom-provider and capability overrides when present. */
    getTokenLimits(): {
        promptTokenLimit?: number;
        contextWindowTokens?: number;
        outputTokenLimit?: number;
    };
    /** Get the installed plugins for this session */
    getInstalledPlugins(): readonly InstalledPlugin[] | undefined;
    getPluginActivationPolicy(): SessionPluginActivationPolicy | undefined;
    getPluginActivationSnapshot(): EffectivePluginSnapshot | undefined;
    nextPluginActivationGeneration(): number;
    updatePluginActivation(resolution: EffectivePluginResolution): boolean;
    protected get installedPlugins(): InstalledPlugin[] | undefined;
    protected set installedPlugins(value: InstalledPlugin[] | undefined);
    protected get enableConfigDiscovery(): boolean;
    get enableOnDemandInstructionDiscovery(): boolean;
    protected get mcpServers(): Record<string, MCPServerConfig> | undefined;
    protected set mcpServers(value: Record<string, MCPServerConfig> | undefined);
    protected getModelListForHostEffect(_options?: {
        skipCache?: boolean;
    }): Promise<{
        list: unknown[];
        modelPriceCategories?: Array<{
            id: string;
            priceCategory: string;
        }>;
        quotaSnapshots?: Record<string, unknown>;
    }>;
    private projectRewindUserTurns;
    private conversationOnlyRewindPoints;
    private assertRewindEvent;
    private runHistoryTruncateForRewind;
    private listRewindPointsForApi;
    private previewRewindForApi;
    /**
     * Applies a rewind: restore captured files (conversation-and-files only),
     * then truncate conversation history, then prune the now-obsolete snapshots.
     *
     * **The three stages span two stores and are not crash-atomic.** File
     * restoration writes the workspace; truncation writes the events log. They
     * are ordered restore-then-truncate and each stage's failure is reported
     * rather than swallowed, but there is no journal spanning them, so a process
     * crash between them leaves the workspace rewound while the conversation
     * still holds the discarded turns.
     *
     * A crash *before* truncation lands is recovered by re-running the same
     * rewind: file restore only reverts paths whose content still matches the
     * postimage Copilot last wrote (already-restored paths come back as
     * skipped), and truncation is re-derived from the still-retained boundary
     * event. A crash *after* truncation lands cannot be recovered that way —
     * truncation removes the boundary event, so the same request is rejected as
     * not a current root user turn. The only stage that can be left undone at
     * that point is snapshot pruning, whose failure mode is orphan snapshots the
     * capture store deliberately tolerates rather than a wrong workspace or
     * conversation. The reverse inconsistency — conversation rewound but files
     * not — cannot happen, because truncation is never attempted until file
     * restore has succeeded.
     */
    private rewindForApi;
    private sessionDiffForApi;
    runNativeSessionHostEffect(effect: string, params: Record<string, unknown>, _caller?: NativeSessionHostEffectCaller): Promise<unknown>;
    /**
     * Whether this session still has active work that should prevent stale cleanup.
     * Subclasses can override to include implementation-specific activity signals.
     */
    get hasActiveWork(): boolean;
    /** Get the skills that were loaded during session initialization. */
    getLoadedSkills(): readonly Skill_2[];
    /**
     * Ensure skills have been loaded. If skills haven't been loaded yet (no session.send has
     * been called), triggers a lightweight skill load so that session.skills.list returns
     * accurate results without waiting for the first message.
     */
    ensureSkillsLoaded(): Promise<void>;
    /**
     * Ensure custom agents have been loaded. Awaits the pending load started in the constructor
     * if it hasn't completed yet. If the constructor's load was skipped (e.g., authInfo wasn't
     * available yet for resumed sessions), retries loading now that authInfo may be set.
     */
    ensureAgentsLoaded(): Promise<void>;
    /**
     * Public read accessor for `enableConfigDiscovery`. The SDK resume path needs to
     * detect a discovery true → false transition before `updateOptions` mutates the
     * flag so it can fire `reloadPluginHooks` for the now-filtered ambient plugins.
     * Also used by shared plugin APIs (e.g. `session.plugins.reload`) to decide whether
     * they may pull ambient global configuration into this session; sessions created with
     * discovery disabled (subagents, isolated SDK sessions) keep only their explicit set.
     */
    isConfigDiscoveryEnabled(): boolean;
    getGitHubMcpUserOverride(): boolean;
    getGitHubMcpToolConfig(): GitHubMcpToolConfig_2 | undefined;
    protected resolveDefaultMcpPolicyOptions(config?: {
        mcp3pEnabled?: boolean;
        configFilter?: McpConfigFilter;
    }): Promise<{
        mcp3pEnabled: boolean;
        configFilter?: McpConfigFilter;
        managedAllowedMcpServerLists?: ManagedMcpServerMatcher[][];
        managedDeniedMcpServers?: ManagedMcpServerMatcher[];
    }>;
    protected resolveActiveGitHubTokenForMcpEnv(): Promise<string | undefined>;
    /**
     * Wait for MCP loading owned by a concrete session implementation.
     *
     * Delegates to {@link ensureMcpLoaded}, which is the virtual seam: that older
     * name is the one published in the `@github/copilot/sdk` type surface, so an
     * external subclass may override it. Forwarding this way (rather than the
     * reverse) keeps such an override in effect for every internal caller.
     */
    ensureMcpHostLoaded(): Promise<void>;
    /**
     * @deprecated Prefer {@link ensureMcpHostLoaded} — this waits for the MCP
     * *host* to load, not for any individual server to connect. Retained under
     * the old name because it is the published `@github/copilot/sdk` surface and
     * the override point consumers may already subclass; concrete sessions
     * (e.g. `LocalSession`) therefore keep overriding this method.
     */
    ensureMcpLoaded(): Promise<void>;
    /**
     * Ensure a specific MCP server is started/connected before a caller looks it
     * up, for paths (e.g. MCP Apps) that need one named server rather than the
     * whole host. The base implementation defers to {@link ensureMcpHostLoaded} (a
     * passive wait); {@link LocalSession} overrides it to additionally start a
     * session-level server that entered the config after the host was built
     * (github/copilot-mcp-core#1996).
     */
    protected ensureMcpServerConnected(_serverName: string): Promise<void>;
    /**
     * `MCP server not connected: <name>` (callers match that prefix), with the
     * cause appended when the server is absent from the session config — the
     * shape of github/copilot-mcp-core#1996, where a session resumed without
     * `mcpServers` can never connect an app's server.
     */
    protected mcpAppsNotConnectedError(serverName: string): Error;
    private publishMcpLoadSucceeded;
    protected shouldPublishMcpLoadSucceeded(): boolean;
    protected isMcpLoading(): boolean;
    allowTurnsToProceedWithoutMcp(): boolean;
    readMcpResource(serverName: string, uri: string): Promise<{
        contents: Array<{
            uri: string;
            mimeType?: string;
            text?: string;
            blob?: string;
            _meta?: Record<string, unknown>;
        }>;
    }>;
    /**
     * Fetch an MCP App resource, typically a `ui://` bundle (SEP-1865).
     * Requires the `mcp-apps` session capability.
     */
    readMcpAppResource(serverName: string, uri: string): ReturnType<Session["readMcpResource"]>;
    /**
     * Enumerate one page of resources an MCP server exposes (`resources/list`).
     * Paired with {@link readMcpResource}, this lets an out-of-process consumer
     * list-then-read without prior knowledge of resource URIs. Pass `cursor` to
     * continue from a prior result's `nextCursor`. Errors are surfaced via
     * {@link formatError}.
     */
    listMcpResources(serverName: string, cursor?: string): Promise<{
        resources: SanitizedMcpResource[];
        nextCursor?: string;
    }>;
    /**
     * Enumerate one page of resource templates an MCP server exposes
     * (`resources/templates/list`). Lets an out-of-process consumer expand a
     * resource template into a concrete URI before reading it. Pass `cursor` to
     * continue from a prior result's `nextCursor`. Errors are surfaced via
     * {@link formatError}.
     */
    listMcpResourceTemplates(serverName: string, cursor?: string): Promise<{
        resourceTemplates: SanitizedMcpResourceTemplate[];
        nextCursor?: string;
    }>;
    protected waitForMcpReloadCompletion(waitReason: string): Promise<void>;
    /** Clear the loaded skills cache and reset loading state so the next list triggers a full reload. */
    clearLoadedSkills(): void;
    /** Clear cached agents so the next ensureAgentsLoaded() call re-scans from disk. */
    clearCachedAgents(): void;
    /** Check whether a skill is currently disabled. */
    isSkillDisabled(skillName: string): boolean;
    protected sendMcpServerInstructionsStatsTelemetry(host: McpHost): void;
    /** Enable a previously disabled MCP server (runtime-only, not persisted). */
    enableMcpServer(serverName: string): Promise<void>;
    /** Disable an MCP server (runtime-only, not persisted). */
    disableMcpServer(serverName: string): Promise<void>;
    /**
     * Build the event-based handler options (elicitation, sampling, OAuth) for McpHost.
     *
     * Elicitation is gated on `supportsElicitation()` (checks the session capability set)
     * rather than `hasEventListeners()`, because in the SDK path the wildcard event forwarder
     * handles event dispatch without registering per-type listeners.
     *
     * Sampling is gated on `hasEventListeners()` since it is only
     * wired in the CLI path which registers explicit listeners.
     *
     * OAuth delegates to `buildMcpOAuthHandler()` when listeners are registered;
     * otherwise OAuth-required servers become `needs-auth`.
     */
    protected getMcpEventHandlers(): Pick<McpHostOptions, "elicitationHandler" | "samplingHandler" | "onOAuthRequired" | "cancelPendingOAuthRequests" | "onHeadersRefresh" | "mcpAppsEnabled">;
    /**
     * Whether this session supports MCP Apps (SEP-1865) UI passthrough.
     * Combined with the MCP_APPS feature flag inside {@link MCPRegistry} —
     * the capability gates per client type, the flag gates rollout.
     */
    supportsMcpApps(): boolean;
    private rawMcpAppsListTools;
    private rawMcpAppsCallTool;
    private callMcpAppToolWithOAuthRetry;
    private rawMcpAppsReadResource;
    /**
     * Read-only probe: unlike the read/list/call paths this only waits for the
     * host, it does not `ensureMcpServerConnected()`. Starting a server here
     * would give a diagnostic side effects (process spawn, OAuth) and let it
     * throw where it otherwise soft-fails. So in the Case C window (a server
     * added via `updateOptions` after the host was built) this reports
     * `connected: false` while a `readResource` would connect it on demand —
     * don't gate those calls on this.
     */
    private rawMcpAppsDiagnose;
    /**
     * Reload MCP servers with the given configuration.
     * Creates a new McpHost internally, stops the previous one, and starts the new servers.
     * Pre-processes config to detect user-configured GitHub MCP servers and stash them
     * for later auth (via configureGitHubMcp).
     */
    reloadMcpServers(config: ReloadMcpServersConfig): Promise<StartServersResult>;
    private performMcpReload;
    protected wireMcpHostStateChanges(mcpHost: McpHost): void;
    protected handleMcpServerStateChanged(): void;
    /**
     * Builds and wires a new `McpHost` from `this.mcpServers` using the options
     * common to both host-creation paths (lazy `McpHostLifecycle` and
     * `performMcpReload()`): everything except the disabled-server list, resolved
     * MCP policy, active GitHub token, and (reload-only) secret store, which the
     * caller passes in. Does NOT assign `this.mcpHost` or call `startServers()` —
     * both callers hand the host to {@link McpHostLifecycle.assignAndStartHost},
     * which owns assign + start + dispose-on-failure uniformly.
     */
    protected createMcpHostInstance(options: {
        disabledMcpServers: string[] | undefined;
        mcpPolicy: {
            mcp3pEnabled: boolean;
            configFilter?: McpConfigFilter;
            managedAllowedMcpServerLists?: ManagedMcpServerMatcher[][];
            managedDeniedMcpServers?: ManagedMcpServerMatcher[];
        };
        activeGitHubToken: string | undefined;
        secretStore?: McpSecretStoreInterface;
        toolSnapshotCache?: McpToolSnapshotCache;
    }): McpHost;
    /**
     * Configure the GitHub MCP server for the given auth info.
     * Starts pending user-configured GitHub servers and the built-in server.
     * @returns true if GitHub auth was applied, false if ignored
     */
    configureGitHubMcp(authInfo: AuthInfo): Promise<boolean>;
    /**
     * Remove GitHub MCP server configuration (e.g., on logout).
     * @returns true if GitHub server was removed, false if no action taken
     */
    removeGitHubMcp(): Promise<boolean>;
    /** Get the extension controller if extensions are available. */
    getExtensionController(): ExtensionController | undefined;
    /** Get the MCP host (if initialized) for status queries. */
    getMcpHost(): McpHost | undefined;
    /**
     * Replace or remove one MCP server without rebuilding the host.
     *
     * Used for authoritative live configuration changes that must preserve all
     * unrelated server and host runtime state.
     */
    replaceMcpServerConfig(serverName: string, config: MCPServerConfig | undefined, options?: {
        trustedFirstParty?: boolean;
    }): Promise<boolean>;
    /**
     * This session's remote (HTTP/SSE) MCP egress decision. Delegates to the live
     * {@link McpHost} when one exists (which also awaits the deferred keychain
     * lookup); otherwise resolves from the sandbox config directly, so the MCP
     * config UI can preview the egress before any host exists.
     */
    getResolvedSandboxRemoteMcpEgress(): Promise<SandboxRemoteMcpEgress_2>;
    protected setOnServerStatusChanged(host: McpHost): void;
    /**
     * Wire the MCP host's `list_changed` notifications to a first-class session
     * event so out-of-process consumers can refresh their view of a server's
     * tools, resources, or prompts without polling.
     */
    protected setOnListChanged(host: McpHost): void;
    /** Wire the MCP host's user-abort notification to the session's abort flow. */
    protected setAbortCallback(host: McpHost): void;
    /**
     * Hook invoked when a built-in MCP server requests a user-initiated abort
     * (e.g. computer-use escape). Subclasses override to drop queued work so
     * the abort fully stops the session, not just the current turn.
     */
    protected onUserAbort(): void;
    /** Enable a skill by removing it from the disabled set. */
    enableSkill(skillName: string): void;
    /** Disable a skill by adding it to the disabled set. */
    disableSkill(skillName: string): void;
    /** Emit a skills_loaded event with the current skill state. */
    private emitSkillsChanged;
    private eventProcessingQueue;
    private eventHandlers;
    private wildcardEventHandlers;
    private observedBuiltinAgentPolicyRevision;
    /**
     * Parent session in the built-in agent policy inheritance chain. Set for
     * subagents via {@link inheritBuiltinAgentPolicyState}; keeps inheritance
     * downward-only so a descendant's local policy update never mutates an
     * ancestor or sibling.
     */
    protected builtinAgentPolicyParent?: Session<SessionMetadata>;
    /**
     * Local revision counter, bumped whenever this session's *own* built-in
     * agent policy changes. Combined with ancestors' counters into a chain
     * revision so a live parent-policy update is detected by existing subagents
     * (see {@link getBuiltinAgentPolicyRevision}).
     */
    protected builtinAgentPolicyVersion: number;
    protected shellToolProcessFlags?: string[];
    protected shellInitScripts?: readonly ShellInitScript_2[];
    /** This session's own (unmerged) built-in agent allowlist. */
    private get localIncludedBuiltinAgents();
    /** This session's own (unmerged) built-in agent denylist. */
    private get localExcludedBuiltinAgents();
    protected get includedBuiltinAgents(): string[] | undefined;
    protected get excludedBuiltinAgents(): string[] | undefined;
    /**
     * Resolves the effective built-in agent policy by merging the inherited
     * (ancestor) policy with this session's own local policy: the denylist is
     * the union across the chain, while a local allowlist narrows (intersects)
     * the inherited one. Mirrors the parent-linked resolution used before the
     * Rust port so subagents track live parent-policy changes.
     */
    protected resolveBuiltinAgentPolicy(): {
        includedBuiltinAgents?: string[];
        excludedBuiltinAgents?: string[];
    };
    /**
     * Chain revision built from this session's version counter plus every
     * ancestor's, so a policy change anywhere up the inheritance chain yields a
     * new value and invalidates cached tool config on the next access.
     */
    protected getBuiltinAgentPolicyRevision(): string;
    /**
     * Links this (subagent) session into the parent's built-in agent policy
     * chain and re-seeds the observed revision so the first tool-config access
     * doesn't spuriously invalidate.
     */
    protected inheritBuiltinAgentPolicyState(parent: Session<SessionMetadata>): void;
    /** The session's local MCP host, if one has been created. Owned by {@link mcpHostLifecycle}. */
    protected get mcpHost(): McpHost | undefined;
    /**
     * Assigns the session's local MCP host. Delegates to the lifecycle, which
     * owns the host and clears the native MCP server snapshot when cleared to
     * `undefined` (failed/abandoned `startServers()`, reload dispose-before-replace,
     * or teardown).
     */
    protected set mcpHost(host: McpHost | undefined);
    protected inheritedMcpTools?: readonly Tool[];
    /**
     * MCP tools captured *before* {@link handleWebSearchTooling} normalizes the web-search tool
     * for this session's own model/flag decision. Subagents inherit from this raw snapshot (not the
     * normalized {@link ToolConfig.mcpTools}) so a child running a different model can normalize the
     * web-search tool against its *own* native-web-search decision. Inheriting the normalized array
     * is lossy: the raw `github-mcp-server-web_search` tool is either removed (parent uses hosted
     * search) or already rewritten to the generic `web_search` wrapper (parent doesn't), and neither
     * can be reversed by an ineligible/eligible child.
     */
    protected rawMcpToolsForSubagentInheritance?: readonly Tool[];
    protected inheritedMcpServers?: Readonly<Record<string, MCPServerConfig>>;
    /** Resolver for OTel trace context on MCP tool calls. Provided at construction by the session manager. */
    protected _mcpTraceContextResolver?: TraceContextResolver;
    /**
     * Resolver for OTel parent trace context propagation. Invoked from
     * {@link sendForSchema} so the runtime's OTel lifecycle can attach (or
     * clear) the W3C trace context for the upcoming agent turn. The
     * session manager provides this when the session is created or resumed.
     * Always invoked unconditionally, including when both args are undefined,
     * so prior trace context is cleared rather than inherited.
     */
    protected _otelParentContextResolver?: (traceparent: string | undefined, tracestate: string | undefined) => void;
    protected nativeHookProcessor?: NativeHookProcessor;
    /**
     * Hook processors this session replaced while a turn was still running.
     *
     * A request binds its hook pipeline to one concrete {@link NativeHookProcessor}
     * at assembly time and cannot rebind. Disposing that processor out from under
     * a live turn invalidates its native handle, so the pre-tool guard fails
     * closed and rejects every remaining tool call — killing a turn that was
     * running fine (github/copilot-agent-runtime#14153). Retiring the processor
     * here instead keeps the in-flight request's hooks working (unchanged
     * authorization policy for the rest of that request, which is what the
     * request was admitted under) while new requests bind the replacement.
     * Drained once the session goes idle, and on dispose.
     */
    private readonly retiredNativeHookProcessors;
    protected ownsNativeHookSession: boolean;
    /**
     * Agents whose FILE was found during discovery but failed to load (e.g. malformed
     * frontmatter). Mirrors the currently-applied `customAgents` set so `selectCustomAgent`
     * can distinguish a genuinely-absent agent from one that exists but failed to parse.
     */
    private customAgentLoadFailures;
    /** Live prompt builders are JS closures; serializable agent cache/selection state lives in Rust. */
    private readonly customAgentCallbackSidecars;
    private readonly agentPromptOverrides;
    protected sectionTransformFn?: SectionTransformFn;
    /**
     * The cwd claimed by an authoritative change (`metadata.setWorkingDirectory`
     * or an SDK resume carrying a caller-supplied `workingDirectory`). `undefined`
     * until the first authoritative change: while unset, a bare
     * `updateOptions({workingDirectory})` may move the cwd (initial/SDK/test
     * convenience); once set, a NON-authoritative patch whose `workingDirectory`
     * differs is refused so a stale full-options snapshot cannot silently rewind
     * the runtime working directory. See {@link resolveWorkingDirectoryOverride}.
     */
    private authoritativeWorkingDir;
    /**
     * Base (pre-experiment) values of the two dynamic-retrieval flags, captured
     * whenever feature flags are set from options. The native settings/tools
     * planner restores these when no arm is assigned, so a mid-session transition from an
     * assigned arm back to unassigned can't leave the mutated flags stuck on.
     */
    protected featureFlagService: IFeatureFlagService;
    private ownedFeatureFlagService?;
    /**
     * Tail of the per-session GitHub MCP refresh chain. Credential re-pins fire
     * `configureGitHubMcp` fire-and-forget, but that method caches the new token
     * synchronously before an async server restart with no per-server mutex, so
     * two overlapping refreshes could finish out of order and leave the server on
     * a stale bearer while the cache records the newer token. Serializing them
     * here preserves arrival order without blocking the credential-swap response.
     */
    private githubMcpRefreshChain;
    protected coreServices: CoreServices;
    /**
     * When set, returns whether the plan-mode write gate is active in the parent
     * session, consulted live per tool call. Present on subagents spawned from a
     * plan-mode parent so delegated work inherits the no-mutations behavior and
     * tracks later parent-mode changes rather than a construction-time snapshot.
     * See {@link isPlanModeWriteGateActive}.
     */
    protected readonly parentPlanModeWriteGateActive?: () => boolean;
    /**
     * Native session ids of this session's plan-mode ancestors, outermost first.
     * Handed to the native write gate so it can re-read each ancestor's live mode
     * per tool batch instead of freezing {@link parentPlanModeWriteGateActive}.
     */
    protected readonly parentPlanModeWriteGateSessionIds?: string[];
    /**
     * Per-invocation agent id (typically the dispatching task tool's `toolCallId`)
     * when this session represents a subagent invocation. Undefined on outer
     * sessions. Distinct from `sessionId` (which identifies the CLI session as a
     * whole and is shared by all subagent invocations under the same root).
     *
     * Used to surface the per-invocation id on hook payloads, preserving the
     * existing hook contract after the McpHost/CAPI/OAuth consumers were moved
     * to read the root `sessionId` directly.
     */
    /**
     * Per-session cap (decoded bytes) for inline model-facing binary tool
     * results persisted in session events. Undefined falls back to
     * the Rust-owned default cap. Resolved via
     * {@link getMaxInlineBinaryBytes}.
     */
    protected _skillsLoadingPromise?: Promise<void>;
    protected _agentsLoadingPromise?: Promise<void>;
    private _agentsGeneration;
    private _agentsLoadingGeneration?;
    private _agentsLoadingRetired?;
    private _retireAgentsLoading?;
    private _reloadAvailableModels?;
    /**
     * Accumulated eligible user messages for the current autopilot task span:
     * the opening request plus any later steering. Used as the completion
     * reviewer's ground data (both for `/goal` objectives and plain autopilot):
     * later steering is folded in under the steering experiment, and the span
     * feeds the plain-autopilot reviewer under the plain-autopilot experiment.
     * `startedAt` marks the span start so tool evidence can be sampled from the
     * right point. The span is cleared on a real completion (any `task_complete`
     * outcome other than `continue`); the next eligible message opens a fresh
     * span. Bounded to avoid unbounded growth on a session that never completes.
     */
    private _autopilotTaskSpan;
    /**
     * Consecutive reviewer-derived `continue` decisions for the current
     * non-objective (plain autopilot) task span. The plain-autopilot analogue of
     * the objective rejection streak: sampled into the reviewer so the native
     * decision fails open once the rejection budget is exhausted instead of
     * looping. Reset on span clear and on any non-reviewer-`continue` outcome.
     */
    private nonObjectiveCompletionRejectionStreak;
    /**
     * Ground data for the completion reviewer over the current task span.
     *
     * The base ground data is the task's *opening request*:
     *   - objective mode: the authoritative `/goal` objective text (`objectiveText`);
     *   - plain autopilot: the first accumulated eligible user message.
     *
     * When `includeSteering` is true (the steering experiment) any later eligible
     * user messages are appended — deduped against the objective text so the opening
     * `/goal` send captured as a user message is not repeated — so the reviewer
     * verifies against the opening request plus later steering. When false, only the
     * opening request is returned. With no accumulated messages and no objective text
     * the result is the empty string. Lives on the base class so the reviewer methods
     * on `LocalSession` and the accumulator here share one span.
     */
    protected buildTaskSpanCriteria(objectiveText: string | undefined, includeSteering: boolean): string;
    /** Start timestamp of the current autopilot task span, if one is open. */
    protected getAutopilotTaskSpanStart(): string | undefined;
    /** Read the non-objective completion rejection streak (reviewer fail-open budget). */
    protected getNonObjectiveCompletionRejectionStreak(): number;
    /** Update the non-objective completion rejection streak. */
    protected setNonObjectiveCompletionRejectionStreak(value: number): void;
    /**
     * Owns creating, starting, reconciling, disposing, and lazily (re)loading
     * this session's local `McpHost`, plus the MCP state only the host lifecycle
     * touches (selected-agent server names, last-reconciled snapshot, native
     * server snapshot). `Session` reaches the host only through this class,
     * passing an accessor-based context for the session behavior the lifecycle
     * must call back into — see {@link McpHostLifecycle}.
     *
     * Constructed in the constructor body (not a field initializer) because it
     * needs {@link nativeSessionId}, which is assigned there.
     */
    protected readonly mcpHostLifecycle: McpHostLifecycle;
    /** Throws if the session's MCP lifecycle has been torn down (see `dispose()`). */
    protected throwIfMcpLifecycleDisposed(): void;
    protected acquireMcpLifecycle(): Promise<() => void>;
    /**
     * Proactively cancels an in-flight MCP load so callers that must tear down
     * promptly — namely `dispose()` — don't stall for the connect handshake
     * timeout (native stdio/HTTP connects have a 60s minimum, see
     * `native_config_pipeline.rs`). Both load paths hold the lifecycle mutex for
     * the whole handshake, so awaiting it would block just as long; instead
     * {@link McpHostLifecycle.cancelInFlightLoad} disposes the current host
     * outside the mutex to abort its connects. This method only releases the
     * session-specific pre-host waits below, then delegates the rest.
     */
    protected cancelInFlightMcpLoad(): Promise<void>;
    /**
     * Tracks an in-flight MCP restart kicked off by a sandbox toggle in
     * `updateOptions()`. The next turn (`initializeMcpHost()`) awaits this so
     * MCP tools aren't loaded against stdio servers running under a stale
     * sandbox policy.
     */
    protected _pendingSandboxRestart?: Promise<void>;
    /**
     * Tracks the in-flight resolution + secret-filter registration of the sandbox
     * proxy password (which may be a `${secret:…}` keychain / `${VAR}` env
     * reference resolved asynchronously) kicked off by a sandbox change in the
     * synchronous `updateOptions()`. The next turn (`initializeMcpHost()`) awaits
     * this so the resolved credential is redacted before any tool can echo it.
     */
    protected _pendingProxySecretRegistration?: Promise<void>;
    private pluginActivationPolicy?;
    private pluginActivationSnapshot?;
    private pluginActivationGeneration;
    protected onExitPlanMode?: (request: ExitPlanModeRequest) => Promise<ExitPlanModeResponse>;
    private _autopilotObjectiveRegistry?;
    /**
     * A context-clear seed prompt captured mid-turn. Enqueued as its own next
     * turn once the current agentic loop exits (see
     * `finalizePendingClearContextMessage`); the native projection owns the
     * actual context wipe via the durable `session.context_cleared` event.
     */
    protected pendingClearContextMessage: string | undefined;
    /**
     * Session-level autopilot continuation driver state. When enabled via
     * {@link AutopilotContinuationConfig}, the session itself handles the
     * continuation loop instead of requiring each host to implement it.
     */
    protected _autopilotContinuation: {
        readonly config: AutopilotContinuationConfig;
        taskCompleted: boolean;
        hasError: boolean;
        madeProgressThisTurn: boolean;
        consecutiveNoProgressTurns: number;
        nonObjectiveContinuationCount: number;
        /**
         * Set when a non-objective (plain autopilot) completion was reviewed as
         * `blocked`. Unlike an objective `blocked` (which pauses the objective),
         * a plain-autopilot block has nothing to pause, so it stops the
         * continuation loop and surfaces the block to the user. Consumed and
         * cleared by {@link tryAutopilotContinuation}.
         */
        blocked?: boolean;
    };
    protected requestedTools?: string[];
    protected deferredToolLoading?: boolean;
    /**
     * Optional hard cap on the number of model turns this session's agentic loop runs.
     * Set for constrained subagents (e.g. the search subagent); undefined for normal
     * sessions. When set, the session enforces the cap itself: once a turn starts more
     * than one grace turn past the budget it aborts and sets {@link turnCapReached}. This
     * value also drives {@link LastTurnWarningProcessor} to warn the model before its
     * final turn.
     */
    protected maxAgentTurns?: number;
    /**
     * Optional warning injected before the final allotted turn (only when
     * {@link maxAgentTurns} is set). Coaxes the model to produce a final answer.
     */
    protected lastTurnWarning?: string;
    protected extensionController?: ExtensionController;
    protected sessionTelemetry?: DisposableTelemetrySender;
    protected userMessageSentimentTelemetry?: UserMessageSentimentTelemetry;
    protected taskCompletionCriteriaTelemetry?: TaskCompletionCriteriaTelemetry;
    protected nativeDirectRegistration?: DirectNativeSessionRegistration;
    private nativeDirectInvokeCount;
    private nativeDirectDisposePending;
    /** Handler that delegates permission requests to a parent session. */
    protected parentPermissionRequestHandler?: (request: PermissionRequest_2) => Promise<PermissionRequestResult>;
    private managedPermissionRulesActiveCache;
    /** Content exclusion service auto-created by Session when auth and feature flags are available. */
    protected contentExclusionService?: ContentExclusionServiceHandle_2;
    /** Returns the content exclusion service, or undefined if not yet initialized. */
    getContentExclusionService(): ContentExclusionServiceHandle_2 | undefined;
    protected setContentExclusionService(service: ContentExclusionServiceHandle_2 | undefined, _ownsService: boolean): void;
    protected replayIfcEffects(effectsJson: string): {
        activated?: boolean;
    };
    stampIfcToolResult(result: ToolResult): ToolResult;
    protected hydrateIfcEngineFromPersistedToolEvents(resetToFloor?: boolean): Promise<void>;
    /** Virtual filesystem for session-scoped storage (events, workspace, temp files). */
    readonly sessionFs: SessionFs;
    /** Per-session MCP OAuth token/registration store. */
    readonly mcpOAuthStore: MCPOAuthStoreInterface;
    private readonly mcpOAuthServersWithUpdatedCredentials;
    private readonly mcpOAuthServersRequiringTokenRefresh;
    protected copilotUrl?: string;
    /**
     * Effective enterprise managed settings applied to this session, or
     * `undefined` when no managed policy is in force. Set via
     * {@link applyManagedSettings} from self-fetched server policy, device MDM,
     * and/or a permissions-only SDK client layer.
     */
    protected effectiveManagedSettings?: ManagedSettings;
    protected managedSettingsLayers?: {
        serverResponse?: ManagedSettings;
        deviceResponse?: ManagedSettings;
        deviceSandboxFloor?: ManagedSettings["sandbox"];
    };
    private clientManagedSettings?;
    private pendingClientManagedSettings?;
    private clientManagedSettingsResumeTransactionActive;
    private managedSettingsResolvedEventPending;
    private clientManagedSettingsResumeTransactionChanged;
    private readonly managedPolicyChildSessions;
    private managedPolicyParent?;
    protected detachManagedPolicyRelationships(): void;
    protected managedMcpInterimFailClosed: boolean;
    /**
     * Cached `true` when managed settings disable bypass-permissions ("yolo")
     * mode. The runtime self-enforces this — {@link setAllowAllPermissions}
     * refuses to enable allow-all while it is set, so the restriction holds for
     * every host (CLI slash commands and SDK `permissions.setAllowAll` alike).
     */
    protected bypassPermissionsDisabledByPolicy: boolean;
    /**
     * Opt-in (from {@link SessionOptions.enableManagedSettings}): when set,
     * the runtime self-fetches enterprise managed settings as soon as auth
     * becomes available and re-applies them on account change.
     */
    private enableManagedSettings;
    private managedSettingsFetchIdentity?;
    private managedSettingsAuthGeneration;
    private managedSettingsFetchGeneration;
    /**
     * Account identity (`host\0login`) that the most recent self-fetch was
     * triggered for. Dedupes repeat triggers and detects account switches.
     */
    /** In-flight (or last) self-fetch promise, awaited by bootstrap when auth is present at create. */
    private managedSettingsIngestPromise?;
    private managedPermissionPolicyGate?;
    private managedMcpPolicyGate?;
    private managedMcpPolicyApplied;
    /**
     * Hourly refresh timer for long-running sessions. Periodically re-fetches
     * and re-applies enterprise managed settings so policy changes made after
     * the session started take effect without a restart. Cleared on
     * {@link dispose}. See {@link MANAGED_SETTINGS_REFRESH_INTERVAL_MS}.
     */
    private managedSettingsRefreshTimer;
    /** Auto-mode session manager; provided by `coreServices.autoModeManager` and used to resolve the virtual `"auto"` model selection. */
    protected autoModeManager: AutoModeSessionManager;
    /**
     * Session-lifetime snapshot of the user-settings `effortLevel` used as the
     * request-time fallback when the session has no pinned reasoning effort.
     * Captured once on first successful read (a transient read failure is
     * retried, never memoized) so a settings write from another live session
     * (e.g. the /model picker in a sibling split-view session) cannot silently
     * change this session's reasoning effort mid-flight. New sessions still read
     * the latest settings value.
     *
     * NOTE: the stored promise MAY reject — the underlying `UserSettings.load`
     * has no attached `.catch` (that is deliberate: the rejection is what drives
     * the retry). Its rejection is handled, and the failed snapshot cleared for
     * retry, ONLY inside {@link getSettingsEffortLevelSnapshot}. Always consume
     * it through that getter; never `await` this field directly.
     */
    protected settingsEffortLevelSnapshot?: Promise<string | undefined>;
    protected verbosity?: Verbosity_2;
    /**
     * Last snapshot handed out by {@link materializeEventSnapshot}, stamped with
     * the native durable-log version and epoch it was taken at. Reused as-is
     * while the version holds, and extended with just the appended tail while
     * the epoch holds. See {@link materializeEventSnapshot}.
     */
    private eventSnapshotCache?;
    readonly taskRegistry: TaskRegistry;
    /** Session-root concurrency limiter shared with child subagent sessions. */
    private readonly subAgentLimiter;
    /** Shell tool context owned by this session, created lazily during tool init. */
    protected readonly shellContextHolder: NonNullable<ToolConfig["shellContextHolder"]>;
    /** Inherited sendInboxPublisher for sidekick child sessions. */
    protected sendInboxPublisher?: SendInboxPublisher;
    /** Parent agent task ID for CAPI X-Parent-Agent-Id header. */
    protected parentAgentTaskId?: string;
    /**
     * Native session whose event log this session's prompt-cache lineage is
     * resolved from: its own, or the parent's when it is a subagent. See
     * {@link getPromptCacheLineageId}.
     */
    protected readonly promptCacheLineageSessionId: string;
    /** Set by SessionAgentExecutor when the subagent fails, read by bridge shutdown handler. */
    subagentFailed: boolean;
    /** Error message when subagentFailed is true. */
    subagentError?: string;
    protected _turnCapReached: boolean;
    /**
     * True once the session aborted itself for exceeding {@link maxAgentTurns}
     * (after one grace turn). Read by SessionAgentExecutor to report the run as a
     * successful, turn-capped completion (salvaging partial work) instead of a failure.
     * Exposed read-only to external callers: only the session (and its subclasses,
     * e.g. the turn-cap enforcement in the `assistant.turn_start` handler) sets the
     * backing field.
     */
    get turnCapReached(): boolean;
    /**
     * Callback set by `createSubagentSession` bridge to emit `subagent.completed` or
     * `subagent.failed` on the parent session. Called by `SessionAgentExecutor.teardown()`
     * as a more reliable alternative to relying on the `session.shutdown` event chain
     * (which can be silently swallowed if `Session.shutdown()` throws during token counting).
     *
     * @param completion.cancelled - Whether the run was torn down by cancellation
     * (its own abort, or an ancestor being killed) rather than finishing its work.
     * Cancellation still reports `subagent.completed` - it is an expected outcome,
     * not a failure - so the flag is what keeps a torn-down sub-agent distinguishable
     * from one that ran to the end.
     */
    notifySubagentComplete?: (completion?: {
        cancelled?: boolean;
    }) => void;
    protected getSessionShellContext(): InteractiveShellToolContext | undefined;
    protected activeShellContext(): InteractiveShellToolContext | undefined;
    protected readonly shellShutdownController: AbortController;
    protected rewindManager?: SessionRewindManager;
    protected tryStartShellOperation(): boolean;
    protected endShellOperation(): void;
    protected get blocksSubagentStart(): boolean;
    tryBeginRewindOperation(): boolean;
    endRewindOperation(): void;
    sendTaskMessage(agentId: string, message: AgentMessage): Promise<true | string>;
    protected bindShellContextHolderMetadata(): void;
    /**
     * Marks the session's shell context stale (sandbox-policy invalidation) so the
     * next tool build rebuilds it.
     *
     * The shell-context generation lives in two counters: the session scalar
     * (exposed as `shellContextHolder.generation`, which seeds every newly-created
     * context's generation and the tool plan's `shellContextGeneration`) and the
     * native `ShellContextHandle` (consulted by `shellContextHolder.isCurrent()`
     * and the `getOrCreate` creation lease). The scalar has no automatic link to
     * the native handle, so this path must advance BOTH: bumping only the scalar
     * (the pre-fix behavior) tagged a freshly-created context with a generation the
     * native handle never matched, so every command failed with the retryable
     * "<shell context is being reconfigured>" result — most visibly after enabling
     * the sandbox (which invalidates once at construction) and then running the
     * first shell command.
     */
    private invalidateShellContext;
    protected currentTools?: Tool[];
    /** Tools resolved during the last initializeAndValidateTools() call.
     * Used by getInitializedTools() for subagent prompt assembly.
     * Separate from currentTools to avoid interfering with tools_changed_notice
     * detection (which compares currentTools across send() calls). */
    protected initializedTools?: readonly Tool[];
    private forwardSubagentUsageEvent?;
    private additionalDirectories;
    /**
     * Raw creation-time additional directories from {@link SessionOptions.additionalDirectories}.
     * Applied onto the native path manager (and the in-memory
     * {@link additionalDirectories} list, in canonical form) during session bootstrap
     * via {@link applyInitialAdditionalDirectories}. Not persisted — callers must
     * re-supply them on resume (mirroring how the CLI re-passes `--add-dir`).
     */
    private readonly optionAdditionalDirectories;
    protected previousAdditionalDirectoriesUsed?: string[];
    markSubagentFailed(error: string): void;
    getSubagentFailure(): {
        failed: boolean;
        error?: string;
    };
    /**
     * Sets the current system message from either a plain string (legacy
     * single-block form) or a structured SystemMessageContent (preserves the
     * static/per-user split for cache-shaped compaction calls). The flat
     * string and the wrapped object identity used by
     * getPromptContextMessagesSnapshot are derived lazily from this value.
     */
    protected setCurrentSystemMessageContent(value: SystemMessageContent | undefined): void;
    /**
     * Cached model list from CAPI (CAPI-only — never merged with BYOK entries).
     *
     * This invariant matters: several call sites use this cache for backend-qualified
     * metadata/multiplier lookups that must resolve to authoritative CAPI metadata, not
     * a synthesized BYOK entry. The public-facing merged list (CAPI
     * ∪ BYOK) is exposed via `getModelList()` / `mergeByokModelList()` instead.
     *
     * Inherited by child sessions via `createSubagentSession`.
     */
    /** Get the cached model list (session-scoped CAPI models, if populated). */
    getModelListCache(): Model[] | undefined;
    /** Pre-populate the model list cache (used by createSubagentSession to share parent's model list). */
    setModelListCache(models: Model[]): void;
    /**
     * White-box accessor bridging the legacy `modelListCache` instance field to
     * the native model-list-cache state. Production code reads the cache via
     * {@link getModelListCache}; this accessor keeps test/introspection code that
     * pokes `modelListCache` directly working against the native-backed store.
     */
    protected get modelListCache(): Model[] | undefined;
    protected set modelListCache(models: Model[] | undefined);
    /**
     * Entitled subagent-only models (see `SUBAGENT_ONLY_MODELS` in `./knownModels`)
     * that CAPI advertised for this session, captured from the unfiltered CAPI list in
     * {@link getModelList}. These are deliberately kept out of `modelListCache` and the
     * picker/available lists so they never leak into user-facing surfaces; they are only
     * surfaced to trusted built-in subagents via `ToolConfig.subagentOnlyModels`. Empty
     * when CAPI advertises none.
     */
    protected subagentOnlyModelCache: Model[];
    /**
     * The unfiltered CAPI model list captured from {@link getModelList} (picker-disabled AND
     * subagent-only models included). Unlike {@link modelListCache} — which is the user-facing
     * picker subset and can omit hidden models or be empty on empty-picker tiers even when Auto
     * mode resolves a concrete model — this is the include-hidden superset that dispatch resolves
     * against (`capiClientResolveChatModelWithClient({ includeHidden: true })`). Used by
     * {@link modelUsesResponsesApi} so the native-web-search wire decision matches the model the
     * request will actually be dispatched on. Undefined until the CAPI list has been fetched.
     */
    protected unfilteredModelListCache: Model[] | undefined;
    /** Pre-populate the unfiltered (include-hidden) model list cache (shared by createSubagentSession). */
    setUnfilteredModelListCache(models: Model[]): void;
    /**
     * White-box accessor bridging the legacy `subagentAutoModeSession` instance
     * field to the native subagent-auto-mode-session scalar. `createSubagentSession`
     * writes it via the native setter when minting a complementary-strategy child;
     * this accessor keeps test/introspection code that pokes the field directly
     * working against the native-backed store, and lets `resolveAndValidateModel`
     * observe it for the paired-token attachment decision.
     */
    protected get subagentAutoModeSession(): AutoModeSession | undefined;
    protected set subagentAutoModeSession(value: AutoModeSession | undefined);
    /**
     * White-box accessor bridging the legacy `sandboxConfig` instance field to the
     * native sandbox-config scalar (populated at construction from
     * `options.sandboxConfig` and propagated to subagents by
     * `createSubagentSession`). Sandbox state isn't exposed publicly; this accessor
     * keeps test/introspection code that reads `sandboxConfig` directly working
     * against the native-backed store.
     */
    protected get sandboxConfig(): SandboxConfig_3 | undefined;
    /**
     * White-box accessor bridging the legacy `_selectedModel` instance field to
     * the native model-selection state. Production code reads/writes selection
     * through {@link getSelectedModelState} / `setSelectedModel`; this accessor
     * keeps test/introspection code that assigns `_selectedModel` directly
     * working against the native-backed store.
     */
    protected get _selectedModel(): string | undefined;
    protected set _selectedModel(model: string | undefined);
    /**
     * Stable subagent identities. These are distinct per subagent instance,
     * unlike the shared correlation `sessionId` (which a subagent tree intentionally
     * shares with its root for firewall/OAuth/CAPI correlation). They live as plain
     * instance fields — not native session state keyed by the shared `sessionId` —
     * so concurrent subagents in a tree keep independent identities.
     */
    protected readonly agentId?: string;
    protected readonly parentAgentId?: string;
    protected readonly taskRegistryAgentId?: string;
    protected readonly factoryUsageRunId?: string;
    private readonly factoryUsageCoordinator?;
    protected factoryUsageProducerLease?: FactoryUsageProducerLease;
    /** Stable trajectory identity for this session: the child id, or the root session id. */
    protected get stableAgentId(): string;
    protected readonly pendingRequests: PendingRequestStore;
    /** Register an "interest" in `eventType`. Returns an opaque handle. */
    addEventInterest(eventType: string): {
        handle: string;
    };
    /** Release a previously registered interest. Idempotent. */
    removeEventInterest(handle: string): void;
    /** Check whether any typed handlers are registered for a specific event type. */
    protected hasEventListeners(eventType: string): boolean;
    /**
     * Build the MCP OAuth handler passed to `McpHost`.
     *
     * Listener selection is evaluated on every OAuth request (not captured once
     * when the host is constructed), so later 401/reauth requests can switch to
     * host delegation when interest is registered after `session.create`.
     *
     * With a typed `mcp.oauth_required` consumer, delegate token acquisition to
     * them. Without one, attempt only non-interactive authentication from the
     * session token store; if that cannot satisfy the request, callers route the
     * browser-required signal to `needs-auth`.
     */
    protected buildMcpOAuthHandler(): NonNullable<McpHostOptions["onOAuthRequired"]>;
    /**
     * Always-on dynamic headers-refresh callback. Listener interest is checked
     * per refresh so post-create `eventLog.registerInterest` still works for
     * later requests. Without a consumer, return no headers.
     */
    protected buildMcpHeadersRefreshHandler(): NonNullable<McpHostOptions["onHeadersRefresh"]>;
    private resolveMcpOAuthStaticClientConfig;
    /** Respond to a pending permission request by its ID. Returns true if the response was accepted. */
    respondToPermission(requestId: string, result: PermissionPromptResponse, decisionContext?: PermissionDecisionContext): boolean;
    private emitAutoApprovalDecisionTelemetry;
    protected respondToPermissionWithContext(requestId: string, result: PermissionPromptResponse, _decisionContext?: PermissionDecisionContext): PermissionResponseResult;
    private requestToolPermissionFromUser;
    private requestPathPermissionFromUser;
    private requestUrlPermissionFromUser;
    protected requestAutoApprovalFromModel(_rawPermissionRequest: PermissionRequest_2, _promptRequest: PermissionPromptRequest_2): Promise<AutoApprovalModelOutput>;
    private withAutoApprovalRecommendation;
    /**
     * Evaluates permissionRequest hooks without falling through to any permission flow.
     * Returns a result if hooks produce a decision, or null to let the caller
     * fall through to its own routing (PermissionService, callback, or PendingRequestStore).
     */
    protected evaluatePermissionHooks(permissionRequest: PermissionRequest_2, managedPermissionReviewRequired: boolean): Promise<PermissionRequestResult | null>;
    private emitPermissionHookEvents;
    /**
     * Requests permission with hook pre-evaluation, then falls through to
     * the session-owned PermissionService. Used by callers that are NOT already inside the
     * `buildSettingsAndTools` permission block (which runs hooks itself).
     *
     * Callers that have already evaluated hooks should use
     * `requestPermissionDirect()` to avoid running hooks twice.
     */
    requestPermissionWithHooks(permissionRequest: PermissionRequest_2): Promise<PermissionRequestResult>;
    /**
     * Requests permission via the session-owned PermissionService without running hooks.
     * Use when hooks have already been evaluated by the caller (e.g. the
     * `buildSettingsAndTools` permission block, where hooks already ran).
     */
    requestPermissionDirect(permissionRequest: PermissionRequest_2): Promise<PermissionRequestResult>;
    private managedPermissionRulesActive;
    private managedPermissionReviewRequired;
    /** Respond to a pending user input request by its ID. Returns true if the request was still pending. */
    respondToUserInput(requestId: string, response: {
        answer: string;
        wasFreeform: boolean;
        dismissed?: boolean;
    }): boolean;
    /**
     * Snapshot the live, still-pending ask_user requests with their payloads.
     * `user_input.requested` is emitted ephemerally, so a foreground UI that
     * switches back to a backgrounded session cannot rebuild the prompt from
     * event history (as it can for permissions). This in-memory read lets the
     * UI re-surface the pending prompt on switch-back. In-process structural
     * extra; remote sessions hold no local pending state and return `[]`.
     */
    getPendingUserInputRequests(): PendingUserInputRequest[];
    /**
     * Snapshot the live, still-pending elicitation requests with their payloads
     * and source. Same rationale as {@link getPendingUserInputRequests}:
     * `elicitation.requested` is ephemeral, so switch-back re-surfacing reads
     * the in-memory map rather than reconstructing from history.
     */
    getPendingElicitationRequests(): PendingElicitationRequest[];
    private findPendingPrompt;
    private findPendingPromptRequestId;
    /**
     * Look up a pending user-input request by Mission Control `promptId`.
     * Used by `PromptManager` to drive Mission Control responses when no
     * host-side prompt entry was registered (e.g. SDK-consumer model).
     */
    findUserInputRequestIdByPromptId(promptId: string): (string & {}) | "already-resolved" | undefined;
    /** Look up a pending elicitation request by Mission Control `promptId`. */
    findElicitationRequestIdByPromptId(promptId: string): (string & {}) | "already-resolved" | undefined;
    /** Look up a pending exit-plan-mode request by Mission Control `promptId`. */
    findExitPlanModeRequestIdByPromptId(promptId: string): (string & {}) | "already-resolved" | undefined;
    /** Look up a pending permission request by Mission Control `promptId`. */
    findPermissionByPromptId(promptId: string): {
        requestId: string;
        promptRequest: PermissionPromptRequest_2;
    } | "already-resolved" | undefined;
    /**
     * Exposes this session as a {@link RemotePromptFallback} for
     * `PromptManager` to call when no local TUI-registered prompt exists
     * for a Mission Control steer response. See
     * `src/core/sharedApi/sessionContracts.ts` for the contract.
     */
    get promptFallback(): RemotePromptFallback;
    /** Respond to a pending auto-mode switch request by its ID. Returns true if the request was still pending. */
    respondToAutoModeSwitch(requestId: string, response: AutoModeSwitchResponse_2): boolean;
    /** Respond to a pending exhausted session-limit request by its ID. Returns true if the request was still pending. */
    respondToSessionLimitsExhausted(requestId: string, response: SessionLimitsExhaustedResponse_2): boolean;
    protected handleSessionLimitsExhausted(status: ResponseLimitsStatus): Promise<boolean>;
    private applySessionLimitsExhaustedResponse;
    private emitSessionLimitsExhaustedPromptTelemetry;
    private emitInvalidSessionLimitResponse;
    /**
     * Public entry point for requesting a permission check.
     * Routes through permission hooks first, then falls back to the
     * interactive permission prompt (or rule-based decision).
     */
    requestPermission(permissionRequest: PermissionRequest_2): Promise<PermissionRequestResult>;
    /**
     * Emit an elicitation request event and return a promise that resolves when a client responds.
     * Used by MCP servers (via their elicitation handler) to request structured input from the user.
     */
    requestElicitation(request: ElicitRequestParams, elicitationSource?: string): Promise<ElicitResult>;
    /** Respond to a pending elicitation request by its ID. */
    respondToElicitation(requestId: string, response: ElicitResult): void;
    /** Respond to a pending sampling request by its ID. Returns true if the request was still pending. */
    respondToSampling(requestId: string, response?: CreateMessageResultWithTools): boolean;
    /**
     * Try to respond to a pending elicitation request by its ID.
     * Returns true if the request was found and resolved, false if it was already resolved
     * by another client (race-safe: first responder wins).
     */
    tryRespondToElicitation(requestId: string, response: ElicitResult): boolean;
    /**
     * Emit an MCP OAuth request event and return a promise that resolves when a client responds.
     * Used when an MCP server requires OAuth authentication.
     */
    requestMcpOAuth(serverName: string, serverUrl: string, provider: OAuthClientProvider, staticClientConfig?: McpOAuthStaticClientConfig, redirectPort?: number, wwwAuthenticateParams?: McpOAuthWWWAuthenticateParams, resourceMetadata?: string, httpResponse?: McpOAuthRequestContext["httpResponse"], reason?: McpOAuthRequestReason, signal?: AbortSignal): Promise<OAuthClientProvider | undefined>;
    /** Start an MCP OAuth request while retaining its generated request ID. */
    protected requestMcpOAuthTracked(serverName: string, serverUrl: string, provider: OAuthClientProvider, staticClientConfig?: McpOAuthStaticClientConfig, redirectPort?: number, wwwAuthenticateParams?: McpOAuthWWWAuthenticateParams, resourceMetadata?: string, httpResponse?: McpOAuthRequestContext["httpResponse"], reason?: McpOAuthRequestReason): {
        requestId: string;
        response: Promise<OAuthClientProvider | undefined>;
    };
    /** Return details for a pending MCP OAuth request. */
    getMcpOAuthRequest(requestId: string): McpOAuthPendingRequest | undefined;
    /** Respond to a pending MCP OAuth request by its ID. Returns true if accepted. */
    respondToMcpOAuth(requestId: string, provider: OAuthClientProvider | undefined): boolean;
    tryForwardMcpOAuthPendingRequest(_requestId: string, _result: McpOauthPendingRequestResponse): Promise<boolean | undefined>;
    /** Invalidate MCP-derived session state after updated OAuth credentials are persisted. */
    notifyMcpOAuthStateChanged(serverName?: string, refreshSessionToken?: boolean): Promise<void>;
    /** Respond to a pending MCP headers refresh request by its ID. */
    respondToMcpHeadersRefresh(requestId: string, headers: Record<string, string> | undefined): boolean;
    /**
     * Interactively authenticate a remote MCP server via OAuth. Starts the
     * callback listener before returning the authorization URL, then continues
     * the flow in the background and reconnects the server once tokens arrive.
     * Backs the `session.mcp.oauth.login` API and the `/mcp auth` command.
     */
    private mcpOauthLogin;
    /** Request a UI elicitation dialog. Used by session.ui.* API methods. */
    requestUiElicitation(request: ElicitRequestFormParams): Promise<ElicitResult>;
    /**
     * Whether this session supports UI dialogs (confirm, select, input).
     * Effective capability membership is evaluated by the native session state.
     */
    supportsElicitation(): boolean;
    supportsCanvasRenderer(): boolean;
    getDurableOpenCanvases(): OpenCanvasInstance[];
    /**
     * Assert that a capability is enabled for this session.
     * Throws if the capability is missing, with a message including the capability name.
     */
    assertCapability(capability: SessionCapability): void;
    /**
     * Dynamically add a capability to this session.
     * Returns true if the capability was newly added, false if already present.
     */
    addCapability(capability: SessionCapability): boolean;
    /**
     * Dynamically remove a capability from this session.
     * Returns true if the capability was removed, false if it wasn't present.
     * Cancels any pending requests that depend on the removed capability.
     */
    removeCapability(capability: SessionCapability): boolean;
    /** Respond to a pending external tool request by its ID. */
    respondToExternalTool(requestId: string, result: ToolResult): boolean;
    /** Start an external tool request while retaining its generated request ID. */
    protected requestExternalToolTracked(request: ExternalToolRequest): {
        requestId: string;
        response: Promise<ToolResult>;
    };
    /** Reject a pending external tool request (e.g., on dispatch failure). */
    rejectExternalTool(requestId: string, error: Error): boolean;
    private applyExternalToolResponsePlan;
    protected refreshPendingResumeOrphans(): OrphanedToolResumeInfo[] | undefined;
    protected loadPendingResumeOrphans(): OrphanedToolResumeInfo[] | undefined;
    protected takeResumePermissionResult(toolCallId: string): PermissionRequestResult | undefined;
    protected enqueueResumePendingWake(): void;
    private enqueueResumePendingWakeIfNeeded;
    private wakeResumePendingWork;
    /**
     * Block until an external permission or tool response changes orphan state.
     *
     * Used by the continuation loop when `_continuePendingWork` is true: instead of
     * deferring and returning early, the loop awaits this promise so that
     * `isProcessing` stays true and user sends are naturally queued.
     *
     * Resolves when `notifyOrphanResolution()` is called (from `respondToPermission`
     * or `respondToExternalTool`) or when the abort signal fires.
     */
    protected waitForOrphanResolution(): Promise<void>;
    /** Wake up the continuation loop blocked in `waitForOrphanResolution()`. */
    protected notifyOrphanResolution(): void;
    /**
     * Respond to a pending queued command request by its ID. Returns true
     * when a pending entry was found and resolved; false when the request
     * was already resolved, cancelled, or unknown.
     */
    respondToQueuedCommand(requestId: string, result: QueuedCommandResult_2): boolean;
    /** Register SDK commands. Upserts by name. Emits `commands.changed`. */
    registerSdkCommands(commands: ProtocolCommandDefinition[]): void;
    /** Unregister SDK commands by name. Returns number unregistered. Emits `commands.changed`. */
    unregisterSdkCommands(names: string[]): number;
    /** Get all currently registered SDK commands. */
    getSdkCommands(): ProtocolCommandDefinition[];
    /** Respond to a pending command execution request by its ID. */
    respondToCommandExecution(requestId: string, error?: string): void;
    /** Execute a registered command (emits command.queued, server routes to owning connection). */
    executeCommand(commandName: string, args: string): Promise<CommandExecutionResult>;
    /** Reject pending command executions for specific command names (e.g., on client disconnect). */
    rejectCommandExecutionsForNames(commandNames: Set<string>, error: Error): void;
    /**
     * Optional CLI-side dispatcher for the schedule registry's tick path,
     * installed by the CLI host at startup. Covers slash commands that live
     * in the CLI layer (e.g. `/pr`) and so aren't in `getRuntimeSlashCommand`.
     */
    private scheduledCommandResolver;
    setScheduledCommandResolver(resolver: ScheduledCommandResolver | undefined): void;
    /**
     * Resolve a slash command for the schedule registry's tick path. Bypasses
     * the active-turn gate that `session.commands.invoke` enforces because the
     * registry owns delivery: a plain resolved prompt steers into an in-flight
     * run while a mode-bearing one (e.g. `/plan`) is enqueued to run as its own
     * mode-aware turn, so resolving during an in-flight turn is safe either way.
     *
     * Dispatch order: runtime command marked `schedulable: true` →
     * user-invocable skill(s) resolved in the shared session path → CLI
     * fallback resolver (when set) → null (registry skips the tick). Resolving
     * skills here (rather than only via the CLI resolver) lets scheduled skills
     * also fire in headless / in-process SDK sessions that have no CLI host.
     */
    invokeCommand(name: string, input: string, origin?: ScheduleOrigin): Promise<ResolvedScheduledPrompt | null>;
    private emitSdkCommandsChanged;
    /** Respond to a pending exit plan mode request by its ID. Returns true if the request was still pending (and was resolved by this call), false if the request ID was unknown or already resolved. */
    respondToExitPlanMode(requestId: string, response: ExitPlanModeResponse): boolean;
    /**
     * Whether a direct (in-process) exit plan mode callback is set.
     * When true, the callback already handles both local and remote responses
     * (via prompt manager wrapping), so event listeners should NOT independently
     * dispatch to remote clients to avoid duplicate requests.
     */
    hasDirectExitPlanModeHandler(): boolean;
    /**
     * Whether a direct (in-process) auto-mode-switch handler is active.
     * When true, the server bridge must NOT independently dispatch the request
     * to remote clients — the in-process handler will respond and a remote
     * dispatch would race for the same requestId.
     */
    hasDirectAutoModeSwitchHandler(): boolean;
    /**
     * Register an in-process handler for auto-mode-switch requests. The caller
     * still attaches the actual listener via `session.on("auto_mode_switch.requested", ...)`;
     * this counter exists solely so the server bridge knows to skip its own dispatch.
     * Returns an unregister function that must be called when the handler is no
     * longer active (e.g., on React effect cleanup).
     */
    registerDirectAutoModeSwitchHandler(): () => void;
    abstract send(options: SendOptions): Promise<void>;
    /**
     * Append zero or more user messages to the conversation and run exactly one
     * agent turn over the resulting history. The multi-message sibling of
     * {@link send}. An empty list runs a single turn over the existing history
     * with no new user message.
     *
     * Only in-process local sessions implement the batch turn semantics (via the
     * agentic loop). Remote-backed transports ({@link RemoteSession},
     * {@link RelaySession}, and {@link LocalRpcSession}) cannot honor the
     * single-turn batch contract and instead throw an "unsupported" error.
     */
    abstract sendMessages(items: SendOptions[], turnOptions?: {
        mode?: "enqueue" | "immediate";
        prepend?: boolean;
        requestHeaders?: Record<string, string>;
    }): Promise<void>;
    abstract abort(params?: {
        reason?: AbortReason;
    }): Promise<void>;
    /**
     * Schema-shaped wrapper for {@link send} invoked by the JSON-RPC
     * dispatcher (see `src/core/sharedApi/sessionContracts.ts` and
     * `Session.implMethodName` on the `send` schema entry). The wire
     * contract is fire-and-forget: generate a unique `messageId`,
     * dispatch the agent loop in the background, and return
     * immediately with the messageId. Errors that arise during the
     * loop surface as session events.
     *
     * Lives on the abstract base so EVERY session subclass — both
     * `LocalSession` and the `RemoteSession` family (including
     * `LocalRpcSession`) — can be adapted into a `SessionClient` via
     * `sessionToFacadeApi`. The remote-controller foreground swap in
     * `app.tsx`'s `switchSession` depends on this: without an
     * inherited `sendForSchema`, attaching to a `LocalRpcSession`
     * fails the `typeof source.sendForSchema === "function"` check
     * and the swap silently aborts.
     *
     * Field translation:
     * - `traceparent` / `tracestate` are forwarded to the OTel parent
     *   context resolver (always — including when both are undefined,
     *   so previous trace context is cleared rather than inherited).
     * - Only the public `SendOptions` subset listed in `SendParams`
     *   is forwarded to {@link send}; runtime-only fields (for example
     *   `notificationKind`) are deliberately not derivable from the
     *   schema params.
     * - `billable` defaults to `true` when the caller omits the field;
     *   an explicit `false` is honored.
     */
    sendForSchema(params: SendParams): {
        messageId: string;
    } | Promise<{
        messageId: string;
    }>;
    /**
     * Schema-shaped wrapper for {@link sendMessages} invoked by the JSON-RPC
     * dispatcher. The multi-message sibling of {@link sendForSchema}: it accepts
     * an ordered list of per-message objects plus turn-level options, generates
     * one `messageId` per provided message (empty when none), and drives a single
     * agent turn over the resulting history.
     *
     * Field translation mirrors {@link sendForSchema}:
     * - `traceparent` / `tracestate` are forwarded to the OTel parent context
     *   resolver (always — including when both are undefined, so previous trace
     *   context is cleared rather than inherited).
     * - Only the public per-message subset (`prompt`, `displayPrompt`,
     *   `attachments`, `requiredTool`, `billable`, `source`) is forwarded, plus
     *   the turn-level `agentMode` (copied onto every message so both the primary
     *   final message and each preceding message carry it into the turn).
     *   `requestHeaders` is a turn-level concern applied once via `turnOptions`
     *   below, not duplicated onto every message.
     * - `billable` defaults to `true` when a message omits the field; an explicit
     *   `false` is honored per message.
     */
    sendMessagesForSchema(params: SendMessagesParams): {
        messageIds: string[];
    } | Promise<{
        messageIds: string[];
    }>;
    /**
     * Schema-shaped wrapper for {@link abort} invoked by the JSON-RPC
     * dispatcher. Adapts the `Promise<void>` shape of {@link abort}
     * into the `{success, error?}` shape declared by
     * `sessionApiSchema.abort`, catching errors and returning them
     * in-band rather than throwing. Lives on the abstract base for
     * the same reason as {@link sendForSchema}: remote-controller
     * sessions adapted into `SessionClient` instances need this
     * method to be inheritable.
     */
    abortForSchema(params: {
        reason?: AbortReason;
    }): Promise<{
        success: boolean;
        error?: string;
    }>;
    abstract suspend(): Promise<void>;
    abstract ephemeralQuery(question: string, onChunk: (text: string) => void, abortSignal?: AbortSignal): Promise<string>;
    /**
     * Check if the session is currently in a state where it can be aborted.
     * Returns true if there's an active operation that can be cancelled.
     * Default implementation returns false. Override in subclasses that support abortion.
     */
    isAbortable(): boolean;
    /**
     * Initializes tools and validates tool filter configuration.
     * This method should be called after the session is fully configured (auth, model, MCP servers)
     * but before the first message is sent. It will emit warnings for any unknown tool names
     * specified in availableTools or excludedTools.
     *
     * Default implementation is a no-op. Override in subclasses that support tool validation.
     *
     * @returns Promise that resolves when initialization and validation is complete
     */
    initializeAndValidateTools(): Promise<void>;
    /**
     * Emit a streaming tool-execution partial result with secrets redacted.
     *
     * Each `partialOutput` is filtered independently when this method performs redaction, so a
     * registered secret is fully scrubbed only when the producer streams cumulative output that
     * contains the secret whole in some snapshot. Local user-requested shell execution now
     * redacts partials in Rust before the callback crosses into JS and passes
     * `{ alreadyRedacted: true }` here to avoid main-thread rescans; non-local producers still use
     * this fallback path. Model-tool interactive shells that spill to disk stream a bounded rolling
     * tail (`TAIL_CHARS` in `api_shell_attached.rs`) instead of cumulative output, so a secret longer
     * than that window (or whose identifying prefix has rolled out of it) cannot be matched from
     * snapshot-local scans and may reach streaming egress in fragments. Closing that window fully
     * needs a stateful native streaming-filter primitive (holdback, cf. `debug_logs.rs`).
     */
    protected emitToolExecutionPartialResult(toolCallId: string, partialOutput: string, options?: {
        alreadyRedacted?: boolean;
    }): void;
    executeUserRequestedShellCommand(command: string, options?: UserRequestedShellCommandOptions): Promise<UserRequestedShellCommandResult>;
    /**
     * Run a user-requested shell command and return its normalized outcome. This is the overridable
     * execution seam; {@link executeUserRequestedShellCommand} owns the surrounding tool-event envelope
     * (emitting `tool.user_requested` / `tool.execution_partial_result` / `tool.execution_complete` and
     * building the {@link UserRequestedShellCommandResult}). Overrides (e.g. the relay's host-terminal
     * driver) implement only this method and inherit the shared envelope. `onPartialOutput` receives the
     * cumulative cleaned output as it streams; cancellation flows through `options.abortSignal`.
     *
     * The base implementation runs the command on the local machine.
     */
    protected runUserRequestedShellExecution(command: string, onPartialOutput: (partialOutput: string) => void, options: UserRequestedShellCommandOptions): Promise<UserRequestedShellExecution>;
    constructor(coreServices: CoreServices, options?: SessionOptions);
    abstract getMetadata(): SM;
    private readonly sessionsApi?;
    getSessionsApi(): SessionsApi | undefined;
    protected ensureNativeDirectSessionRegistered(): void;
    protected ensureNativeDirectSessionRegisteredForInvoke(): void;
    private registerNativeDirectSession;
    ensureNativeDirectSessionReady(): Promise<void>;
    private isNativeDirectSessionRegistered;
    private isNativeDirectSessionReady;
    protected invokeNativeJson(invoke: NativeSessionFixedInvoker, params?: unknown): Promise<unknown>;
    protected invokeNativeMethodJson<T = unknown>(invoke: NativeSessionMethodInvoker, method: string, params?: unknown): Promise<T>;
    private finishNativeDirectInvoke;
    protected requestNativeDirectRegistrationDispose(): void;
    private disposeNativeDirectRegistration;
    private handleNativeSessionBridgeCall;
    private handleNativeSessionDispatch;
    private invokeNativeSessionMethod;
    private invokeNativeSessionHostEffect;
    private assertNativeSessionPayloadSessionId;
    /**
     * Overwrite this session's code-change line/file counts with host-reported
     * absolute values. Used by relay sessions to feed the footer's `+N −N` from
     * the host's net `SessionSummary.changes`.
     */
    protected applyRemoteCodeChanges(linesAdded: number, linesRemoved: number, filesCount?: number): void;
    protected emitResponseLimitsStatus(status: ResponseLimitsStatus, state: ResponseLimitsEventState, message: string): void;
    protected emitSessionLimitsTerminalError(_message: string): void;
    protected emitSessionLimitsTerminalWarning(_message: string): void;
    /**
     * Computes token breakdown for the current context window state.
     * Partitions tokens into system, conversation, and tool definitions.
     *
     * Note: Uses currentToolMetadata which approximates the real request payload
     * (e.g., does not account for deferred tool loading or custom tool formats).
     * For precise per-turn breakdowns, use the session_usage_info event instead.
     *
     * @param messages - Chat messages to analyze (defaults to the native chat projection)
     */
    protected computeContextBreakdown(messages?: readonly ChatCompletionMessageParam[]): {
        systemTokens: number;
        conversationTokens: number;
        toolDefinitionsTokens: number;
        totalTokens: number;
    };
    /**
     * Resolve callback for the current `waitForOrphanResolution()` promise.
     * Set while the continuation loop is blocked inside `runAgenticLoop()`,
     * waiting for an external permission or tool response to arrive.
     */
    private _orphanResolutionResolver;
    protected abortController?: AbortController;
    /** Memoized in-flight promise so concurrent callers await the same execution. */
    private _sessionEndHooksPromise;
    /**
     * Opt in to deferred sessionEnd hook execution. When called, sessionEnd hooks
     * will NOT fire at the end of each agentic loop. {@link shutdown} fires them
     * exactly once when the session truly ends and awaits their completion.
     *
     * This is intended for interactive sessions where multiple `send()` calls share
     * one logical session lifetime.
     */
    deferSessionEnd(): void;
    /**
     * Fire `sessionEnd` hooks exactly once. Subsequent calls await the same in-flight
     * promise, ensuring hooks complete before the process exits even when multiple
     * callers race to fire them. Internal-only: external consumers should call
     * {@link shutdown}, which fires deferred hooks and awaits their completion.
     *
     * @param params.reason - Why the session ended
     * @param params.error - Optional error that caused the session to end. Reserved
     *   for internal callers (e.g., {@link shutdown} forwarding an error reason).
     */
    fireSessionEndHooks(params?: {
        reason?: "complete" | "error" | "user_exit";
        error?: Error;
    }): Promise<void>;
    /**
     * Emit a session.shutdown event with the current usage metrics.
     * This event is persisted to events.jsonl.
     *
     * @param shutdownType - Whether this is a routine shutdown or error shutdown
     */
    private _shutdownPromise;
    shutdown(params?: ShutdownParams): Promise<void>;
    protected disposeOwnedFeatureFlagService(): Promise<void>;
    /**
     * Emit a `session.usage_checkpoint` capturing the live per-model prompt-cache
     * state when a completed call has refreshed an expiration since the last flush
     * (#12632). The Rust usage tracker owns the pending flag and gate; this reads
     * and clears it, emitting only when there is cache state to persist.
     */
    protected flushModelCacheCheckpoint(): void;
    private _performShutdown;
    static fromEvents<S extends Session, O extends SessionOptions = SessionOptions>(this: new (coreServices: CoreServices, _options: O) => S, events: SessionEvent[], coreServices: CoreServices, options?: O, resumeOptions?: {
        /**
         * Set when `events` were produced by the strict JSONL load path
         * (the Rust-backed JSONL load path), whose classifier parses every
         * record with serde and rejects the whole load on any lone UTF-16
         * surrogate (`\udXXX`). A successfully loaded event is therefore
         * provably free of lone surrogates in every string and key, so the
         * `sanitizeLoneSurrogatesDeep` deep scan below is a guaranteed no-op
         * and is skipped — it is a pure full-tree character walk over all
         * event data (hundreds of ms on large sessions). Callers whose
         * events did NOT pass that strict validation (e.g. remote/wire
         * sources) must leave this unset so the sanitizer still runs.
         */
        eventsStrictJsonValidated?: boolean;
        /**
         * Stash token from `sessionEventsLoadForResumeJson` redeeming the
         * Rust-parsed copy of the exact same `events` (same order, same
         * filtering). When set, the native event log is hydrated by
         * adopting that stashed parse instead of re-serializing the whole
         * log through `JSON.stringify` for `sessionReplaceEventsSyncJson`
         * to re-parse; on large sessions those two passes dominate resume
         * CPU. Only the validated resume load path may set this, and the
         * caller owns discarding the stash if this method throws before
         * adoption.
         */
        nativeReplayEventsToken?: number;
    }): Promise<S>;
    getSessionRewindManager(): SessionRewindManager | undefined;
    beginRewindTurn(eventId: string, userMessage: string, source?: string): Promise<void>;
    /**
     * The local session-state directory to store rewind snapshots in, or
     * `undefined` when this session is structurally incapable of tracking file
     * changes (a subagent session, or one without local session storage).
     * Requesting tracking for such a session is a caller contract violation
     * rather than a data condition.
     */
    private fileChangeTrackingStatePath;
    /**
     * Whether this session is structurally capable of rewind file-change
     * tracking. A session that merely predates tracking is still "supported":
     * it simply cannot start tracking mid-history.
     */
    supportsFileChangeTracking(): boolean;
    enableFileChangeTrackingForResume(): Promise<ResumeFileChangeTrackingOutcome>;
    fileChangeTrackingWasDurablyActive(): Promise<boolean>;
    private rewindTrackingWasActive;
    /**
     * Returns the current authentication information for this session, if set.
     */
    getAuthInfo(): AuthInfo | undefined;
    /**
     * The concrete model auto-mode resolved to for *this* session (its own token-matched Auto
     * Intent decision when cached, else the standard pick), so concurrent SDK sessions don't
     * read each other's refinement when deriving token limits, compaction thresholds, or display.
     *
     * Only meaningful when this session actually selected Auto (explicitly or via `auto_fallback`,
     * both of which leave `_selectedModel === "auto"`). Concrete-model sessions return `undefined`
     * so they never inherit a concurrent Auto session's process-global standard pick.
     */
    getAutoModeResolvedModel(): string | undefined;
    /**
     * Mint or read back the CAPI auto-mode session token (a `Copilot-Session-Token`
     * JWT) for this session, delegating to {@link AutoModeSessionManager.resolve}
     * (which owns its own cache and refresh logic).
     *
     * Throws if called on a non-CAPI session. Returns `undefined` when CAPI
     * declines to issue a token; resolve errors propagate to the caller.
     */
    getCapiAutoModeToken(): Promise<{
        token: string;
        resolvedModel: string | undefined;
        expiresAt: number | undefined;
    } | undefined>;
    /** Returns a snapshot of the current sub-agent concurrency state. */
    getSubAgentLimiterInfo(): SubAgentLimiterInfo | undefined;
    setNativeHookCallbackRegistration(ownerId: string, registrationId: number): void;
    removeNativeHookCallbackRegistration(ownerId: string): void;
    getNativeHookSessionHandle(): number | undefined;
    listNativeHookResources(): Promise<NativeHookResourceRow[]>;
    getNativePluginHookCount(): number;
    replaceNativeHookSessionHandle(handle: number, reason?: string): void;
    /**
     * Swap in a new hook processor.
     *
     * The outgoing processor is disposed immediately when nothing can still be
     * using it. While a turn is running it is instead *retired*
     * ({@link retiredNativeHookProcessors}): the request that captured it keeps a
     * live native handle for the rest of its life, and is disposed when the
     * session next goes idle. `reason` (when given) is recorded on the outgoing
     * processor so the last-resort fail-closed path can tell the model what
     * actually changed.
     */
    replaceNativeHookProcessor(processor: NativeHookProcessor, ownsHandle?: boolean, reason?: string): void;
    /**
     * Whether an in-flight request may still hold this session's hook processor.
     *
     * A pipeline is captured when the request is assembled and used until the
     * request finishes, so "a turn is active or the queue is being processed" is
     * the conservative envelope. Reads the native liveness scalars defensively:
     * a session whose native half is already gone can hold no live request, and
     * must not throw out of a teardown path.
     */
    private hasRequestBoundToHookProcessor;
    /**
     * Dispose every processor retired by a mid-turn replacement. Safe to call
     * repeatedly; a no-op once the set is empty.
     */
    protected releaseRetiredNativeHookProcessors(reason?: string): void;
    /**
     * Fire notification hooks for a given notification event.
     * Non-blocking callers catch and log failures at the call site.
     */
    protected fireNotificationHook(message: string, notificationType: string, title?: string): Promise<void>;
    /**
     * Gather the serializable pre-update snapshot and delegate to the native
     * `updateOptions` planner. `options` is projected down to the fields the
     * planner inspects so live/callback-bearing options are never serialized;
     * `optionKeys` carries the full key set so `"key" in options` presence
     * semantics survive. The planner validates (and throws) up-front and
     * returns the change-detection/normalization decisions the host applies.
     */
    private buildUpdateOptionsPlan;
    private serializeMcpServersForNative;
    private buildUpdateOptionsNativeFieldValues;
    private refreshUpdateOptionsReferenceCaches;
    private applyLiveUpdateOptionsFieldPlan;
    private applyUpdateOptionsFieldPlan;
    private invalidateLoadedSkillCaches;
    private invalidatePluginDerivedCaches;
    /**
     * Traces which effective-plugin snapshot a given consumer resolved its plugin set from.
     * `fingerprint` is `undefined` when no snapshot is active and the consumer fell back to
     * the legacy per-session `installedPlugins` list.
     */
    private logPluginActivationConsumer;
    /**
     * Drops the cached effective-plugin snapshot and bumps the activation generation so any
     * in-flight resolution started before this change is discarded by {@link updatePluginActivation}
     * instead of overwriting the newer plugin set.
     */
    private invalidatePluginActivationSnapshot;
    private scheduleCustomAgentsLoad;
    private applySandboxConfigUpdatedEffect;
    /**
     * Resolve the sandbox proxy password — a `${secret:…}` keychain reference, a
     * `${VAR}`/`$VAR` environment reference, or a literal — to the real
     * credential and register it (plus the percent-encoded userinfo form and any
     * URL-embedded password) with the global secret filter so a tool can never
     * echo it. Resolution is async (keychain), so the pending work is tracked on
     * `_pendingProxySecretRegistration` and awaited before the turn proceeds (see
     * `initializeMcpHost`); registrations chain so accumulated (rotated)
     * passwords all stay redacted.
     */
    protected registerSandboxProxySecrets(config: SandboxConfig_3 | undefined): void;
    private applyUpdateOptionsEffectPlan;
    /**
     * Updates session options after creation.
     * This method allows selectively updating configuration options without recreating the session.
     * Only the provided options will be updated; omitted options remain unchanged.
     *
     * @param options - Partial session options to update
     *
     * @example
     * ```typescript
     * // Update multiple options at once
     * session.updateOptions({
     *   logger: fileLogger,
     *   mcpServers: mcpConfig,
     *   customAgents: loadedAgents
     * });
     *
     * // Or use capability APIs for focused updates
     * await session.gitHubAuth.setCredentials({ credentials: newAuthInfo });
     * await session.model.switchTo({ modelId: newModel });
     * ```
     */
    updateOptions(options: Partial<UpdatableSessionOptions>, behavior?: UpdateOptionsBehavior): void;
    isSessionTelemetryEnabled(): boolean;
    /**
     * Returns the current telemetry engagement id, if a SessionTelemetry
     * sender is attached and exposes one. Used by the interactive CLI to
     * forward the parent's engagement id to a detached child (rem-agent
     * on shutdown) via env var so the child's telemetry rolls up under
     * the same engagement.
     */
    getEngagementId(): string | undefined;
    setInternalCorrelationIds(internalCorrelationIds: SessionCorrelationIds | undefined): void;
    /** Returns true when a custom (BYOK) provider is configured for this session. */
    hasCustomProvider(): boolean;
    /**
     * Builds and validates the additive BYOK registry from session options.
     * Runs once at construction (after {@link updateOptions} has set the Rust-owned BYOK provider state).
     *
     * Validation (throws on violation):
     * - legacy singular `provider` may not be combined with the `providers`/`models` registry;
     * - every `model.provider` must reference a declared provider name;
     * - model selection ids (provider-qualified `provider/id`) must be unique;
     * - duplicate provider names are rejected.
     */
    private initByokRegistry;
    registerByokEntries(providers: readonly NamedProviderConfig[], models: readonly ProviderModelConfig[]): Model[];
    /**
     * Backing implementation of the `session.provider.getEndpoint` host effect.
     * Gated behind {@link ENABLE_ENV_VAR} because some hosts have no use for the
     * API and may prefer not to make it easier to obtain the session's tokens.
     *
     * Two shapes: a BYOK session returns the planned custom-provider endpoint; a
     * CAPI session returns the Copilot endpoint, minting a short-lived session
     * token when running in auto mode with no explicit `modelId` override.
     */
    private runProviderGetEndpointHostEffect;
    private buildByokProviderEndpoint;
    private endpointFromProviderPlan;
    /** True when this session has at least one registry BYOK model. */
    hasByokRegistry(): boolean;
    /**
     * Public predicate: true when `modelId` names a registry BYOK model. Used by request
     * boundaries (server validation, `switchTo`) to skip CAPI model-policy checks for a
     * selection that the BYOK registry — not the CAPI registry — is responsible for.
     */
    isByokSelection(modelId: string | undefined): boolean;
    /** True when `selectionId` names a registry BYOK model (keys off the registry only). */
    protected isByokModel(selectionId: string | undefined): boolean;
    /**
     * Decide whether reasoning/encrypted fields should be stripped when resuming
     * this session.
     *
     * Default (unchanged): always strip. Copilot/CAPI encrypted reasoning is
     * session-bound and invalid after resume.
     *
     * The `COPILOT_STRIP_REASONING_ON_RESUME` env var overrides this:
     * - truthy -> always strip;
     * - falsy -> keep reasoning across resume (e.g. for BYOK providers whose
     *   reasoning is not tied to a Copilot session).
     *
     * This is intentionally an opt-in escape hatch rather than a behavior change
     * keyed off the provider. When kept, reasoning is preserved as-is; callers who
     * resume with a different model/provider are responsible for that choice (this
     * mirrors mid-session model switches, which already retain prior reasoning).
     */
    protected shouldStripReasoningOnResume(): boolean;
    /**
     * True when this session can serve at least one model backend: CAPI auth, a legacy
     * custom provider, or a non-empty BYOK registry. CAPI-only operations still require
     * `authInfo` separately.
     */
    protected hasModelBackend(): boolean;
    /**
     * Resolves a user-selected model id to its backend. The backend is decided by the
     * selection: a provider-qualified registry BYOK selection id resolves to `byok`;
     * every bare id (including the virtual `auto` id and any CAPI id) resolves to `capi`.
     */
    protected resolveModelBackend(selectionId: string): ResolvedModelBackend;
    /** Returns the synthesized BYOK Model entries (for the model-list merge). */
    getByokModelEntries(): Model[];
    /**
     * Appends the synthesized BYOK entries to a CAPI model list for presentation /
     * validation / subagent-candidate purposes. BYOK entries carry provider-qualified
     * ids, so they never collide with bare CAPI ids and the lists simply concatenate.
     * The merged list must NOT be cached into `modelListCache` (which stays CAPI-only
     * for backend-qualified metadata lookups).
     */
    mergeByokModelList(capiModels: Model[]): Model[];
    setTelemetryFeatureOverrides(overrides: Record<string, string>): void;
    /** Set the resolver for OTel trace context propagation on MCP tool calls. */
    setMcpTraceContextResolver(resolver: TraceContextResolver | undefined): void;
    protected createMcpToolCallInterceptor(): McpToolCallInterceptor;
    /**
     * Send a telemetry event if telemetry is configured.
     * This is a no-op if no telemetry sender was set.
     *
     * @param event - The telemetry event to send
     */
    sendTelemetry(event: TelemetryEvent_2): void;
    protected forwardModelTelemetryEvent(event: Event_2): void;
    protected disposeUserMessageSentimentTelemetry(): void;
    protected disposeTaskCompletionCriteriaTelemetry(): void;
    private customAgentSidecarKey;
    private isReservedCustomAgent;
    private stringifyCustomAgents;
    private stringifyCustomAgent;
    private rememberCustomAgentCallbacks;
    private restoreCustomAgentCallbacks;
    private parseCustomAgentsJson;
    /**
     * Get list of available custom agents.
     * Returns the loaded custom agents, or session-provided custom agents while the discovery cache is empty.
     *
     * @returns Array of available custom agents
     */
    getAvailableCustomAgents(): SweCustomAgent[];
    protected get customAgents(): SweCustomAgent[] | undefined;
    protected set customAgents(agents: SweCustomAgent[] | undefined);
    protected get providedCustomAgents(): SweCustomAgent[] | undefined;
    setAgentPrompt(id: string, prompt: string): Promise<void>;
    /**
     * Get available models for agent validation (model warnings).
     * Returns undefined by default; overridden in LocalSession to fetch from API.
     */
    protected getAvailableModelsForAgentValidation(): Promise<Model[] | undefined>;
    /**
     * Get the currently selected custom agent.
     *
     * @returns The selected custom agent, or undefined if using the default agent
     */
    getSelectedCustomAgent(): SweCustomAgent | undefined;
    /**
     * Map a runtime custom agent to the wire {@link AgentInfo} shape returned by
     * the `session.agent.*` RPCs. Mirrors the pre-port `sessionAgentApi` mapping:
     * `id` defaults to `name` when no distinct id was assigned, and the
     * runtime-only callback fields (`prompt`, `buildSystemPrompt`, …) are dropped.
     */
    private toWireCustomAgentInfo;
    private toMissionControlAgentInfo;
    private toWireAgentInfo;
    protected get selectedCustomAgent(): SweCustomAgent | undefined;
    protected set selectedCustomAgent(agent: SweCustomAgent | undefined);
    /**
     * Per-instance snapshot of the tool-filter scalars.
     *
     * Subagents reuse the parent's sessionId and therefore share one native
     * session entry, so constructing a later subagent rebuilds that entry and
     * overwrites the shared tool-filter scalars. Main kept these values as
     * per-instance fields; caching them on the owning instance preserves that
     * per-instance view even after a sibling/descendant clobbers the shared
     * native slot. The cache is refreshed whenever this instance legitimately
     * changes its filters (updateOptions or the setters below) and is lazily
     * initialized on first read after construction.
     */
    private _toolFilterStateCache?;
    protected refreshToolFilterStateCache(): void;
    private toolFilterStateCache;
    protected get availableTools(): string[] | undefined;
    protected set availableTools(value: string[] | undefined);
    protected get excludedTools(): string[] | undefined;
    protected set excludedTools(value: string[] | undefined);
    protected get toolFilterPrecedence(): ToolFilterPrecedence | undefined;
    protected get defaultAgentExcludedTools(): string[] | undefined;
    protected set defaultAgentExcludedTools(value: string[] | undefined);
    /**
     * Get the SDK client name for this session.
     * This identifies the SDK consumer (e.g., "autopilot", "sdk").
     */
    getClientName(): string | undefined;
    protected get clientName(): string | undefined;
    getClientKind(): SessionClientKind | undefined;
    getRunningInInteractiveMode(): boolean | undefined;
    getCopilotUrl(): string | undefined;
    getIntegrationId(): string | undefined;
    /** Core services bundle, used to spin up ephemeral generation sessions (e.g. schedule parsing). */
    getCoreServices(): CoreServices;
    /** Custom (BYOK) provider configuration, when one is set. */
    getProviderConfig(): ProviderConfig | undefined;
    /**
     * Get the custom configuration directory for this session.
     * When set, this overrides the default Copilot config directory (~/.copilot or $COPILOT_HOME).
     *
     * @returns The custom configuration directory, or undefined if using the default
     */
    getConfigDir(): string | undefined;
    getSettingsStorageContext(): SettingsStorageContext | undefined;
    /**
     * The directory that holds this process's `process-*.log` files, granted
     * read-only to the sandbox for Feedback Hub log collection (issue #13274 review).
     *
     * Prefers the running logger's actual output location — which honors the CLI
     * `--log-dir` option and is fixed at process startup, so it points at where the
     * logs are really written regardless of any later `configDir` change — and falls
     * back to the default `<copilotHome>/logs` when no file logger is attached (e.g.
     * SDK consumers).
     */
    protected resolveProcessLogDir(): string;
    /**
     * Get all tracked task summaries for this session.
     * Returns a unified array with type discriminator for each task.
     *
     * NOTE: Despite the name, this returns both sync and background tasks.
     * Consider renaming to `getTrackedTasks` (along with the `BackgroundTask`
     * type and `session.background_tasks_changed` event) in a follow-up.
     */
    getBackgroundTasks(): BackgroundTask[];
    /**
     * Inject a factory on the shared {@link LSPClientFactory} singleton that
     * records each spawned LSP server's lifecycle as a `service` task in this
     * session's {@link TaskRegistry}. Wired once at construction so it is in
     * place before any LSP client is created (including by the CLI's warmup hook).
     */
    private wireLspServiceReporterFactory;
    /**
     * Tear down the LSP service reporter factory wired in
     * {@link wireLspServiceReporterFactory}, so a finished session stops
     * recording new LSP `service` tasks into its (now defunct) registry.
     */
    private unwireLspServiceReporterFactory;
    /**
     * Live snapshot of long-lived background services (e.g. LSP servers) tracked
     * in the {@link TaskRegistry}. Kept separate from {@link getBackgroundTasks}
     * so services do not appear in `/tasks` or inflate task counts; the `/lsp logs`
     * panel consumes this instead. Refreshed by CLI consumers on
     * `session.background_tasks_changed`.
     */
    getServiceTasks(): ServiceTask[];
    /**
     * Cheap count of LSP services still initializing (registry status
     * `running`), without materializing or copying any server logs. Backs the
     * "N LSP servers initializing" statusbar hint, which refreshes on every
     * forwarded log line during a chatty startup — {@link getServiceTasks} would
     * deep-copy every service's (growing) log on each of those events.
     */
    getInitializingServiceCount(): number;
    /**
     * Whether a tracked task can currently be promoted into background mode.
     */
    canPromoteTaskToBackground(taskId: string): boolean;
    /**
     * Get the currently-promotable sync task, if any.
     */
    getCurrentPromotableTask(): PromotableTask | undefined;
    /**
     * Promote a tracked task into background mode.
     *
     * Returns false for unknown tasks or tasks that are not
     * currently eligible for promotion.
     */
    promoteTaskToBackground(taskId: string): boolean;
    /**
     * Promote the currently-awaited sync task into background mode.
     */
    promoteCurrentTaskToBackground(): BackgroundTask | undefined;
    /**
     * Returns the current set of available tools as {@link ToolMetadata} objects.
     * This strips non-serializable properties (callback, shutdown, summariseIntention)
     * from the full Tool objects.
     */
    getToolDefinitions(): ToolMetadata[];
    /**
     * Emits a notification that the current tool definitions changed.
     */
    notifyToolDefinitionsChanged(): void;
    protected emitToolDefinitionsChanged(model?: string): void;
    protected getExternalToolMetadata(definitions: readonly ExternalToolDefinition[] | undefined): ToolMetadata[];
    protected getToolSearchExternalOverride(definitions?: readonly ExternalToolDefinition[] | undefined): ExternalToolDefinition | undefined;
    protected getModelVisibleExternalToolDefinitions(definitions: readonly ExternalToolDefinition[] | undefined): ExternalToolDefinition[];
    protected getValidOverridingExternalToolNames(): Set<string>;
    /**
     * Returns the agent-tool spec used by `clearDeferralForAgentTools`: either the
     * selected custom agent, or a synthetic spec derived from `requestedTools`
     * when no custom agent is selected. Returns `undefined` when neither is set.
     */
    protected getAgentToolSpec(): {
        tools?: string[] | null;
        deferredToolLoading?: boolean;
    } | undefined;
    private updateCachedExternalToolMetadata;
    /**
     * Registers a callback that is invoked whenever the set of available tools changes.
     * The callback receives the current tool definitions and the model they were resolved for.
     *
     * @param callback - Called with the current tools and model on each update
     * @returns A function that unsubscribes the callback
     */
    onToolsUpdate(callback: (tools: ToolMetadata[], model: string) => void): () => void;
    private getToolCallSummariesForTask;
    /**
     * Gets progress information for a background task.
     * For agent tasks, derives progress from session events correlated by agent id or parent tool call id.
     * For shell tasks, reads recent output from the live shell session or detached log.
     *
     * @param task - The background task to get progress for
     * @returns Progress information discriminated by task type
     */
    getBackgroundTaskProgress(task: BackgroundTask): Promise<BackgroundTaskProgress>;
    protected emitAssistantIntent(intent: string): void;
    /**
     * Emits `task_complete_todo_state` telemetry so we can measure how often
     * `task_complete` fires while the session still has open TODOs (any todo
     * whose status is not `done`). Counts only — never todo content — mirroring
     * the PII-safe metric pattern used elsewhere. Safe to call fire-and-forget:
     * a missing workspace or a DB error is swallowed and never blocks the agent
     * completing its task.
     *
     * @param mode - The session mode captured *before* `session.task_complete`
     * was emitted. It must be snapshotted at the call site because the emit runs
     * handlers synchronously (e.g. `AutopilotObjectiveRegistry` reverts an
     * objective-originated autopilot session back to interactive), so reading
     * `this.currentMode` here would misreport the mode at completion.
     */
    protected emitTaskCompleteTodoStateTelemetry(mode: SessionMode): void;
    protected refreshIntentFromSessionSql(toolName: string | undefined, toolArgs: unknown, parentToolCallId?: string): Promise<void>;
    /**
     * Returns a richer timeline of bridged events for a subagent task. Unlike
     * {@link getBackgroundTaskProgress} (which only surfaces tool executions
     * and truncates aggressively for the /tasks list view), this accessor
     * returns one entry per logical event suitable for rendering a full
     * scrollable timeline in the /tasks detail view.
     *
     * Coverage matches the bridge in {@link createSubagentSession} -- only
     * events bridged onto the parent session with `agentId` are visible:
     * - `assistant.message` -> `assistant`
     * - `tool.execution_start` (without matching complete) -> `tool_inflight`
     * - `tool.execution_complete` -> `tool_done` (collapses with prior start)
     * - `skill.invoked` -> `skill`
     * - `subagent.started` / `subagent.completed` / `subagent.failed` -> `lifecycle`
     *
     * Entries from `hook.start` / `hook.end` are dropped because they are
     * protocol noise rather than user-meaningful work.
     *
     * @param task - The agent task whose timeline to derive.
     * @returns Timeline entries in chronological order.
     */
    getSubagentTimeline(task: AgentTask): SubagentTimelineEntry[];
    /**
     * Cancel a background task by ID.
     * For agents, this cancels the execution.
     * For shell tasks, this stops the running command and marks detached or attached
     * shell tasks cancelled.
     *
     * @param taskId - The task ID (agent ID or shell ID)
     * @returns true if the task was found and cancelled, false otherwise
     */
    cancelBackgroundTask(taskId: string): Promise<boolean>;
    /**
     * Refresh the status of all background tasks.
     * This refreshes detached shell status by checking whether their processes are
     * still running. Agent and attached-shell status changes are pushed directly by
     * their runtime callbacks.
     */
    refreshBackgroundTasks(): Promise<void>;
    /**
     * Remove a finalized background task from tracking.
     * Only removes tasks that are not running (completed, failed, or cancelled).
     *
     * @param taskId - The task ID (agent ID or shell ID)
     * @returns true if the task was found and removed, false otherwise
     */
    removeBackgroundTask(taskId: string): boolean;
    /**
     * Returns the cached ToolConfig for this session, if available.
     * Override in subclasses that cache tool configuration.
     */
    protected getToolConfig(): ToolConfig | undefined;
    private getEffectiveBuiltinAgentPolicy;
    /**
     * The session's access-filtered model catalog (`ToolConfig.availableModels`),
     * exposed for prompt builders such as `/chronicle cost-tips` that need to name
     * specific cheaper, *accessible* models and stay silent on `/model` when the
     * user has no alternative. Returns `undefined` when no tool config is available.
     */
    getAvailableModelInfoForPrompt(): AvailableModelInfo[] | undefined;
    protected invalidateStaleBuiltinAgentToolConfig(): void;
    private clearSelectedBuiltinAgentIfDisallowed;
    /**
     * Invalidates cached tool configuration after the effective agent set changes.
     */
    protected invalidateAgentToolConfig(): void;
    /** Marks cached command availability derived from model, rollout, settings, and agent policy as stale. */
    protected invalidateRubberDuckAvailability(): void;
    updateSubagentSettings(subagentSettings: UserSettings["subagents"] | undefined): void;
    /**
     * Prepare a background agent task without creating its task identity.
     *
     * Delegates to {@link TaskRegistry.startAgent}, which is shared with the
     * task tool, avoiding duplication of agent-launch / multi-turn wiring.
     *
     * Slow model and tool resolution happens here so callers can serialize only
     * the short identity commit with their own accounting state.
     *
     * @returns A prepared task whose commit creates and registers the agent identity
     * @throws If tools are not initialized or the agent type / model is invalid
     */
    prepareSubagent(params: {
        agentType: string;
        prompt: string;
        name: string;
        description?: string;
        model?: string;
        factoryRunId?: string;
        factoryUsageRunId?: string;
        factoryUsageCoordinator?: FactoryUsageCoordinator;
        suppressMultiTurn?: boolean;
    }): Promise<{
        resolvedModel?: string;
        commit(): string;
    }>;
    commitPreparedSubagent(prepared: {
        commit(): string;
    }): Promise<string>;
    /**
     * Start a background agent task from the SDK/shared API layer.
     *
     * Uses the session registry directly so API-created agents share task
     * lifecycle and multi-turn behavior with task-tool agents.
     *
     * @returns The generated agent ID for the background task
     * @throws If tools are not initialized or the agent type / model is invalid
     */
    startSubagent(params: Parameters<Session["prepareSubagent"]>[0]): Promise<string>;
    /**
     * Notify listeners that background tasks have changed.
     * Called internally when tasks start or complete.
     */
    protected notifyBackgroundTaskChange(): void;
    queueFactoryCompletionNotification(record: FactoryCompletionNotificationRecord | Promise<FactoryCompletionNotificationRecord>, _lifecycle: FactoryCompletionNotificationLifecycle, _fallback: FactoryCompletionNotificationFallback): void;
    invalidateFactoryCompletionNotification(_runId: string): void;
    registerBackgroundWorkPredicate(predicate: () => boolean): () => void;
    protected hasRegisteredBackgroundWork(): boolean;
    /** Hook called after compaction replaces chat messages. Override to reset per-turn dedup state. */
    protected onCompactionApplied(): Promise<void>;
    protected onUsageMetricsUpdated(_event: SessionEvent): void;
    protected inheritResponseLimitsForSubagent(_session: Session): void;
    protected getRuntimeSettings(): RuntimeSettings_2;
    protected getModelResolverSettings(): RuntimeSettings_2;
    /**
     * Resolves the user-settings `effortLevel` fallback exactly once per session.
     * Request-time model resolution uses this instead of re-reading settings from
     * disk so the effective reasoning effort of a session with an unpinned effort
     * is fixed for the session's lifetime (per-session isolation): a `/model`
     * change in another live session persists a new global default without
     * retroactively changing this session's requests.
     */
    protected getSettingsEffortLevelSnapshot(): Promise<string | undefined>;
    protected getCurrentSettingsForHandle(): RuntimeSettings_2;
    protected clearAutoModeSessionTokenFromSettings(): void;
    protected clearCachedAutoModeSessionTokenFromSettings(): void;
    protected overlayCurrentSessionSettingsForHandle(settings: RuntimeSettings_2): RuntimeSettings_2;
    private serializeSettingsJson;
    protected disposeSettingsHandle(): void;
    /**
     * Resolves the repository name to use for settings.
     * Returns the explicitly configured repositoryName if set,
     * otherwise attempts to detect it from the git remote in the working directory.
     *
     * @returns The repository name in "owner/repo" format, or undefined if not available
     */
    protected resolveRepositoryName(): Promise<string | undefined>;
    protected get repositoryName(): string | undefined;
    protected resolveCapiRepositoryContext(): Promise<CAPIRepositoryContext>;
    /**
     * Select a custom agent for subsequent queries.
     * When a custom agent is selected, only that agent's tools (and required tools) will be available.
     * The selected custom agent will still be available via the task tool.
     *
     * @param agentId - The name/id of the custom agent to select
     * @throws Error if the agent is not found
     */
    selectCustomAgent(agentId: string): Promise<void>;
    /**
     * Clear custom agent selection.
     * After calling this, all tools will be available again.
     */
    clearCustomAgent(): void;
    /**
     * Attempts to load a built-in YAML agent by normalized id.
     * Matches against `{name}.agent.yaml` ids and bare `{name}` for convenience.
     * Returns undefined if no matching built-in agent is found.
     */
    private tryLoadBuiltinYamlAgent;
    /**
     * Registers an event handler for specific event types or all events.
     * Supports both synchronous and asynchronous handlers.
     *
     * @param eventType - The event type to listen for (e.g., "assistant.message", "tool.execution_complete") or "*" for all events
     * @param handler - The handler function to call when the event is emitted. Can be sync or async.
     * @param options - Optional configuration. `includeSubAgents` (default false for typed handlers) controls whether events from sub-agents are delivered.
     * @returns A function that unsubscribes the handler when called
     */
    on<K extends EventType>(eventType: K, handler: EventHandler<K>, options?: {
        includeSubAgents?: boolean;
    }): () => void;
    on(eventType: "*", handler: WildcardEventHandler): () => void;
    /**
     * Emits an event to all registered handlers.
     * Automatically generates event fields (id, timestamp, parentId). Non-ephemeral events
     * are added to the session history; ephemeral events are dispatched to handlers but
     * never stored in the durable event stream.
     *
     * @param eventType - The type of event to emit
     * @param data - The event data payload
     * @param ephemeral - Whether this event is ephemeral (not stored in events array, default: false)
     * @returns The generated event ID
     */
    private emitInternal;
    /**
     * Emits an event to all registered handlers.
     * Automatically generates event fields (id, timestamp, parentId) and adds the event to the session history.
     * Triggers both legacy callbacks and new-style event handlers. Does not allow emitting ephemeral events.
     *
     * @param eventType - The type of event to emit
     * @param data - The event data payload
     */
    emit<K extends EventType>(eventType: EventPayload<K>["ephemeral"] extends true ? never : K, data: EventData<K>, agentId?: string): string;
    /**
     * Emits an ephemeral event (not persisted to disk).
     * Convenience method that calls emit() with ephemeral = true.
     *
     * @param eventType - The type of event to emit
     * @param data - The event data payload
     */
    emitEphemeral<K extends EventType>(eventType: EventPayload<K>["ephemeral"] extends false ? never : K, data: EventData<K>, agentId?: string): string;
    /**
     * Narrows a hook-supplied replacement value to a string.
     *
     * Hook output is untrusted: declarative command/http hooks return arbitrary
     * JSON and SDK-registered callbacks return arbitrary JS values. These fields
     * replace content that every downstream contract declares as a required
     * string, so a non-string value would be persisted verbatim into the
     * session's events and make the whole file unloadable on the next resume. A
     * non-string override is therefore dropped, matching how the native prompt
     * planner treats a non-string `modifiedPrompt`.
     *
     * An absent value is a silent no-op, whether it arrives as `undefined` from
     * a hook that omits the key or as `null` from one that emits it every turn
     * with nothing to say (a `jq` conditional that did not fire). Neither is a
     * mistake, so diagnosing them would warn on every turn of a correctly
     * written hook. Only a value that is present and unusable is reported: a
     * value of the wrong type, or an empty string.
     *
     * An empty string is rejected rather than applied because these fields
     * replace content that must stay non-empty: an empty
     * `modifiedTransformedPrompt` would be persisted verbatim and leave the
     * model with no user content at all for that turn, which is worse than the
     * `null` case. It is also an easy accident for a shell hook interpolating an
     * unset variable, so unlike `null` it is diagnosed rather than silent, and
     * it matches `responseContent`, which already treats an empty string as
     * absent.
     *
     * The drop is surfaced twice: to the CLI log for a post-mortem, and as a
     * session warning so the author sees it at the moment their override stops
     * taking effect rather than mistaking it for a hook that never ran. Only the
     * field name and the received type are reported, never the value, because
     * hook output can carry user content.
     */
    protected narrowHookOverride(value: unknown, hookField: HookStringField): string | undefined;
    protected emitModelCallFailure(event: ModelCallFailureEvent_3, source: ModelCallFailureSource, agentId?: string, isByokOverride?: boolean): void;
    /**
     * Returns all events that have occurred in the session.
     * Events are returned in chronological order and include all session lifecycle, user messages,
     * assistant responses, tool executions, and other session events.
     *
     * @returns A readonly array of all session events
     */
    getEvents(): readonly SessionEvent[];
    /**
     * Number of durable events, without materializing them.
     *
     * `getEvents().length` answers the same question by serializing the entire
     * native log, marshalling it across the napi boundary, and parsing it in
     * V8 — work proportional to the log's *bytes* for an answer that is one
     * integer. Callers that only need the count (resume telemetry, "does this
     * session have any history") must use this instead; on a large resumed
     * session it is the difference between a sub-microsecond read and a
     * multi-hundred-millisecond round trip.
     */
    getEventCount(): number;
    /**
     * Drop the materialized event graph. It is only a cache of the native log,
     * but on a long session it is hundreds of megabytes, so disposal releases
     * it rather than pinning the whole history in V8 behind a retained
     * `Session` object.
     */
    protected clearEventSnapshotCache(): void;
    /**
     * Adopt `events` as the cached snapshot when they are provably what the
     * native durable log now holds.
     *
     * Resume has just parsed the whole log into JS objects in order to rebuild
     * session state, and then installed those same events natively. Without
     * this, the very next `getEvents()` / `getInitialEvents()` — the CLI's
     * timeline seed on a cold resume — would serialize that log straight back
     * out of Rust and re-parse an identical copy in V8, doubling both the time
     * and the peak memory of resuming a large session.
     *
     * The length check is the proof obligation. The native replace commits the
     * replacement together with any events that were emitted concurrently
     * (`apply_replaced_event_projection`), so a differing count means the log
     * is not exactly `events` and the seed is skipped, leaving the normal
     * fetch-on-demand path. Length and tokens come from one locked read, so
     * they cannot describe different states of the log.
     */
    protected seedEventSnapshotCache(events: readonly SessionEvent[]): void;
    /**
     * How many durable events of `eventType` the log holds for the primary
     * agent (events carrying an `agentId` — a subagent's — are not counted).
     *
     * Counted in the runtime. Callers must not rebuild this from
     * {@link getEvents}: filtering in JavaScript forces the whole log to be
     * materialized, which is the cost this class of accessor exists to avoid.
     */
    countPrimaryEventsOfType(eventType: SessionEvent["type"]): number;
    /**
     * Materialize the durable event log as JS objects, reusing the previous
     * result while the native log is provably unchanged.
     *
     * Every materialization serializes the native `Value` DOM to JSON,
     * marshals that string into V8, and re-parses it — on a long session that
     * is hundreds of megabytes and hundreds of milliseconds *per call*. Resume
     * alone used to pay it about a dozen times (the resume-event count, the
     * file-change-tracking probe, the CLI's prior-user-turn / model-snapshot /
     * auto-mode probes, the timeline seed), which is why resuming a large
     * session was dominated by re-reading state that had not changed.
     *
     * Correctness rests on two tokens the runtime draws from one
     * process-global counter, so neither ever repeats — not even after a
     * session id is removed and re-registered, which a per-core counter would
     * restart and make a stale snapshot look current. The *version* moves on
     * every durable mutation and never on ephemeral emits, so a streaming turn
     * cannot invalidate the cache. The *epoch* moves only when the log is
     * rewritten wholesale (resume hydration, compaction truncation, eviction),
     * which is what makes "the tail alone brings me up to date" a proof rather
     * than a heuristic: within an epoch the log is append-only, so any earlier
     * snapshot is a prefix of any later one. The runtime reads tokens and
     * events under one lock, so the tokens always describe exactly the events
     * returned with them.
     *
     * The returned array is shared between callers, matching the `readonly`
     * contract of {@link getEvents} and {@link getInitialEvents}: consumers
     * filter, slice, and scan it but must not mutate it in place.
     */
    private materializeEventSnapshot;
    /**
     * Objective-era completion tool evidence — the bounded tool-execution summary
     * used to seed the independent completion reviewer's prompt — derived entirely
     * in the native runtime off the Node main thread. The host no longer parses or
     * walks the unbounded event history on each `task_complete`; the native side
     * returns only the already-capped evidence (newest 200 distinct entries).
     * `sinceTimestamp` is the candidate objective's `createdAt`.
     */
    protected getAutopilotCompletionEvidence(sinceTimestamp: string): Promise<AutopilotCompletionToolEvidence[]>;
    /**
     * Sample the completion reviewer's conversation context: the user's own
     * recent asks this session, oldest to newest. Unlike the tool evidence this
     * is NOT scoped to the current objective era — it spans task/objective
     * boundaries so the reviewer can interpret a terse objective against an
     * earlier ask (the subject/scope carried over from a prior turn). The native
     * extractor keeps only genuine user asks and bounds the window.
     */
    protected getAutopilotConversationContext(): Promise<string[]>;
    acceptNativeSessionEvent(event: SessionEvent): void;
    /**
     * Records a native-plan-originated event (the `user.message` /
     * `system.notification` yielded by the immediate-prompt pre-request plan)
     * into the durable event log and projects it into chat message history.
     *
     * The pre-port `ImmediatePromptProcessor.preRequest` produced these events
     * with `this.emit(...)`, which persists them to history (they are read back
     * from `getChatMessages()` and pushed onto the request). The native
     * pre-request plan only *builds* the event — it does not record it — so
     * unlike an event the native session already recorded (handled by
     * {@link acceptNativeSessionEvent}, which must not double-record), an
     * immediate-prompt event must be recorded here. Otherwise a later request
     * rebuilt from history (e.g. an autopilot-continuation or a fresh run)
     * would be missing the injected message and diverge from the pre-port
     * conversation.
     */
    protected recordImmediatePromptEvent(event: SessionEvent): SessionEvent;
    private dispatchEventHandlers;
    getInitialEvents(): readonly SessionEvent[];
    getInitializedTools(): readonly Tool[];
    /**
     * Truncates the session to a specific event, removing all events after it.
     * This clears and rebuilds the internal state (chat messages, etc.) from the remaining events.
     *
     * Note: This only affects in-memory state. The caller is responsible for
     * persisting the truncation to disk via native history persistence.
     *
     * @param upToEventId - The event ID to truncate to (this event is excluded)
     * @returns The number of events removed
     */
    truncateToEvent(upToEventId: string): Promise<{
        eventsRemoved: number;
    }>;
    /**
     * Returns conversation messages reconstructed from session events.
     * Messages are processed asynchronously in order to handle attachments and ensure consistency.
     * Excludes system/developer prompt snapshots, which are available via getSystemContextMessages().
     *
     * @returns A Promise that resolves to a readonly array of chat completion messages
     * ```
     */
    getChatMessages(): Promise<readonly ChatCompletionMessageParam[]>;
    /**
     * Returns chat messages that are part of the replayable conversation context.
     * Useful for displaying the user/assistant conversation without system/developer prompts.
     *
     * @returns A Promise that resolves to an array of user, assistant, and tool messages
     */
    getChatContextMessages(): Promise<ChatCompletionMessageParam[]>;
    getChatContextMessageSources(): Promise<readonly (MessageSource | null)[]>;
    /**
     * Returns the latest system/developer prompt snapshots known to the session.
     * Useful for inspecting the instructions sent to the model without mixing them
     * into the replayed conversation history.
     *
     * @returns A Promise that resolves to an array of system/developer messages
     */
    getSystemContextMessages(): Promise<ChatCompletionMessageParam[]>;
    /**
     * Returns the list of skills that have been invoked in this session.
     * Used for restoring skill permissions on session resume and for compaction.
     *
     * @returns A readonly array of invoked skill information
     */
    getInvokedSkills(): readonly InvokedSkillInfo[];
    protected getOriginalUserMessagesSnapshot(): string[];
    /**
     * Human-authored user messages (oldest-to-newest) used as the auto-approval
     * judge's `[user]` authorization evidence. Narrower than
     * {@link getOriginalUserMessagesSnapshot}: it excludes `agent-` messages and
     * autopilot continuations, and includes `command-`/`schedule-` prompts.
     */
    protected getAutoApprovalHumanUserMessagesSnapshot(): string[];
    /**
     * Returns the current system message used in the most recent agent turn.
     * This is the full system prompt that was sent to the model.
     *
     * @returns The system message string, or undefined if not yet initialized
     */
    getCurrentSystemMessage(): string | undefined;
    get currentSystemMessage(): string | undefined;
    set currentSystemMessage(value: string | undefined);
    /**
     * Returns the exact custom-instructions prompt section included in the current system message.
     *
     * @returns The rendered custom-instructions section, or undefined when it is unavailable or transformed
     */
    getCurrentCustomInstructionsMessage(): string | undefined;
    get currentCustomInstructionsMessage(): string | undefined;
    set currentCustomInstructionsMessage(value: string | undefined);
    private getPromptContextMessagesSnapshot;
    /**
     * Returns lightweight tool metadata for token counting.
     * Used by /context command to calculate token usage.
     *
     * @returns The array of tool metadata, or undefined if not yet initialized
     */
    getCurrentToolMetadata(): ToolMetadata[] | undefined;
    /**
     * Returns the currently selected model for this session.
     * The model may change during a session if `setSelectedModel` is called.
     *
     * @returns A Promise that resolves to the model identifier string, or undefined if no model is set
     */
    getSelectedModel(): Promise<string | undefined>;
    protected getSelectedModelState(): string | undefined;
    protected getModelSelectionVersion(): number;
    protected setSelectedModelState(model: string | undefined): void;
    /**
     * Returns the current reasoning effort level for this session.
     *
     * @returns The reasoning effort level, or undefined if not set
     */
    getReasoningEffort(): ReasoningEffort | undefined;
    /**
     * Returns the context tier selected for this session.
     * "default" uses the lower context window, "long_context" uses the full native window.
     *
     * @returns The context tier, or undefined if not set
     */
    getContextTier(): ContextTier_3 | undefined;
    /**
     * Returns the current output verbosity level for this session.
     *
     * @returns The verbosity level, or undefined if not set
     */
    getVerbosity(): Verbosity_2 | undefined;
    /**
     * Returns the configured session limits.
     *
     * @returns The session limits, or undefined if no limits are configured.
     */
    getSessionLimits(): SessionLimitsConfig_3 | undefined;
    /**
     * Returns a redacted, secret-free snapshot of the session's runtime settings
     * for boundary consumers (CLI/apps). Secrets are excluded.
     */
    getSettingsSnapshot(): SessionSettingsSnapshot;
    getSettingsSecretValue(name: RuntimeSettingsSecretName): string | undefined;
    evaluateSettingsPredicate(name: SessionSettingsPredicateName, toolName?: string): boolean;
    /**
     * Returns the current reasoning summary mode for this session.
     *
     * @returns The reasoning summary mode, or undefined if not set
     */
    getReasoningSummary(): ReasoningSummary_2 | undefined;
    /**
     * Ids of the durable events {@link resolveEventBinariesForExternalConsumer}
     * could actually rewrite, computed in the runtime over the native log.
     *
     * A pre-filter for consumers that externalize a whole log at once. Without
     * it every event pays a `JSON.stringify` of its payload plus a napi round
     * trip just to be told it has no binary references — on a 74k-event session
     * that is ~400 ms of the resume to discover that 18 events matter. The
     * runtime deliberately returns a superset, so an event in the set may still
     * resolve to itself; only events NOT in the set are guaranteed unchanged
     * and safe to skip.
     */
    getExternalBinaryResolutionEventIds(): ReadonlySet<string>;
    /**
     * Resolves any binary-asset references on an event back to inline binary,
     * for EXTERNAL consumers (SDK/remote streams + reads) that don't maintain
     * their own asset registry and would otherwise receive a bare reference
     * whose `session.binary_asset` event they may never have seen.
     *
     * Returns the event unchanged when it carries no references. Internal
     * persistence / `getEvents()` / fork intentionally keep the reference-bearing
     * form (that's where the de-duplication lives); this resolution is applied
     * only at the external-serialization boundary.
     */
    resolveEventBinariesForExternalConsumer(event: SessionEvent): Promise<SessionEvent>;
    /**
     * Interns the model-facing bytes of byte-forwarding `user.message`
     * attachments into `session.binary_asset` events and freezes tagged-file
     * fallback lines so replay can reproduce the original prompt without
     * re-reading changed or deleted files.
     */
    protected internAttachmentsAndEmitAssets(attachments: Attachment[] | undefined, ctx?: {
        supportedNativeDocumentMimeTypes?: ReadonlySet<string>;
        nativeDocumentPathFallbackPaths?: ReadonlySet<string>;
    }, agentId?: string): Promise<Attachment[] | undefined>;
    internAndFreezeAttachmentsForEmit(attachments: Attachment[] | undefined, agentId?: string): Promise<Attachment[] | undefined>;
    /**
     * Clears all conversation messages from context while preserving the session.
     * System and developer messages are preserved.
     *
     * @param initialMessage - First user message of the fresh context window.
     *   It is NOT sent from here: it is stashed and delivered by the enclosing
     *   turn driver, which enqueues it once the agentic loop exits (see
     *   `finalizePendingClearContextMessage`). It is therefore only meaningful
     *   when this method is called from inside an agentic turn - which the
     *   `session.history.clearContext` RPC enforces before it ever gets here.
     *   Called on an IDLE session there is no turn driver to deliver the seed,
     *   so it is dropped rather than stranded.
     * @returns Object containing the count of messages that were cleared
     */
    clearContextMessages(initialMessage: string): Promise<{
        messagesCleared: number;
    }>;
    /**
     * Returns the organization custom instructions configured for this session.
     * These are additional instructions provided by the organization.
     *
     * @returns The organization custom instructions string, or undefined if not set
     */
    getOrganizationCustomInstructions(): string | undefined;
    /**
     * Returns whether custom instructions should be skipped for this session.
     *
     * @returns True if custom instructions should be skipped, false otherwise
     */
    getSkipCustomInstructions(): boolean;
    /**
     * Returns whether on-demand instruction discovery is enabled for this session.
     *
     * @returns True if on-demand instruction discovery is enabled, false otherwise
     */
    getEnableOnDemandInstructionDiscovery(): boolean;
    /**
     * Returns the effective cap (decoded bytes) for inline model-facing binary
     * tool results, falling back to the Rust-owned default cap when
     * the session did not specify `maxInlineBinaryBytes`.
     */
    getMaxInlineBinaryBytes(): number;
    /**
     * Returns additional directories to search for custom instruction files.
     *
     * @returns Array of directory paths, or undefined if not set
     */
    getInstructionDirectories(): string[] | undefined;
    /**
     * Returns the individual custom instruction sources discovered for this session.
     * Uses the git root and working directory to match the system prompt loading path.
     *
     * @returns Array of individual instruction sources
     */
    getInstructionSources(): Promise<RepoInstructionSource[]>;
    /**
     * Returns instruction sources discovered dynamically via file access.
     */
    getDynamicInstructionSources(): RepoInstructionSource[];
    getDynamicInstructionTelemetrySnapshot(): Array<{
        type?: string;
        contentLength: number;
    }>;
    /**
     * Returns the system message configuration for this session.
     * This can be used to replace or append to the default system message.
     *
     * @returns The system message config, or undefined if not set
     */
    getSystemMessageConfig(): SystemMessageConfig | undefined;
    /**
     * Sets the batched transform callback for system prompt sections.
     * Called by the SDK server layer to bind a connection-specific callback
     * that forwards transform requests to the SDK client via JSON-RPC.
     */
    setSectionTransformFn(fn: SectionTransformFn | undefined): void;
    /**
     * Sets the workspace context for infinite sessions.
     * This context is injected into the system prompt to give the agent
     * awareness of the workspace and its history.
     *
     * @param context - The workspace context info, or undefined to clear
     */
    setWorkspaceContext(context: WorkspaceContextInfo | undefined): void;
    /**
     * Gets the current workspace context, if any.
     */
    getWorkspaceContext(): WorkspaceContextInfo | undefined;
    /**
     * Returns the effective capabilities for this session.
     * Applies runtime overrides (e.g., askUserDisabled, runningInInteractiveMode) to the base capabilities.
     */
    protected getEffectiveCapabilities(): Set<SessionCapability>;
    /**
     * Get the current workspace, if any.
     * Only available for LocalSession when infinite sessions are enabled.
     */
    getWorkspace(): Workspace | null;
    /**
     * Check if workspace features are enabled for this session.
     */
    isWorkspaceEnabled(): boolean;
    /**
     * Get the workspace path for this session.
     * Returns null for base Session (non-local sessions don't have workspaces).
     */
    getWorkspacePath(): string | null;
    /** Get the working directory (user's repo/project directory) for this session. */
    getWorkingDirectory(): string;
    getAdditionalDirectories(): string[];
    protected getAdditionalDirectoryGrants(): string[];
    protected excludeCurrentWorkingDirectory(directories: readonly string[]): string[];
    replaceAdditionalDirectories(directories: readonly string[]): void;
    addAdditionalDirectory(directory: string): void;
    private additionalDirectoryKey;
    /**
     * Return `candidate` when it is an absolute path under the session
     * filesystem's path convention; otherwise `undefined`.
     *
     * A relative, empty, or whitespace-only `workingDirectory` is an
     * incidental-cwd hazard: stored raw it would later be resolved against the
     * launcher's `process.cwd()` by downstream readers (str_replace `location`,
     * `repoPath`, `@`-import discovery) and re-emitted through
     * `getWorkingDirectory()`. The rest of the runtime already refuses to trust
     * a non-absolute `workingDirectory` (the hook-safe gate's `isAbsolute`
     * check, the persisted `notAbsolute -> invalid` rule, sdkServer's
     * empty -> undefined), so a non-absolute candidate is treated as "no
     * override". RPC-backed SDK sessions may declare a non-host path convention
     * (`SessionFs.conventions`), so absoluteness is judged under that convention
     * rather than the host OS. The `typeof` guard is load-bearing:
     * `isAbsolute(undefined)` throws, and the no-workingDirectory path passes
     * `undefined`. Part of the Session CWD migration.
     */
    protected absoluteWorkingDirOverride(candidate: string | undefined): string | undefined;
    /**
     * Whether two absolute working-directory paths refer to the same directory.
     * Each is normalized (collapsing redundant `.` segments and separators) with
     * this session's path convention, and case-folded when the target volume is
     * case-insensitive.
     *
     * Case sensitivity is derived from `SessionFs` ownership of the paths, not
     * by blindly probing the runtime host's filesystem. A Windows-convention
     * `SessionFs` (e.g. an `RpcSessionFs` backed by a Windows client) is always
     * case-insensitive regardless of runtime host OS, so host probes against a
     * foreign-convention path like `C:\Repo` are invalid. For LOCAL posix
     * filesystems we can still probe `a`/`b` directly (for correct per-volume
     * behavior on macOS/external drives). For non-local posix providers, where
     * the runtime host cannot authoritatively probe the client volume, preserve
     * POSIX semantics and compare case-sensitively.
     *
     * Public (not just used internally) so callers outside this class - e.g.
     * `sessionMetadataApi`'s `recordContextChange` - can compare a reported cwd
     * against this session's authoritative one using this session's own
     * filesystem conventions, rather than falling back to a host-filesystem
     * path-equality helper that cannot account for a foreign-convention
     * `SessionFs` (e.g. an `RpcSessionFs`).
     */
    workingDirsEqual(a: string, b: string): boolean;
    /**
     * The working directory an `updateOptions` patch should apply, or `undefined`
     * when the patch must not move the cwd.
     *
     * Returns `undefined` for a non-absolute candidate (an incidental-cwd hazard,
     * treated as "no override" - see {@link absoluteWorkingDirOverride}), and for
     * a NON-authoritative candidate that conflicts with an authoritative cwd
     * already claimed via {@link authoritativeWorkingDir}: a stale full-options
     * snapshot (e.g. the CLI options-sync effect echoing a lagging React cwd, or
     * any generic `session.options.update` patch) must not silently rewind the
     * runtime working directory with no event and no guard. Only an explicit
     * authoritative change (`metadata.setWorkingDirectory` or an SDK resume
     * carrying a caller-supplied `workingDirectory`) may move the cwd once one
     * has been claimed. Part of the Session CWD migration.
     */
    protected resolveWorkingDirectoryOverride(candidate: string | undefined, authoritative: boolean): string | undefined;
    /**
     * Get the number of checkpoints in the workspace.
     */
    getCheckpointCount(): number;
    /**
     * Rename the session (set custom name).
     * Updates both in-memory workspace and persists to disk.
     */
    renameSession(_name: string): Promise<void>;
    /**
     * Auto-update the session summary (display name).
     * Base implementation does nothing - only LocalSession has workspaces.
     * Will not overwrite a manually set name when the LocalSession override runs.
     */
    updateSessionSummary(_summary: string): Promise<void>;
    /**
     * Update workspace metadata (cwd, repo, branch) for this session.
     * Base implementation does nothing - LocalSession overrides.
     */
    updateWorkspaceMetadata(_context: WorkspaceContext, _name?: string): Promise<void>;
    /**
     * List checkpoints with their titles for context injection.
     */
    listCheckpointTitles(): Promise<{
        number: number;
        title: string;
        filename: string;
    }[]>;
    /**
     * Read a specific checkpoint by number.
     * Returns null if checkpoint doesn't exist or workspace is not enabled.
     */
    readCheckpoint(_checkpointNumber: number): Promise<string | null>;
    /**
     * Check if a plan.md file exists in the workspace.
     */
    hasPlan(): Promise<boolean>;
    /**
     * Get the absolute file path of plan.md in the workspace.
     * Returns null if workspace is not enabled.
     */
    getPlanPath(): string | null;
    /**
     * Read the plan.md content from the workspace.
     * Returns null if no plan exists.
     */
    readPlan(): Promise<string | null>;
    /**
     * Write plan content to the workspace plan.md file.
     * Base throws because silently discarding the write would be data loss for SDK callers
     * (e.g. via session.plan.update()) on session kinds without a workspace-backed plan.
     * LocalSession overrides.
     */
    writePlan(_content: string): Promise<void>;
    /**
     * Delete the workspace plan.md file.
     * Base throws because silently no-oping would mask the lack of capability for SDK callers
     * (e.g. via session.plan.delete()). LocalSession overrides.
     */
    deletePlan(): Promise<void>;
    /**
     * Read the machine-managed autopilot objective state file.
     * Returns null if no objective file exists or workspace storage is not enabled.
     */
    readAutopilotObjective(): Promise<string | null>;
    /**
     * Write the machine-managed autopilot objective state file.
     */
    writeAutopilotObjective(_content: string): Promise<"create" | "update">;
    /**
     * List files in the workspace files directory.
     */
    listWorkspaceFiles(): Promise<string[]>;
    /**
     * Read a file from the workspace files directory.
     */
    readWorkspaceFile(_path: string): Promise<string>;
    /**
     * Write a file to the workspace files directory.
     */
    writeWorkspaceFile(_path: string, _content: string): Promise<void>;
    /**
     * Ensure workspace exists for this session.
     * Only available for LocalSession when infinite sessions are enabled.
     */
    ensureWorkspace(_context?: WorkspaceContext): Promise<Workspace>;
    /**
     * Sets the selected model for this session and emits a model change event.
     *
     * @param model - The model identifier to switch to
     * @param reasoningEffort - Optional reasoning effort level for the new model
     * @param modelCapabilitiesOverrides - Optional capability overrides; cleared if omitted
     * @param reasoningSummary - Optional reasoning summary mode
     * @param contextTier - Optional context tier for tiered-pricing models. Omit to use normal model behavior.
     */
    setSelectedModel(model: string, reasoningEffort?: ReasoningEffort, modelCapabilitiesOverrides?: ModelCapabilitiesOverride, reasoningSummary?: ReasoningSummary_2, contextTier?: ContextTier_3, verbosity?: Verbosity_2, deferIfModelChangeQueued?: boolean): Promise<ModelSwitchOutcome>;
    protected applyModelChange(model: string, options?: {
        reasoningEffort?: ReasoningEffort;
        reasoningSummary?: ReasoningSummary_2;
        verbosity?: Verbosity_2;
        modelCapabilitiesOverrides?: ModelCapabilitiesOverride;
        contextTier?: ContextTier_3;
        cause?: string;
        /**
         * When true, defer (enqueue) the switch if another model change is
         * already queued, even with no active turn, so it drains last and
         * wins. Only honored by session subclasses that route the switch
         * through the native `session.model.switchTo` deferral path (e.g.
         * {@link LocalSession}); the base implementation applies changes
         * directly and ignores it.
         */
        deferIfModelChangeQueued?: boolean;
    }): Promise<ModelSwitchOutcome>;
    /**
     * Compacts the conversation history into a single summary message.
     * Used by the /compact slash command for manual compaction.
     *
     * Trigger-attribution contract: `trigger` is stamped on the persisted
     * `session.compaction_start` / `session.compaction_complete` events only
     * when the caller actually knows what initiated the compaction; when it is
     * omitted the events persist without a trigger, meaning "unknown". Never
     * guess a trigger on behalf of a caller.
     *
     * @param customInstructions - Optional user-provided instructions to focus the compaction summary
     * @param trigger - What initiated this compaction, recorded on the persisted compaction events. Omit when unknown.
     * @param tokenLimit - Context window token limit this compaction targets, recorded on the persisted compaction events. Pass it only when the target window differs from the compacting model's own (e.g. a model switch); omit to record the compacting model's limit.
     * @returns Promise that resolves with compaction results
     * @throws Error if compaction fails or is not supported
     */
    abstract compactHistory(customInstructions?: string, trigger?: ClientCompactionTrigger, tokenLimit?: number): Promise<CompactionResult>;
    /**
     * Add a function to the event processing queue to ensure sequential processing
     * Returns a promise that resolves when the function has been processed
     * Ensures that state updates from events are processed in order
     */
    protected enqueueEventProcessing<T>(fn: () => T | PromiseLike<T>): Promise<T>;
    /**
     * Classify orphaned tool calls using persisted permission and external tool events.
     *
     * Resume uses the persisted event stream to recover durable request
     * boundaries, then overlays any in-memory external tool completions that a
     * caller handed back after reconnect. We intentionally do not serialize the
     * external tool result itself into the event log.
     */
    private classifyOrphanedToolCalls;
    /**
     * Resolve orphaned tool calls from persisted request boundaries plus any
     * in-memory responses that were handed back after resume. Only invoked when
     * the session was resumed with `continuePendingWork: true`; in the default
     * mode no orphans are tracked, so this method is never reached.
     *
     * The native store plans the resolution (interrupt / permission-resolved /
     * continue-approved / warn-and-interrupt / external-completed), tracking the
     * deferred-approval bookkeeping and leaving awaiting-* orphans pending for
     * the wait-loop in `runAgenticLoop`. TypeScript executes the live effects.
     */
    protected resolveResumeOrphans(tools: Tool[], settings: RuntimeSettings_2, toolsetComplete: boolean): Promise<void>;
    private executeResumeOrphanAction;
    protected hasAwaitingResumeOrphans(): boolean;
    private resolveInterruptedResumeOrphansOnExplicitResume;
    private emitInterruptedOrphan;
    private emitResumeWarning;
    private emitPermissionResolvedOrphan;
    private emitCompletedExternalToolOrphan;
    private continueApprovedExternalToolOrphan;
    protected emitSyntheticToolResult(toolCallId: string, result: ToolResult | ExternalToolResult, defaultFailureMessage: string, includeResumeProvenance?: boolean): void;
    protected emitSyntheticToolExecutionStart(toolCallId: string, toolName: string, args: unknown, tools: Tool[] | undefined): void;
    private emitSyntheticToolFailure;
    protected emitSessionLimitsSkippedToolResults(toolRequests: NonNullable<Extract<SessionEvent, {
        type: "assistant.message";
    }>["data"]["toolRequests"]>, currentModel: string, interactionId: string, turnId?: string, rte?: boolean): Promise<void>;
    private getInterruptedToolMessage;
    protected get _chatMessages(): ChatCompletionMessageParam[];
    protected get _continuePendingWork(): boolean;
    protected set _continuePendingWork(value: boolean);
    protected get _resumeOrphans(): {
        setPermissionResultJson: (toolCallId: string, resultJson: string) => void;
    };
    protected hydrateNativeProjectedMessages(messages: NativeProjectedMessage[]): ChatCompletionMessageParam[];
    private processUserRequestedShellContextPartForLlm;
    protected rewriteChatHistoryForModel(newModel: string): Promise<void>;
    private historyRewriteChain;
    /**
     * Mirror of the native effective-model history-rewrite dedupe key. Kept in
     * sync with the native mark so observers of the last effective model a
     * rewrite ran for see the settled model on success and an unchanged value
     * when a rewrite throws (matching the pre-port field of the same name, which
     * a transient failure must not leave set or the next turn's retry is skipped).
     */
    private lastEffectiveModelForHistoryRewrite;
    /** Native-backed mirror of the pre-port `_createdFromEvents` field. */
    protected get _createdFromEvents(): boolean;
    /** Native-backed mirror of the pre-port `autoModeTelemetryToken` field. */
    private get autoModeTelemetryToken();
    protected setAutoModeTelemetryToken(token: string): void;
    protected maybeRewriteChatHistoryForEffectiveModel(newModel: string): Promise<void>;
    /**
     * Process event to update internal state (_chatMessages, model selection, etc.)
     */
    private processEventForState;
    private maybeRewriteChatHistoryForCurrentSelectedModel;
    /**
     * Whether {@link applyNativeProjectionSideEffects} would do anything for
     * this event.
     *
     * Kept adjacent to that method's `switch` so the two cannot drift: every
     * arm below that performs work must be listed here. Resume replays the
     * whole log through the side-effect pass, and on a long session all but a
     * handful of events are inert — awaiting an `async` no-op for each one
     * turned a 74k-event resume into 74k scheduled microtasks for nothing.
     */
    private hasNativeProjectionSideEffects;
    private applyNativeProjectionSideEffects;
    private applyResumeProjectionSideEffects;
    private rebuildStateFromNativeProjection;
    private replaceNativeSessionSnapshot;
    private shapeCustomAgentsUpdatedAgents;
    private emitCustomAgentsUpdated;
    private getProvidedCustomAgents;
    private getEffectiveAgentId;
    private toEffectiveAgent;
    protected getEffectiveSelectedCustomAgent(): SweCustomAgent | undefined;
    protected getAgentPromptOverride(agentId: string): string | undefined;
    private mergeProvidedCustomAgents;
    private loadBuiltinAgentsForListing;
    private startCustomAgentsLoad;
    private retireCustomAgentsLoad;
    private loadCustomAgents;
    /**
     * Reload custom agents. Re-runs discovery for discovered agents while preserving
     * session-provided agents, and emits a `session.custom_agents_updated` event.
     * If the previously selected agent is still available after reload, the selection is preserved.
     */
    reloadCustomAgents(): Promise<void>;
    /**
     * Resolve an ExP-backed feature flag.
     *
     * Delegates to {@link FeatureFlagService.getFlagWithExpOverride}, which
     * awaits the ExP assignment and falls back to the static feature flag when
     * ExP has no assignment. The service is always present on a Session.
     */
    protected resolveExpFlag(expFlag: Parameters<IFeatureFlagService["getFlagWithExpOverride"]>[0], featureFlag: FeatureFlag): Promise<boolean>;
    private noOuterLoopTruncationArmPromise?;
    protected getNoOuterLoopTruncationArm(): Promise<boolean>;
    private noSqlTablesReminderArmPromise?;
    /**
     * A/B experiment arm: when true, the per-turn `<sql_tables>` system reminder
     * is omitted from the CLI user message. The `sql` tool (whose description
     * already documents the pre-existing `todos` / `todo_deps` tables) and the
     * separate `<todo_status>` reminder are unaffected.
     */
    protected getNoSqlTablesReminderArm(): Promise<boolean>;
    protected resolveIsRubberDuckAgentExpEnabled(): Promise<boolean>;
    private activateFactoryUsageProducer;
    /**
     * Creates an ephemeral LocalSession configured as a subagent of this session.
     *
     * The child session inherits auth, working directory, feature flags, provider config,
     * custom instructions state, and other parent context. The caller specifies only what
     * differs for the subagent (capabilities, tool restrictions, MCP servers, etc.).
     *
     * The child session uses `interactionType: "conversation-subagent"` and increments
     * `subAgentDepth` to enforce max-depth limits.
     */
    createSubagentSession(agentId: string, options?: SubagentSessionOptions): LocalSession;
}

/** Ordered list of the session modes a session can occupy. */
export declare const SESSION_MODES: readonly ["interactive", "plan", "autopilot"];

/** Current activity flags for the session. */
declare interface SessionActivity {
    /** Whether an in-flight operation can currently be aborted. */
    abortable: boolean;
    /** Whether the session currently has active work, including running turns or tasks. */
    hasActiveWork: boolean;
}

declare type SessionAgentApi = SessionApi["agent"];

declare interface SessionApi {
    abort(params: AbortRequest): AbortResult | Promise<AbortResult>;
    agent: {
        deselect(): void | Promise<void>;
        getCurrent(): AgentGetCurrentResult | Promise<AgentGetCurrentResult>;
        list(params?: AgentListRequest): AgentList | Promise<AgentList>;
        reload(): AgentReloadResult | Promise<AgentReloadResult>;
        select(params: AgentSelectRequest): AgentSelectResult | Promise<AgentSelectResult>;
        setPrompt(params: AgentSetPromptRequest): void | Promise<void>;
    };
    cancelAllBackgroundAgents(): number | Promise<number>;
    canvas: {
        action: {
            invoke(params: CanvasActionInvokeRequest): CanvasActionInvokeResult | Promise<CanvasActionInvokeResult>;
        };
        close(params: CanvasCloseRequest): void | Promise<void>;
        list(): CanvasList | Promise<CanvasList>;
        listOpen(): CanvasListOpenResult | Promise<CanvasListOpenResult>;
        open(params: CanvasOpenRequest): OpenCanvasInstance | Promise<OpenCanvasInstance>;
    };
    commands: {
        enqueue(params: EnqueueCommandParams): EnqueueCommandResult | Promise<EnqueueCommandResult>;
        execute(params: ExecuteCommandParams): ExecuteCommandResult | Promise<ExecuteCommandResult>;
        handlePendingCommand(params: CommandsHandlePendingCommandRequest): CommandsHandlePendingCommandResult | Promise<CommandsHandlePendingCommandResult>;
        invoke(params: CommandsInvokeRequest): SlashCommandInvocationResult | Promise<SlashCommandInvocationResult>;
        list(params?: CommandsListRequest): CommandList | Promise<CommandList>;
        respondToQueuedCommand(params: CommandsRespondToQueuedCommandRequest): CommandsRespondToQueuedCommandResult | Promise<CommandsRespondToQueuedCommandResult>;
    };
    completions: {
        getTriggerCharacters(): CompletionsGetTriggerCharactersResult | Promise<CompletionsGetTriggerCharactersResult>;
        request(params: CompletionsRequestRequest): CompletionsRequestResult | Promise<CompletionsRequestResult>;
    };
    contentExclusion: {
        checkPaths(params: ContentExclusionCheckPathsRequest): ContentExclusionCheckPathsResult | Promise<ContentExclusionCheckPathsResult>;
    };
    debug: {
        collectLogs(params: DebugCollectLogsRequest): DebugCollectLogsResult | Promise<DebugCollectLogsResult>;
    };
    eventLog: {
        read(params: EventLogReadRequest): EventsReadResult | Promise<EventsReadResult>;
        registerInterest(params: RegisterEventInterestParams): RegisterEventInterestResult | Promise<RegisterEventInterestResult>;
        releaseInterest(params: ReleaseEventInterestParams): EventLogReleaseInterestResult | Promise<EventLogReleaseInterestResult>;
        tail(): EventLogTailResult | Promise<EventLogTailResult>;
    };
    extensions: {
        disable(params: ExtensionsDisableRequest): void | Promise<void>;
        enable(params: ExtensionsEnableRequest): void | Promise<void>;
        list(): ExtensionList | Promise<ExtensionList>;
        reload(): void | Promise<void>;
        sendAttachmentsToMessage(params: SendAttachmentsToMessageParams): void | Promise<void>;
    };
    factory: {
        agent(params: FactoryAgentRequest): FactoryAgentResult | Promise<FactoryAgentResult>;
        cancel(params: FactoryCancelRequest): FactoryRunResult | Promise<FactoryRunResult>;
        getRun(params: FactoryGetRunRequest): FactoryRunResult | Promise<FactoryRunResult>;
        getRunDetail(params: FactoryGetRunRequest): FactoryRunDetail | Promise<FactoryRunDetail>;
        getRunProgress(params: FactoryGetRunProgressRequest): FactoryProgressPage | Promise<FactoryProgressPage>;
        journal: {
            get(params: FactoryJournalGetRequest): FactoryJournalGetResult | Promise<FactoryJournalGetResult>;
            put(params: FactoryJournalPutRequest): FactoryAckResult | Promise<FactoryAckResult>;
        };
        listRuns(params: FactoryListRunsRequest): FactoryListRunsResult | Promise<FactoryListRunsResult>;
        log(params: FactoryLogRequest): FactoryAckResult | Promise<FactoryAckResult>;
        resume(params: FactoryResumeRequest): FactoryResumeResult | Promise<FactoryResumeResult>;
        run(params: FactoryRunRequest): FactoryRunResult | Promise<FactoryRunResult>;
    };
    fleet: {
        start(params: FleetStartRequest): FleetStartResult | Promise<FleetStartResult>;
    };
    gitHubAuth: {
        getStatus(): SessionAuthStatus | Promise<SessionAuthStatus>;
        setCredentials(params: SessionSetCredentialsParams): SessionSetCredentialsResult | Promise<SessionSetCredentialsResult>;
    };
    history: {
        abortManualCompaction(): HistoryAbortManualCompactionResult | Promise<HistoryAbortManualCompactionResult>;
        cancelBackgroundCompaction(): HistoryCancelBackgroundCompactionResult | Promise<HistoryCancelBackgroundCompactionResult>;
        clearContext(params: HistoryClearContextRequest): HistoryClearContextResult | Promise<HistoryClearContextResult>;
        compact(params?: HistoryCompactRequest): HistoryCompactResult | Promise<HistoryCompactResult>;
        listRewindPoints(): HistoryListRewindPointsResult | Promise<HistoryListRewindPointsResult>;
        previewRewind(params: HistoryPreviewRewindRequest): HistoryPreviewRewindResult | Promise<HistoryPreviewRewindResult>;
        rewind(params: HistoryRewindRequest): HistoryRewindResult | Promise<HistoryRewindResult>;
        summarizeForHandoff(): HistorySummarizeForHandoffResult | Promise<HistorySummarizeForHandoffResult>;
        truncate(params: HistoryTruncateRequest): HistoryTruncateResult | Promise<HistoryTruncateResult>;
    };
    instructions: {
        getSources(): InstructionsGetSourcesResult | Promise<InstructionsGetSourcesResult>;
    };
    interruptMainTurn(params: InterruptMainTurnRequest): InterruptMainTurnResult | Promise<InterruptMainTurnResult>;
    limitPrediction: {
        predict(params?: SessionLimitPredictionRequest): SessionLimitPredictionResult | Promise<SessionLimitPredictionResult>;
    };
    log(params: LogRequest): LogResult | Promise<LogResult>;
    lsp: {
        initialize(params: LspInitializeRequest): void | Promise<void>;
    };
    mcp: {
        apps: {
            callTool(params: McpAppsCallToolRequest): Record<string, unknown> | Promise<Record<string, unknown>>;
            diagnose(params: McpAppsDiagnoseRequest): McpAppsDiagnoseResult | Promise<McpAppsDiagnoseResult>;
            getHostContext(): McpAppsHostContext | Promise<McpAppsHostContext>;
            listTools(params: McpAppsListToolsRequest): McpAppsListToolsResult | Promise<McpAppsListToolsResult>;
            readResource(params: McpAppsReadResourceRequest): McpAppsReadResourceResult | Promise<McpAppsReadResourceResult>;
            setHostContext(params: McpAppsSetHostContextRequest): void | Promise<void>;
        };
        cancelSamplingExecution(params: McpCancelSamplingExecutionParams): McpCancelSamplingExecutionResult | Promise<McpCancelSamplingExecutionResult>;
        configureGitHub(params: McpConfigureGitHubRequest): McpConfigureGitHubResult | Promise<McpConfigureGitHubResult>;
        disable(params: McpDisableRequest): void | Promise<void>;
        enable(params: McpEnableRequest): void | Promise<void>;
        executeSampling(params: McpExecuteSamplingParams): McpSamplingExecutionResult | Promise<McpSamplingExecutionResult>;
        headers: {
            handlePendingHeadersRefreshRequest(params: McpHeadersHandlePendingHeadersRefreshRequestRequest): McpHeadersHandlePendingHeadersRefreshRequestResult | Promise<McpHeadersHandlePendingHeadersRefreshRequestResult>;
        };
        isServerRunning(params: McpIsServerRunningRequest): McpIsServerRunningResult | Promise<McpIsServerRunningResult>;
        list(): McpServerList | Promise<McpServerList>;
        listTools(params: McpListToolsRequest): McpListToolsResult | Promise<McpListToolsResult>;
        oauth: {
            authenticationStateChanged(params: McpOauthAuthenticationStateChangedRequest): void | Promise<void>;
            handlePendingRequest(params: McpOauthHandlePendingRequest): McpOauthHandlePendingResult | Promise<McpOauthHandlePendingResult>;
            login(params: McpOauthLoginRequest): McpOauthLoginResult | Promise<McpOauthLoginResult>;
            respond(params: McpOauthRespondRequest): McpOauthRespondResult | Promise<McpOauthRespondResult>;
        };
        registerExternalClient(params: McpRegisterExternalClientRequest): void | Promise<void>;
        reload(): void | Promise<void>;
        reloadWithConfig(params: McpReloadWithConfigRequest): McpStartServersResult | Promise<McpStartServersResult>;
        removeGitHub(): McpRemoveGitHubResult | Promise<McpRemoveGitHubResult>;
        resources: {
            list(params: McpResourcesListRequest): McpResourcesListResult | Promise<McpResourcesListResult>;
            listTemplates(params: McpResourcesListTemplatesRequest): McpResourcesListTemplatesResult | Promise<McpResourcesListTemplatesResult>;
            read(params: McpResourcesReadRequest): McpResourcesReadResult | Promise<McpResourcesReadResult>;
        };
        restartServer(params: McpRestartServerRequest): void | Promise<void>;
        setEnvValueMode(params: McpSetEnvValueModeParams): McpSetEnvValueModeResult | Promise<McpSetEnvValueModeResult>;
        startServer(params: McpStartServerRequest): void | Promise<void>;
        stopServer(params: McpStopServerRequest): void | Promise<void>;
        unregisterExternalClient(params: McpUnregisterExternalClientRequest): void | Promise<void>;
    };
    metadata: {
        activity(): SessionActivity | Promise<SessionActivity>;
        contextInfo(params: MetadataContextInfoRequest): MetadataContextInfoResult | Promise<MetadataContextInfoResult>;
        getContextAttribution(): MetadataContextAttributionResult | Promise<MetadataContextAttributionResult>;
        getContextHeaviestMessages(params: MetadataContextHeaviestMessagesRequest): MetadataContextHeaviestMessagesResult | Promise<MetadataContextHeaviestMessagesResult>;
        isProcessing(): MetadataIsProcessingResult | Promise<MetadataIsProcessingResult>;
        recomputeContextTokens(params: MetadataRecomputeContextTokensRequest): MetadataRecomputeContextTokensResult | Promise<MetadataRecomputeContextTokensResult>;
        recordContextChange(params: MetadataRecordContextChangeRequest): MetadataRecordContextChangeResult | Promise<MetadataRecordContextChangeResult>;
        setWorkingDirectory(params: MetadataSetWorkingDirectoryRequest): MetadataSetWorkingDirectoryResult | Promise<MetadataSetWorkingDirectoryResult>;
        snapshot(): SessionMetadataSnapshot | Promise<SessionMetadataSnapshot>;
    };
    mode: {
        get(): SessionMode_2 | Promise<SessionMode_2>;
        set(params: ModeSetRequest): void | Promise<void>;
    };
    model: {
        getCurrent(): CurrentModel | Promise<CurrentModel>;
        list(params?: ModelListRequest): SessionModelList | Promise<SessionModelList>;
        setReasoningEffort(params: ModelSetReasoningEffortRequest): ModelSetReasoningEffortResult | Promise<ModelSetReasoningEffortResult>;
        switchTo(params: ModelSwitchToRequest): ModelSwitchToResult | Promise<ModelSwitchToResult>;
    };
    name: {
        get(): NameGetResult | Promise<NameGetResult>;
        set(params: NameSetRequest): void | Promise<void>;
        setAuto(params: NameSetAutoRequest): NameSetAutoResult | Promise<NameSetAutoResult>;
    };
    options: {
        update(params: SessionUpdateOptionsParams): SessionUpdateOptionsResult | Promise<SessionUpdateOptionsResult>;
    };
    permissions: {
        configure(params: PermissionsConfigureParams): PermissionsConfigureResult | Promise<PermissionsConfigureResult>;
        folderTrust: {
            addTrusted(params: FolderTrustAddParams): PermissionsFolderTrustAddTrustedResult | Promise<PermissionsFolderTrustAddTrustedResult>;
            isTrusted(params: FolderTrustCheckParams): FolderTrustCheckResult | Promise<FolderTrustCheckResult>;
        };
        getAllowAll(params: PermissionsGetAllowAllRequest): AllowAllPermissionState | Promise<AllowAllPermissionState>;
        handlePendingPermissionRequest(params: PermissionDecisionRequest): PermissionRequestResult_2 | Promise<PermissionRequestResult_2>;
        locations: {
            addToolApproval(params: PermissionLocationAddToolApprovalParams): PermissionsLocationsAddToolApprovalResult | Promise<PermissionsLocationsAddToolApprovalResult>;
            apply(params: PermissionLocationApplyParams): PermissionLocationApplyResult | Promise<PermissionLocationApplyResult>;
            resolve(params: PermissionLocationResolveParams): PermissionLocationResolveResult | Promise<PermissionLocationResolveResult>;
        };
        modifyRules(params: PermissionsModifyRulesParams): PermissionsModifyRulesResult | Promise<PermissionsModifyRulesResult>;
        notifyPromptShown(params: PermissionPromptShownNotification): PermissionsNotifyPromptShownResult | Promise<PermissionsNotifyPromptShownResult>;
        paths: {
            add(params: PermissionPathsAddParams): PermissionsPathsAddResult | Promise<PermissionsPathsAddResult>;
            isPathWithinAllowedDirectories(params: PermissionPathsAllowedCheckParams): PermissionPathsAllowedCheckResult | Promise<PermissionPathsAllowedCheckResult>;
            isPathWithinWorkspace(params: PermissionPathsWorkspaceCheckParams): PermissionPathsWorkspaceCheckResult | Promise<PermissionPathsWorkspaceCheckResult>;
            list(params: PermissionsPathsListRequest): PermissionPathsList | Promise<PermissionPathsList>;
            updatePrimary(params: PermissionPathsUpdatePrimaryParams): PermissionsPathsUpdatePrimaryResult | Promise<PermissionsPathsUpdatePrimaryResult>;
        };
        pendingRequests(params: PermissionsPendingRequestsRequest): PendingPermissionRequestList | Promise<PendingPermissionRequestList>;
        resetSessionApprovals(params: PermissionsResetSessionApprovalsRequest): PermissionsResetSessionApprovalsResult | Promise<PermissionsResetSessionApprovalsResult>;
        setAllowAll(params: PermissionsSetAllowAllRequest): AllowAllPermissionSetResult | Promise<AllowAllPermissionSetResult>;
        setApproveAll(params: PermissionsSetApproveAllRequest): PermissionsSetApproveAllResult | Promise<PermissionsSetApproveAllResult>;
        setRequired(params: PermissionsSetRequiredRequest): PermissionsSetRequiredResult | Promise<PermissionsSetRequiredResult>;
        urls: {
            setUnrestrictedMode(params: PermissionUrlsSetUnrestrictedModeParams): PermissionsUrlsSetUnrestrictedModeResult | Promise<PermissionsUrlsSetUnrestrictedModeResult>;
        };
    };
    plan: {
        delete(): void | Promise<void>;
        read(): PlanReadResult | Promise<PlanReadResult>;
        readSqlTodos(): PlanReadSqlTodosResult | Promise<PlanReadSqlTodosResult>;
        readSqlTodosWithDependencies(): PlanReadSqlTodosWithDependenciesResult | Promise<PlanReadSqlTodosWithDependenciesResult>;
        update(params: PlanUpdateRequest): void | Promise<void>;
    };
    plugins: {
        list(): PluginList | Promise<PluginList>;
        reload(params?: PluginsReloadRequest): void | Promise<void>;
    };
    provider: {
        add(params: ProviderAddRequest): ProviderAddResult | Promise<ProviderAddResult>;
        getEndpoint(params?: ProviderGetEndpointRequest): ProviderEndpoint | Promise<ProviderEndpoint>;
    };
    queue: {
        beginDeferredIdleDrain(params: QueueBeginDeferredIdleDrainRequest): QueueBeginDeferredIdleDrainResult | Promise<QueueBeginDeferredIdleDrainResult>;
        clear(): void | Promise<void>;
        consumeSystemNotifications(params: QueueConsumeSystemNotificationsRequest): QueueRemoveMostRecentResult | Promise<QueueRemoveMostRecentResult>;
        deferSessionIdle(params: QueueDeferSessionIdleRequest): void | Promise<void>;
        duplicateAt(params: QueueDuplicateAtRequest): QueueDuplicateAtResult | Promise<QueueDuplicateAtResult>;
        enqueueResumePending(): QueueEnqueueResumePendingResult | Promise<QueueEnqueueResumePendingResult>;
        finishDeferredIdleDrain(params: QueueFinishDeferredIdleDrainRequest): QueueFinishDeferredIdleDrainResult | Promise<QueueFinishDeferredIdleDrainResult>;
        hasPending(): QueueHasPendingResult | Promise<QueueHasPendingResult>;
        insertAt(params: QueueInsertAtRequest): QueueInsertAtResult | Promise<QueueInsertAtResult>;
        moveItem(params: QueueMoveItemRequest): QueueMoveItemResult | Promise<QueueMoveItemResult>;
        pendingItems(): QueuePendingItemsResult | Promise<QueuePendingItemsResult>;
        process(): void | Promise<void>;
        removeAt(params: QueueRemoveAtRequest): QueueRemoveAtResult | Promise<QueueRemoveAtResult>;
        removeMostRecent(): QueueRemoveMostRecentResult | Promise<QueueRemoveMostRecentResult>;
        sendNow(params: QueueSendNowRequest): QueueSendNowResult | Promise<QueueSendNowResult>;
        setDrainPaused(params: QueueSetDrainPausedRequest): void | Promise<void>;
        snapshot(): QueueSnapshotResult | Promise<QueueSnapshotResult>;
        updateText(params: QueueUpdateTextRequest): QueueUpdateTextResult | Promise<QueueUpdateTextResult>;
    };
    remote: {
        disable(): void | Promise<void>;
        enable(params: RemoteEnableRequest): RemoteEnableResult | Promise<RemoteEnableResult>;
        notifySteerableChanged(params: RemoteNotifySteerableChangedRequest): RemoteNotifySteerableChangedResult | Promise<RemoteNotifySteerableChangedResult>;
    };
    schedule: {
        add(params: ScheduleAddRequest): ScheduleAddResult | Promise<ScheduleAddResult>;
        addAt(params: ScheduleAddAtRequest): ScheduleAddResult | Promise<ScheduleAddResult>;
        addCron(params: ScheduleAddCronRequest): ScheduleAddResult | Promise<ScheduleAddResult>;
        addSelfPaced(params: ScheduleAddSelfPacedRequest): ScheduleAddResult | Promise<ScheduleAddResult>;
        hasSelfPaced(): ScheduleHasSelfPacedResult | Promise<ScheduleHasSelfPacedResult>;
        hydrate(): void | Promise<void>;
        list(): ScheduleList | Promise<ScheduleList>;
        rearmSelfPaced(params: ScheduleRearmSelfPacedRequest): ScheduleAddResult | Promise<ScheduleAddResult>;
        stop(params: ScheduleStopRequest): ScheduleStopResult | Promise<ScheduleStopResult>;
    };
    send(params: SendRequest): SendResult | Promise<SendResult>;
    sendMessages(params: SendMessagesRequest): SendMessagesResult | Promise<SendMessagesResult>;
    sendSystemNotification(params: SendSystemNotificationRequest): void | Promise<void>;
    settings: {
        evaluatePredicate(params: SessionSettingsEvaluatePredicateRequest): SessionSettingsEvaluatePredicateResult | Promise<SessionSettingsEvaluatePredicateResult>;
        snapshot(): SessionSettingsSnapshot | Promise<SessionSettingsSnapshot>;
    };
    shell: {
        cancelUserRequested(params: ShellCancelUserRequestedRequest): CancelUserRequestedShellCommandResult | Promise<CancelUserRequestedShellCommandResult>;
        exec(params: ShellExecRequest): ShellExecResult | Promise<ShellExecResult>;
        executeUserRequested(params: ShellExecuteUserRequestedRequest): UserRequestedShellCommandResult_2 | Promise<UserRequestedShellCommandResult_2>;
        kill(params: ShellKillRequest): ShellKillResult | Promise<ShellKillResult>;
    };
    shutdown(params: ShutdownRequest): void | Promise<void>;
    skills: {
        disable(params: SkillsDisableRequest): void | Promise<void>;
        enable(params: SkillsEnableRequest): void | Promise<void>;
        ensureLoaded(): void | Promise<void>;
        getInvoked(): SkillsGetInvokedResult | Promise<SkillsGetInvokedResult>;
        list(): SkillList | Promise<SkillList>;
        reload(): SkillsLoadDiagnostics | Promise<SkillsLoadDiagnostics>;
    };
    suspend(): void | Promise<void>;
    tasks: {
        cancel(params: TasksCancelRequest): TasksCancelResult | Promise<TasksCancelResult>;
        getCurrentPromotable(): TasksGetCurrentPromotableResult | Promise<TasksGetCurrentPromotableResult>;
        getProgress(params: TasksGetProgressRequest): TasksGetProgressResult | Promise<TasksGetProgressResult>;
        list(): TaskList | Promise<TaskList>;
        promoteCurrentToBackground(): TasksPromoteCurrentToBackgroundResult | Promise<TasksPromoteCurrentToBackgroundResult>;
        promoteToBackground(params: TasksPromoteToBackgroundRequest): TasksPromoteToBackgroundResult | Promise<TasksPromoteToBackgroundResult>;
        refresh(): TasksRefreshResult | Promise<TasksRefreshResult>;
        remove(params: TasksRemoveRequest): TasksRemoveResult | Promise<TasksRemoveResult>;
        sendMessage(params: TasksSendMessageRequest): TasksSendMessageResult | Promise<TasksSendMessageResult>;
        startAgent(params: TasksStartAgentRequest): TasksStartAgentResult | Promise<TasksStartAgentResult>;
        waitForPending(): TasksWaitForPendingResult | Promise<TasksWaitForPendingResult>;
    };
    telemetry: {
        getEngagementId(): SessionTelemetryEngagement | Promise<SessionTelemetryEngagement>;
        setFeatureOverrides(params: TelemetrySetFeatureOverridesRequest): void | Promise<void>;
    };
    tools: {
        getCurrentMetadata(): ToolsGetCurrentMetadataResult | Promise<ToolsGetCurrentMetadataResult>;
        handlePendingToolCall(params: HandlePendingToolCallRequest): HandlePendingToolCallResult | Promise<HandlePendingToolCallResult>;
        initializeAndValidate(): ToolsInitializeAndValidateResult | Promise<ToolsInitializeAndValidateResult>;
        updateSubagentSettings(params: UpdateSubagentSettingsRequest): ToolsUpdateSubagentSettingsResult | Promise<ToolsUpdateSubagentSettingsResult>;
    };
    ui: {
        elicitation(params: UIElicitationRequest): UIElicitationResponse | Promise<UIElicitationResponse>;
        ephemeralQuery(params: UIEphemeralQueryRequest): UIEphemeralQueryResult | Promise<UIEphemeralQueryResult>;
        handlePendingAutoModeSwitch(params: UIHandlePendingAutoModeSwitchRequest): UIHandlePendingResult | Promise<UIHandlePendingResult>;
        handlePendingElicitation(params: UIHandlePendingElicitationRequest): UIElicitationResult | Promise<UIElicitationResult>;
        handlePendingExitPlanMode(params: UIHandlePendingExitPlanModeRequest): UIHandlePendingResult | Promise<UIHandlePendingResult>;
        handlePendingSampling(params: UIHandlePendingSamplingRequest): UIHandlePendingResult | Promise<UIHandlePendingResult>;
        handlePendingSessionLimitsExhausted(params: UIHandlePendingSessionLimitsExhaustedRequest): UIHandlePendingResult | Promise<UIHandlePendingResult>;
        handlePendingUserInput(params: UIHandlePendingUserInputRequest): UIHandlePendingResult | Promise<UIHandlePendingResult>;
        registerDirectAutoModeSwitchHandler(): UIRegisterDirectAutoModeSwitchHandlerResult | Promise<UIRegisterDirectAutoModeSwitchHandlerResult>;
        unregisterDirectAutoModeSwitchHandler(params: UIUnregisterDirectAutoModeSwitchHandlerRequest): UIUnregisterDirectAutoModeSwitchHandlerResult | Promise<UIUnregisterDirectAutoModeSwitchHandlerResult>;
    };
    usage: {
        getMetrics(): UsageGetMetricsResult | Promise<UsageGetMetricsResult>;
    };
    visibility: {
        get(): VisibilityGetResult | Promise<VisibilityGetResult>;
        set(params: VisibilitySetRequest): VisibilitySetResult | Promise<VisibilitySetResult>;
    };
    workspaces: {
        addSummary(params: WorkspacesAddSummaryRequest): WorkspacesAddSummaryResult | Promise<WorkspacesAddSummaryResult>;
        autopilotObjectiveExists(): WorkspacesAutopilotObjectiveExistsResult | Promise<WorkspacesAutopilotObjectiveExistsResult>;
        createFile(params: WorkspacesCreateFileRequest): void | Promise<void>;
        deleteAutopilotObjective(): WorkspacesDeleteAutopilotObjectiveResult | Promise<WorkspacesDeleteAutopilotObjectiveResult>;
        diff(params: WorkspacesDiffRequest): WorkspaceDiffResult | Promise<WorkspaceDiffResult>;
        ensure(params: WorkspacesEnsureRequest): WorkspacesGetWorkspaceResult | Promise<WorkspacesGetWorkspaceResult>;
        getWorkspace(): WorkspacesGetWorkspaceResult | Promise<WorkspacesGetWorkspaceResult>;
        listCheckpoints(): WorkspacesListCheckpointsResult | Promise<WorkspacesListCheckpointsResult>;
        listFiles(): WorkspacesListFilesResult | Promise<WorkspacesListFilesResult>;
        readAutopilotObjective(): WorkspacesReadAutopilotObjectiveResult | Promise<WorkspacesReadAutopilotObjectiveResult>;
        readCheckpoint(params: WorkspacesReadCheckpointRequest): WorkspacesReadCheckpointResult | Promise<WorkspacesReadCheckpointResult>;
        readFile(params: WorkspacesReadFileRequest): WorkspacesReadFileResult | Promise<WorkspacesReadFileResult>;
        saveLargePaste(params: WorkspacesSaveLargePasteRequest): WorkspacesSaveLargePasteResult | Promise<WorkspacesSaveLargePasteResult>;
        truncateSummaries(params: WorkspacesTruncateSummariesRequest): WorkspacesGetWorkspaceResult | Promise<WorkspacesGetWorkspaceResult>;
        updateMetadata(params: WorkspacesUpdateMetadataRequest): WorkspacesGetWorkspaceResult | Promise<WorkspacesGetWorkspaceResult>;
        writeAutopilotObjective(params: WorkspacesWriteAutopilotObjectiveRequest): WorkspacesWriteAutopilotObjectiveResult | Promise<WorkspacesWriteAutopilotObjectiveResult>;
    };
}

/** A session approval that can be persisted and restored. */
declare type SessionApproval = {
    kind: "commands";
    readonly commandIdentifiers: readonly string[];
} | {
    kind: "read";
} | {
    kind: "write";
} | {
    kind: "memory";
} | {
    kind: "mcp";
    serverName: string;
    toolName: string | null;
} | {
    kind: "mcp-sampling";
    serverName: string;
} | {
    kind: "custom-tool";
    toolName: string;
} | {
    kind: "extension-management";
    operation?: string;
} | {
    kind: "factory";
    approvalKey?: string;
} | {
    kind: "extension-permission-access";
    extensionName: string;
};

/**
 * A SessionApproval type specific to the kind of UserToolPermissionRequest.
 * This allows us to tie user requests and responses back together with the right approval type.
 */
declare type SessionApprovalFor<K extends UserToolPermissionRequest["kind"]> = Extract<SessionApproval, {
    kind: K;
}>;

/** Authentication status and account metadata for the session. */
declare interface SessionAuthStatus {
    /** Authentication type */
    authType?: AuthInfoType;
    /** Copilot plan tier (e.g., individual_pro, business) */
    copilotPlan?: string;
    /** Authentication host URL */
    host?: string;
    /** Whether the session has resolved authentication */
    isAuthenticated: boolean;
    /** Authenticated login/username, if available */
    login?: string;
    /** Human-readable authentication status description */
    statusMessage?: string;
}

/** Map of sessionId -> bytes freed by removing the session's workspace directory. */
declare interface SessionBulkDeleteResult {
    /** Map of sessionId -> bytes freed by removing the session's workspace directory. Sessions whose deletion failed are omitted from this map (failures are logged on the server but not surfaced per-id; check the map for absent IDs to detect them). */
    freedBytes: Record<string, number>;
}

declare type SessionCanvasApi = SessionApi["canvas"];

declare type SessionCanvasApi_2 = SessionApi["canvas"];

declare interface SessionCanvasRuntimeApi extends SessionCanvasApi_2 {
    registerProvider(params: {
        connectionId: string;
        connection: CanvasProviderConnection;
        info: CanvasProviderInfo;
        canvases: CanvasContribution[];
    }): void;
    unregisterProvider(connectionId: string): void;
    seedOpenInstances(instances: OpenCanvasInstance[]): void;
    getOpenInstanceOwner(instanceId: string): {
        extensionId: string;
        canvasId: string;
    } | undefined;
    dispose(): void;
}

/** Session capability enabled for this session */
declare type SessionCapability = "tui-hints" | "plan-mode" | "memory" | "cli-documentation" | "ask-user" | "interactive-mode" | "system-notifications" | "elicitation" | "session-store" | "mcp-apps" | "canvas-renderer";

export declare type SessionClientKind = "cli" | "acp" | "sdk";

declare type SessionCommandsApi = SessionApi["commands"];

declare type SessionCompactionStartData = Extract<SessionEvent, {
    type: "session.compaction_start";
}>["data"];

/** A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` (UTF-16 code units) in the composer with `insertText`; when the range is absent, the active token around the cursor is replaced. */
declare interface SessionCompletionItem {
    /** Text spliced into the composer when the item is accepted. */
    insertText: string;
    /** Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the host's display kind. */
    kind?: string;
    /** Primary display label for the picker row. Falls back to `insertText` when absent. */
    label?: string;
    /** End (exclusive) of the replacement range in `text`, in UTF-16 code units. */
    rangeEnd?: number;
    /** Start of the replacement range in `text`, in UTF-16 code units. */
    rangeStart?: number;
}

declare type SessionCompletionsApi = SessionApi["completions"];

declare type SessionContentExclusionApi = SessionApi["contentExclusion"];

export declare interface SessionContext {
    readonly cwd: string;
    readonly gitRoot?: string;
    readonly repository?: string;
    readonly hostType?: RepoHostType;
    readonly branch?: string;
}

/** Pre-resolved working-directory context for session startup. */
declare interface SessionContext_2 {
    /** Active git branch */
    branch?: string;
    /** Most recent working directory for this session */
    cwd: string;
    /** Git repository root, if the cwd was inside a git repo */
    gitRoot?: string;
    /** Repository host type */
    hostType?: SessionContextHostType;
    /** Repository slug in `owner/name` form, when known */
    repository?: string;
}

/** Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). */
declare type SessionContextAttribution = {
    bufferTokens: number;
    categories: {
        buffer: number;
        customInstructions: number;
        freeSpace: number;
        mcpTools: number;
        messages: number;
        systemPrompt: number;
        systemTools: number;
    };
    compactionThreshold: number;
    compactions: {
        count: number;
    };
    entries: {
        attributes?: Record<string, string>;
        id: string;
        kind: string;
        label: string;
        parentId?: string;
        tokens: number;
    }[];
    limit: number;
    modelId: string;
    modelSource: string;
    promptTokenLimit: number;
    totalTokens: number;
} | null;

/** Repository host type */
declare type SessionContextHostType = "github" | "ado";

/** Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). */
declare type SessionContextInfo = {
    bufferTokens: number;
    compactionThreshold: number;
    conversationTokens: number;
    limit: number;
    mcpToolsTokens: number;
    modelName: string;
    promptTokenLimit: number;
    systemTokens: number;
    toolDefinitionsTokens: number;
    totalTokens: number;
} | null;

declare type SessionCorrelationIds = Record<string, string>;

/** Native per-session SQLite database handle owned by the Rust runtime. */
declare type SessionDatabaseHandle = InstanceType<NativeRuntime["SessionDatabaseHandle"]>;

declare type SessionDatabaseHandleCompat = Omit<RuntimeSessionDatabaseHandle, "execute" | "batch" | "transaction"> & {
    execute(queryType: string, query: string, paramsJson?: string): Promise<RuntimeNative.SessionDatabaseSqlResult | undefined>;
    batch(queries: Array<[queryType: string, query: string]>): Promise<Array<RuntimeNative.SessionDatabaseSqlResult | undefined>>;
    transaction(statementsJson: string): Promise<RuntimeNative.SessionDatabaseSqlResult[]>;
};

declare type SessionDebugApi = SessionApi["debug"];

/** The enriched metadata records, with summary and context fields backfilled where available. Sessions confirmed empty and unnamed are omitted. */
declare interface SessionEnrichMetadataResult {
    /** Enriched records, with summary and context backfilled. Sessions confirmed empty and unnamed may be omitted. */
    sessions: LocalSessionMetadataValue[];
}

/** Union of all session event variants emitted by the Copilot CLI runtime. */
export declare type SessionEvent = StartEvent | ResumeEvent | RemoteSteerableChangedEvent | ErrorEvent_2 | IdleEvent | TitleChangedEvent | ScheduleCreatedEvent | ScheduleCancelledEvent | ScheduleRearmedEvent | AutopilotObjectiveChangedEvent | InfoEvent | WarningEvent | ModelChangeEvent | ModeChangedEvent | SessionLimitsChangedEvent | PermissionsChangedEvent | PlanChangedEvent | TodosChangedEvent | MemoryChangedEvent | WorkspaceFileChangedEvent | HandoffEvent | TruncationEvent | SnapshotRewindEvent | ShutdownEvent | UsageCheckpointEvent | ContextChangedEvent | UsageInfoEvent | ContextClearedEvent | CompactionStartEvent | CompactionCompleteEvent | TaskCompleteEvent | UserMessageEvent | PendingMessagesModifiedEvent | AssistantTurnStartEvent | AssistantTurnRetryEvent | AssistantIntentEvent | AssistantServerToolProgressEvent | AssistantReasoningEvent | AssistantReasoningDeltaEvent | AssistantToolCallDeltaEvent | AssistantStreamingDeltaEvent | AssistantMessageEvent | AssistantMessageStartEvent | AssistantMessageDeltaEvent | AssistantTurnEndEvent | AssistantIdleEvent | AssistantUsageEvent | ModelCallFailureEvent | ModelCallStartEvent | AbortEvent | ToolUserRequestedEvent | ToolExecutionStartEvent | ToolExecutionPartialResultEvent | ToolExecutionProgressEvent | ToolExecutionCompleteEvent | ToolSearchActivatedEvent | SkillInvokedEvent | SubagentStartedEvent | SubagentCompletedEvent | SubagentFailedEvent | SubagentSelectedEvent | SubagentDeselectedEvent | HookStartEvent | HookEndEvent | HookProgressEvent | BinaryAssetEvent | SystemMessageEvent | SystemNotificationEvent | PermissionRequestedEvent | PermissionCompletedEvent | UserInputRequestedEvent | UserInputCompletedEvent | ElicitationRequestedEvent | ElicitationCompletedEvent | SamplingRequestedEvent | SamplingCompletedEvent | McpOauthRequiredEvent | McpOauthCompletedEvent | McpHeadersRefreshRequiredEvent | McpHeadersRefreshCompletedEvent | CustomNotificationEvent | ExternalToolRequestedEvent | ExternalToolCompletedEvent | CommandQueuedEvent | CommandExecuteEvent | CommandCompletedEvent | AutoModeSwitchRequestedEvent | AutoModeSwitchCompletedEvent | SessionLimitsExhaustedRequestedEvent | SessionLimitsExhaustedCompletedEvent | AutoModeResolvedEvent | ManagedSettingsResolvedEvent | ManagedSettingsEnforcedEvent | CommandsChangedEvent | CapabilitiesChangedEvent | ExitPlanModeRequestedEvent | ExitPlanModeCompletedEvent | ToolsUpdatedEvent | BackgroundTasksChangedEvent | FactoryRunUpdatedEvent | SkillsLoadedEvent | CustomAgentsUpdatedEvent | McpServersLoadedEvent | McpServerStatusChangedEvent | McpToolsListChangedEvent | McpResourcesListChangedEvent | McpPromptsListChangedEvent | ExtensionsLoadedEvent | CanvasOpenedEvent | CanvasRegistryChangedEvent | CanvasClosedEvent | CanvasUnavailableEvent | CanvasRecordedEvent | CanvasRemovedEvent | ExtensionsAttachmentsPushedEvent | McpAppToolCallCompleteEvent;

declare type SessionEventsApi = SessionApi["eventLog"];

/** Discriminant union of every {@link SessionEvent} `type` string. */
export declare type SessionEventType = SessionEvent["type"];

declare type SessionExtensionsApi = SessionApi["extensions"];

declare type SessionFactoryApi = Omit<SessionApi["factory"], "listRuns"> & SessionFactoryToolApi & {
    listRuns(params?: FactoryListRunsRequest): ReturnType<SessionApi["factory"]["listRuns"]>;
    waitForRun(params: {
        runId: string;
        signal?: AbortSignal;
    }): Promise<FactoryRunResult>;
    getRunWithName(params: {
        runId: string;
    }): Promise<{
        factoryName: string;
        run: FactoryRunResult;
    }>;
};

declare interface SessionFactoryToolApi {
    runFromTool(params: Parameters<SessionApi["factory"]["run"]>[0] & {
        toolCallId?: string;
    }): ReturnType<SessionApi["factory"]["run"]>;
    resumeFromTool(params: Parameters<SessionApi["factory"]["resume"]>[0] & {
        toolCallId?: string;
    }): ReturnType<SessionApi["factory"]["resume"]>;
}

export declare type SessionFeatureFlagService = IFeatureFlagService & Disposable_2;

declare type SessionFleetApi = SessionApi["fleet"];

/**
 * Abstract filesystem for session-scoped storage.
 *
 * Every {@link Session} has a `sessionFs` property that all session-scoped
 * file I/O (events, workspace, temp files, etc.) goes through. This decouples
 * the runtime from the host filesystem and enables SDK clients to supply their
 * own storage backend via JSON-RPC.
 *
 * The default implementation is {@link LocalSessionFs} which wraps the Rust
 * runtime's native local filesystem helpers.
 *
 * SDK clients can register as the session filesystem provider via
 * `sessionFs.setProvider`, which causes the server to create
 * {@link RpcSessionFs} instances rooted under the provider's session-state home
 * and route all I/O back to the client.
 *
 * Callers should construct paths using this instance's `sessionStatePath`,
 * `tmpdir`, and `join()` helpers. Methods treat the resulting string as a
 * SessionFs-native path and do not reinterpret it.
 */
declare abstract class SessionFs {
    private readonly sqliteSupported;
    /**
     * Per-session SQLite database, or `undefined` when the underlying
     * filesystem provider does not support SQLite.
     *
     * Lazily constructed: `sessionStatePath` is abstract and set by the
     * subclass after `super()` runs, so the native handle must be created on
     * first access rather than in the constructor.
     */
    private _sessionDatabase?;
    constructor(sqliteSupported: boolean);
    /**
     * Whether this provider backs {@link sessionDatabase}. Mirrored into the
     * native session registry so Rust-side SQLite consumers can skip
     * persistence entirely, exactly as a `undefined` `sessionDatabase` did.
     */
    get supportsSqlite(): boolean;
    get sessionDatabase(): SessionDatabaseHandle | undefined;
    /**
     * The initial working directory for the session.
     * This is the user's project directory. The runtime may change its own
     * mutable cwd later; this records the value at session creation time.
     */
    getInitialCwd(): string | undefined;
    /**
     * Root directory for session-scoped files (events, workspace,
     * checkpoints, temp files, etc.). May be undefined when the session
     * doesn't have a dedicated storage area (e.g., CCA runtime).
     */
    abstract readonly sessionStatePath: string | undefined;
    /**
     * Path convention used by this filesystem.
     * Consumers use this to construct paths with the correct separator
     * without calling back into the abstraction.
     */
    abstract readonly conventions: "windows" | "posix";
    /**
     * Absolute path for temporary files within this filesystem.
     * Large output handler and other temp-file consumers use this as their base directory.
     */
    abstract readonly tmpdir: string;
    /** Path separator for this filesystem's convention. */
    get sep(): string;
    /** Join path segments using this filesystem's convention separator. */
    join(...segments: string[]): string;
    /**
     * Returns the mutex key that should protect exclusive access to this
     * filesystem path. Local filesystems use the path directly; virtual
     * filesystems may override this to namespace identical virtual paths.
     */
    lockKey(path: string): string;
    /** Read a file's content as a UTF-8 string. */
    abstract readFile(path: string): Promise<string>;
    /** Stream a file's content split into lines, omitting the final empty line when the file ends with a newline. */
    abstract readFileStream(path: string, options: {
        split: "lines";
    }): AsyncIterable<string>;
    /** Write a string to a file, creating it if it doesn't exist, replacing if it does. */
    abstract writeFile(path: string, content: string, options?: {
        mode?: number;
    }): Promise<void>;
    /** Append a string to a file, creating it if it doesn't exist. */
    abstract appendFile(path: string, content: string, options?: {
        mode?: number;
    }): Promise<void>;
    /** Check whether a path exists. */
    abstract exists(path: string): Promise<boolean>;
    /** Get metadata for a file or directory. */
    abstract stat(path: string): Promise<SessionFsStat>;
    /** Create a directory. */
    abstract mkdir(path: string, options?: {
        recursive?: boolean;
        mode?: number;
    }): Promise<void>;
    /** List entries in a directory (names only, not full paths). */
    abstract readdir(path: string): Promise<string[]>;
    /** List entries in a directory with type information. */
    abstract readdirWithTypes(path: string): Promise<SessionFsDirEntry[]>;
    /** Remove a file or directory. */
    abstract rm(path: string, options?: {
        recursive?: boolean;
        force?: boolean;
    }): Promise<void>;
    /** Rename/move a file or directory. Used for atomic writes. */
    abstract rename(src: string, dest: string): Promise<void>;
    /**
     * Release resources held by this instance (e.g., open SQLite connections).
     * Called during session shutdown. Subclasses that hold resources should override
     * and call `super.dispose()`.
     */
    dispose(): Promise<void>;
    /** Execute a SQLite query against this session's database. */
    abstract sqliteQuery(queryType: SqliteQueryType, query: string, params?: Record<string, SqliteBindValue>): Promise<SessionFsSqliteResult | undefined>;
    /**
     * Execute statements atomically on the owning SQLite connection.
     *
     * Providers apply their SQLite busy timeout for every call. A
     * `busyOrLocked` error guarantees that the transaction was rolled back.
     */
    sqliteTransaction(_statements: SessionFsSqliteStatement[]): Promise<SessionFsSqliteResult[]>;
    /** Check whether the session database already exists (without creating it). */
    abstract sqliteExists(): Promise<boolean>;
    /**
     * Reverse-call handler for native code that needs to route I/O back
     * through this `SessionFs`. The base class returns a default handler
     * that dispatches each request to its own abstract methods, so any
     * non-local `SessionFs` works with native APIs that take a reverse-call
     * handler (workspace manager, RPC bridge, etc.) without subclasses
     * needing to implement the dispatch themselves.
     *
     * `LocalSessionFs` overrides this to return `undefined`, signaling that
     * the native side should perform operations directly against the local
     * filesystem instead of bouncing through JavaScript. RPC-backed
     * implementations may override to expose their own handler.
     */
    getReverseCallHandler(): SessionFsReverseCallHandler | undefined;
    /**
     * Session identifier used to address this session's resources over the
     * reverse-call channel. Only RPC-backed implementations have one; the base
     * (and local) filesystem returns `undefined`.
     */
    getSessionId(): string | undefined;
}

/** File path, content to append, and optional mode for the client-provided session filesystem. */
declare interface SessionFsAppendFileRequest {
    /** Content to append */
    content: string;
    /** Optional POSIX-style mode for newly created files */
    mode?: number;
    /** Path using SessionFs conventions */
    path: string;
}

/**
 * Directory entry with type information, returned by {@link SessionFs.readdirWithTypes}.
 */
declare interface SessionFsDirEntry {
    name: string;
    type: "file" | "directory";
}

/** Describes a filesystem error. */
declare interface SessionFsError {
    /** Error classification */
    code: SessionFsErrorCode;
    /** Free-form detail about the error, for logging/diagnostics */
    message?: string;
}

/** Error classification */
declare type SessionFsErrorCode = "ENOENT" | "UNKNOWN";

/** Path to test for existence in the client-provided session filesystem. */
declare interface SessionFsExistsRequest {
    /** Path using SessionFs conventions */
    path: string;
}

/** Indicates whether the requested path exists in the client-provided session filesystem. */
declare interface SessionFsExistsResult {
    /** Whether the path exists */
    exists: boolean;
}

/** Directory path to create in the client-provided session filesystem, with options for recursive creation and POSIX mode. */
declare interface SessionFsMkdirRequest {
    /** Optional POSIX-style mode for newly created directories */
    mode?: number;
    /** Path using SessionFs conventions */
    path: string;
    /** Create parent directories as needed */
    recursive?: boolean;
}

/** Directory path whose entries should be listed from the client-provided session filesystem. */
declare interface SessionFsReaddirRequest {
    /** Path using SessionFs conventions */
    path: string;
}

/** Names of entries in the requested directory, or a filesystem error if the read failed. */
declare interface SessionFsReaddirResult {
    /** Entry names in the directory */
    entries: string[];
    /** Describes a filesystem error. */
    error?: SessionFsError;
}

/** Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. */
declare interface SessionFsReaddirWithTypesEntry {
    /** Entry name */
    name: string;
    /** Entry type */
    type: SessionFsReaddirWithTypesEntryType;
}

/** Entry type */
declare type SessionFsReaddirWithTypesEntryType = "file" | "directory";

/** Directory path whose entries (with type information) should be listed from the client-provided session filesystem. */
declare interface SessionFsReaddirWithTypesRequest {
    /** Path using SessionFs conventions */
    path: string;
}

/** Entries in the requested directory paired with file/directory type information, or a filesystem error if the read failed. */
declare interface SessionFsReaddirWithTypesResult {
    /** Directory entries with type information */
    entries: SessionFsReaddirWithTypesEntry[];
    /** Describes a filesystem error. */
    error?: SessionFsError;
}

/** Path of the file to read from the client-provided session filesystem. */
declare interface SessionFsReadFileRequest {
    /** Path using SessionFs conventions */
    path: string;
}

/** File content as a UTF-8 string, or a filesystem error if the read failed. */
declare interface SessionFsReadFileResult {
    /** File content as UTF-8 string */
    content: string;
    /** Describes a filesystem error. */
    error?: SessionFsError;
}

/** Source and destination paths for renaming or moving an entry in the client-provided session filesystem. */
declare interface SessionFsRenameRequest {
    /** Destination path using SessionFs conventions */
    dest: string;
    /** Source path using SessionFs conventions */
    src: string;
}

/**
 * Callback that native Rust code uses to deliver a reverse-call request
 * back to JavaScript (RPC-backed `SessionFs` implementations only).
 * Local filesystems do not need a handler.
 */
declare type SessionFsReverseCallHandler = (call: SessionFsReverseCall) => void;

/** Path to remove from the client-provided session filesystem, with options for recursive removal and force. */
declare interface SessionFsRmRequest {
    /** Ignore errors if the path does not exist */
    force?: boolean;
    /** Path using SessionFs conventions */
    path: string;
    /** Remove directories and their contents recursively */
    recursive?: boolean;
}

/** Optional capabilities declared by the provider */
declare interface SessionFsSetProviderCapabilities {
    /** Whether the provider supports SQLite query/exists operations */
    sqlite?: boolean;
}

/** Path conventions used by this filesystem */
declare type SessionFsSetProviderConventions = "windows" | "posix";

/** Initial working directory, session-state path layout, and path conventions used to register the calling SDK client as the session filesystem provider. */
declare interface SessionFsSetProviderRequest {
    /** Optional capabilities declared by the provider */
    capabilities?: SessionFsSetProviderCapabilities;
    /** Path conventions used by this filesystem */
    conventions: SessionFsSetProviderConventions;
    /** Initial working directory for sessions */
    initialCwd: string;
    /** Path within each session's SessionFs where the runtime stores files for that session */
    sessionStatePath: string;
}

/** Indicates whether the calling client was registered as the session filesystem provider. */
declare interface SessionFsSetProviderResult {
    /** Whether the provider was set successfully */
    success: boolean;
}

/** Indicates whether the per-session SQLite database already exists. */
declare interface SessionFsSqliteExistsResult {
    /** Whether the session database already exists */
    exists: boolean;
}

/** SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call. */
declare interface SessionFsSqliteQueryRequest {
    /** Optional named bind parameters */
    params?: Record<string, unknown>;
    /** SQL query to execute */
    query: string;
    /** How to execute the query: 'exec' for DDL/multi-statement (no results), 'query' for SELECT (returns rows), 'run' for INSERT/UPDATE/DELETE (returns rowsAffected) */
    queryType: SessionFsSqliteQueryType;
}

/** Query results including rows, columns, and rows affected, or a filesystem error if execution failed. */
declare interface SessionFsSqliteQueryResult {
    /** Column names from the result set */
    columns: string[];
    /** Describes a filesystem error. */
    error?: SessionFsError;
    /** SQLite last_insert_rowid() value for INSERT. */
    lastInsertRowid?: number;
    /** For SELECT: array of row objects. For others: empty array. */
    rows: Record<string, unknown>[];
    /** Number of rows affected (for INSERT/UPDATE/DELETE) */
    rowsAffected: number;
}

/** How to execute the query: 'exec' for DDL/multi-statement (no results), 'query' for SELECT (returns rows), 'run' for INSERT/UPDATE/DELETE (returns rowsAffected) */
declare type SessionFsSqliteQueryType = "exec" | "query" | "run";

/**
 * Result of a SQLite query execution via {@link SessionFs.sqliteQuery}.
 */
declare interface SessionFsSqliteResult {
    /** For SELECT: array of row objects. For others: empty array. */
    rows: Record<string, unknown>[];
    /** Column names from the result set */
    columns: string[];
    /** Number of rows affected (for INSERT/UPDATE/DELETE) */
    rowsAffected: number;
    /** SQLite last_insert_rowid() value for INSERT. */
    lastInsertRowid?: number;
}

declare interface SessionFsSqliteStatement {
    queryType: SqliteQueryType;
    query: string;
    params?: Record<string, SqliteBindValue>;
}

/** Classified SQLite transaction failure. busyOrLocked guarantees rollback; postCommitAmbiguous must never be retried. */
declare interface SessionFsSqliteTransactionError {
    errorClass: SessionFsSqliteTransactionErrorClass;
    message: string;
}

/** SQLite transaction failure classification. */
declare type SessionFsSqliteTransactionErrorClass = "busyOrLocked" | "fatal" | "postCommitAmbiguous";

/** Statements to execute atomically. Providers apply busy handling for every call. */
declare interface SessionFsSqliteTransactionRequest {
    statements: SessionFsSqliteTransactionStatement[];
}

/** Per-statement results, or a classified transaction error. */
declare interface SessionFsSqliteTransactionResult {
    error?: SessionFsSqliteTransactionError;
    results: SessionFsSqliteQueryResult[];
}

/** One statement in an atomic SQLite transaction. */
declare interface SessionFsSqliteTransactionStatement {
    /** Optional named bind parameters. */
    params?: Record<string, unknown>;
    /** SQL statement to execute. */
    query: string;
    /** How to execute the statement. */
    queryType: SessionFsSqliteQueryType;
}

/**
 * Stat result for a file or directory in the session filesystem.
 */
declare interface SessionFsStat {
    isFile: boolean;
    isDirectory: boolean;
    size: number;
    mtime: Date;
    birthtime: Date;
}

/** Path whose metadata should be returned from the client-provided session filesystem. */
declare interface SessionFsStatRequest {
    /** Path using SessionFs conventions */
    path: string;
}

/** Filesystem metadata for the requested path, or a filesystem error if the stat failed. */
declare interface SessionFsStatResult {
    /** ISO 8601 timestamp of creation */
    birthtime: string;
    /** Describes a filesystem error. */
    error?: SessionFsError;
    /** Whether the path is a directory */
    isDirectory: boolean;
    /** Whether the path is a file */
    isFile: boolean;
    /** ISO 8601 timestamp of last modification */
    mtime: string;
    /** File size in bytes */
    size: number;
}

/** File path, content to write, and optional mode for the client-provided session filesystem. */
declare interface SessionFsWriteFileRequest {
    /** Content to write */
    content: string;
    /** Optional POSIX-style mode for newly created files */
    mode?: number;
    /** Path using SessionFs conventions */
    path: string;
}

declare type SessionGitHubAuthApi = SessionApi["gitHubAuth"];

declare type SessionHistoryApi = SessionApi["history"];

/** Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. */
declare interface SessionInstalledPlugin {
    /** Path where the plugin is cached locally */
    cache_path?: string;
    /** Whether the plugin is currently enabled */
    enabled: boolean;
    /** Installation timestamp (ISO-8601) */
    installed_at: string;
    /** Marketplace the plugin came from (empty string for direct repo installs) */
    marketplace: string;
    /** Plugin name */
    name: string;
    /** Source descriptor for direct repo installs (when marketplace is empty) */
    source?: SessionInstalledPluginSource;
    /** Per-plugin source fingerprint (a SHA-256 hash of the plugin's catalog source spec plus its resolved source subtree — NOT a Git commit SHA) captured at marketplace install/update time. Auto-update compares it against the freshly recomputed fingerprint to detect a content change that does not bump the version. Absent for pre-existing installs and for direct (non-marketplace) installs. */
    source_sha?: string;
    /** Installed version, if known */
    version?: string;
}

/** Source descriptor for direct repo installs (when marketplace is empty) */
declare type SessionInstalledPluginSource = string | SessionInstalledPluginSourceGitHub | SessionInstalledPluginSourceUrl | SessionInstalledPluginSourceLocal;

/** Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or full commit SHA, and optional subpath. */
declare interface SessionInstalledPluginSourceGitHub {
    path?: string;
    ref?: string;
    repo: string;
    /** Optional full 40-character hexadecimal commit SHA. */
    sha?: string;
    /** Constant value. Always "github". */
    source: "github";
}

/** Source descriptor for a direct local plugin install, with a local filesystem path. */
declare interface SessionInstalledPluginSourceLocal {
    path: string;
    /** Constant value. Always "local". */
    source: "local";
}

/** Source descriptor for a direct URL plugin install, with URL, optional ref or full commit SHA, and optional subpath. */
declare interface SessionInstalledPluginSourceUrl {
    path?: string;
    ref?: string;
    /** Optional full 40-character hexadecimal commit SHA. */
    sha?: string;
    /** Constant value. Always "url". */
    source: "url";
    url: string;
}

declare type SessionInstructionsApi = SessionApi["instructions"];

declare type SessionLimitPredictionApi = SessionApi["limitPrediction"];

/** Baseline data provenance for a prediction. */
declare interface SessionLimitPredictionBaselineData {
    /** End of the baseline data slice. */
    windowEnd: string;
    /** Start of the baseline data slice. */
    windowStart: string;
}

/** Client population used for the prediction baseline. */
declare type SessionLimitPredictionClientType = "cli-interactive" | "cli-prompt";

/** Explainable AI-credit session-limit prediction. */
declare interface SessionLimitPredictionDetails {
    /** Baseline data provenance. */
    baselineData: SessionLimitPredictionBaselineData;
    /** Client population used for the prediction. */
    clientType: SessionLimitPredictionClientType;
    /** Resolved model family when known. */
    family?: string;
    /** Model identifier used for lookup. */
    modelId: string;
    /** Recommended maximum AI credits for this session. */
    recommendedCap: number;
    /** Tier chosen as the recommended cap. */
    recommendedTier: SessionLimitPredictionTier;
    /** Baseline fallback level used to create the prediction. */
    source: SessionLimitPredictionSource;
    /** Key matched at the source level, such as a model id, family id, or `global`. */
    sourceKey: string;
    /** Ordered usage tiers and their AI-credit caps. */
    tiers: SessionLimitPredictionTierOption[];
}

/** Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. */
declare type SessionLimitPredictionRequest = {
    clientType?: SessionLimitPredictionClientType;
    modelId?: string;
};

/** Prediction result. Available results include prediction details; unavailable results include an explicit reason. */
declare type SessionLimitPredictionResult = {
    kind: "available";
    prediction: SessionLimitPredictionDetails;
} | {
    kind: "unavailable";
    reason: SessionLimitPredictionUnavailableReason;
};

/** Baseline fallback level used to create the prediction. */
declare type SessionLimitPredictionSource = "model" | "family" | "global";

/** Semantic usage tier used for a recommended cap or additional headroom. */
declare type SessionLimitPredictionTier = "recommended" | "additional_headroom" | "generous_headroom" | "maximum_headroom";

/** Semantic usage tier and its AI-credit cap. */
declare interface SessionLimitPredictionTierOption {
    /** AI-credit cap for this tier. */
    cap: number;
    tier: SessionLimitPredictionTier;
}

/** Reason a prediction could not be computed. */
declare type SessionLimitPredictionUnavailableReason = "auto_unresolved" | "no_model";

/** Session limits update details. Null clears the limits. */
export declare interface SessionLimitsChangedData {
    /** Current session limits, or null when no limits are active */
    sessionLimits: SessionLimitsConfig | null;
}

/** Session event "session.session_limits_changed". Session limits update details. Null clears the limits. */
export declare interface SessionLimitsChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session limits update details. Null clears the limits. */
    data: SessionLimitsChangedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.session_limits_changed". */
    type: "session.session_limits_changed";
}

/** Optional session limits. */
export declare interface SessionLimitsConfig {
    /** Maximum AI Credits allowed across the session's current accounting window. */
    maxAiCredits?: number;
}

/** Optional session limits. */
declare interface SessionLimitsConfig_2 {
    /** Maximum AI Credits allowed across the session's current accounting window. */
    maxAiCredits?: number;
}

/**
 * Optional session limits.
 *
 * These fields only model the caller's configured limits. Enforcement and
 * limit-exhaustion behavior are handled by the runtime layer that consumes this
 * configuration.
 */
declare interface SessionLimitsConfig_3 {
    /** Maximum AI Credits allowed across the session's current accounting window. */
    maxAiCredits?: number;
}

/** Session limit exhaustion prompt completion notification. */
export declare interface SessionLimitsExhaustedCompletedData {
    /** Request ID of the resolved request; clients should dismiss any UI for this request. */
    requestId: string;
    /** The user's selected session-limit action. */
    response: SessionLimitsExhaustedResponse;
}

/** Session event "session_limits_exhausted.completed". Session limit exhaustion prompt completion notification. */
export declare interface SessionLimitsExhaustedCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session limit exhaustion prompt completion notification. */
    data: SessionLimitsExhaustedCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session_limits_exhausted.completed". */
    type: "session_limits_exhausted.completed";
}

/** Session limit exhaustion notification requiring user action. */
export declare interface SessionLimitsExhaustedRequestedData {
    /** Configured max AI Credits for the current accounting window. */
    maxAiCredits: number;
    /** Unique identifier for this request; used to respond via session.ui.handlePendingSessionLimitsExhausted(). */
    requestId: string;
    /** AI Credits already consumed in the current accounting window. */
    usedAiCredits: number;
}

/** Session event "session_limits_exhausted.requested". Session limit exhaustion notification requiring user action. */
export declare interface SessionLimitsExhaustedRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session limit exhaustion notification requiring user action. */
    data: SessionLimitsExhaustedRequestedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session_limits_exhausted.requested". */
    type: "session_limits_exhausted.requested";
}

/** The user's selected action for an exhausted session limit. */
export declare interface SessionLimitsExhaustedResponse {
    /** Action selected by the user. */
    action: SessionLimitsExhaustedResponseAction;
    /** AI Credits to add to the current max when action is 'add'. */
    additionalAiCredits?: number;
    /** New absolute max AI Credits when action is 'set'. */
    maxAiCredits?: number;
}

/** Response from the exhausted session-limit dialog. */
declare type SessionLimitsExhaustedResponse_2 = SessionLimitsExhaustedResponse;

/** User action selected for an exhausted session limit. */
export declare type SessionLimitsExhaustedResponseAction = "add" | "set" | "unset" | "cancel";

/** Sessions matching the filter, ordered most-recently-modified first. */
declare interface SessionList {
    /** Sessions ordered most-recently-modified first. Discriminated by `isRemote`. */
    sessions: SessionListEntry[];
}

/** Local or remote session metadata entry. Narrow on `isRemote` to access source-specific fields. */
declare type SessionListEntry = LocalSessionMetadataValue | RemoteSessionMetadataValue;

/** Optional filter applied to the returned sessions */
declare interface SessionListFilter {
    /** Match sessions whose context.branch equals this value */
    branch?: string;
    /** Match sessions whose context.cwd equals this value */
    cwd?: string;
    /** Match sessions whose context.gitRoot equals this value */
    gitRoot?: string;
    /** Match sessions whose context.repository equals this value */
    repository?: string;
}

/** Queued repo-level startup prompts and the total hook command count after loading. */
declare interface SessionLoadDeferredRepoHooksResult {
    /** Total hook command count (user + plugin + repo) loaded for the session by this call. Captured atomically with startupPrompts so callers don't need to read a separate counter. */
    hookCount: number;
    /** Repo-level startup prompts queued from repo hook configs. Empty on resume, when no repo configs were pending, or when disableAllHooks is set. */
    startupPrompts: string[];
}

declare type SessionLogApi = Pick<SessionApi, "log">;

declare type SessionLoggingDisabledEvent = {
    kind: "session_logging_disabled";
    reason: "session-full" | "error";
    requestId?: string;
    responseBody?: string;
    statusCode?: number;
};

/** Log severity level. Determines how the message is displayed in the timeline. Defaults to "info". */
declare type SessionLogLevel = "info" | "warning" | "error";

declare type SessionLspApi = SessionApi["lsp"];

/** Enterprise permission policy expressed with the runtime's managed permission-rule syntax. */
declare interface SessionManagedPermissions {
    /** Permission rules that allow matching operations unless another managed source, deny, or ask rule restricts them. */
    allow?: string[];
    /** Permission rules that require explicit human approval. */
    ask?: string[];
    /** Permission rules that block matching operations. Deny has highest precedence. */
    deny?: string[];
    /** When set to `disable`, prevents bypass/allow-all permission modes. */
    disableBypassPermissionsMode?: DisableBypassPermissionsMode;
}

/** Managed settings an SDK host may inject at session startup. Only permissions are accepted in this initial contract. */
declare interface SessionManagedSettings {
    permissions?: SessionManagedPermissions;
}

declare type SessionMcpApi = Omit<SessionApi["mcp"], "oauth" | "headers" | "apps">;

declare type SessionMcpAppsApi = SessionApi["mcp"]["apps"];

declare type SessionMcpHeadersApi = SessionApi["mcp"]["headers"];

declare type SessionMcpOauthApi = SessionApi["mcp"]["oauth"];

declare type SessionMcpResourcesApi = SessionApi["mcp"]["resources"];

export declare interface SessionMetadata {
    readonly sessionId: string;
    readonly startTime: Date;
    readonly modifiedTime: Date;
    readonly summary?: string;
    readonly name?: string;
    readonly clientName?: string;
    readonly isRemote: boolean;
    readonly context?: SessionContext;
}

declare type SessionMetadataApi = SessionApi["metadata"];

/** Point-in-time snapshot of slow-changing session identifier and state fields */
declare interface SessionMetadataSnapshot {
    /** True when the session was detected to be in use by another process at construction time. Local consumers may surface a confirmation prompt before fully attaching. Always false for new sessions. */
    alreadyInUse: boolean;
    /** Runtime client name associated with the session (telemetry identifier). */
    clientName?: string;
    /** The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot') */
    currentMode: MetadataSnapshotCurrentMode;
    /** User-provided name supplied at session construction (via `--name`), if any. Immutable after construction. */
    initialName?: string;
    /** Whether this is a remote session (i.e., one whose runtime executes elsewhere and is steered through this process) */
    isRemote: boolean;
    /** ISO 8601 timestamp of when the session's persisted state was last modified on disk. For new sessions, equals startTime. For resumed sessions, reflects the previous modification time at construction. */
    modifiedTime: string;
    /** Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. */
    remoteMetadata?: MetadataSnapshotRemoteMetadata;
    /** Currently selected model identifier, if any */
    selectedModel?: string;
    /** The unique identifier of the session */
    sessionId: string;
    /** Current session limits, or null when no limits are active */
    sessionLimits: SessionLimitsConfig_2 | null;
    /** ISO 8601 timestamp of when the session started */
    startTime: string;
    /** Short human-readable summary of the session, if known. Omitted when no summary has been generated. */
    summary?: string;
    /** Absolute path to the session's current working directory */
    workingDirectory: string;
    /** Public-facing workspace metadata for this session, or null if the session has no associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, internal flags). */
    workspace: WorkspaceSummary;
    /** Absolute path to the session's workspace directory on disk, or null if the session has no associated workspace */
    workspacePath: string | null;
}

/** The session mode the agent is operating in */
export declare type SessionMode = "interactive" | "plan" | "autopilot";

/** The session mode the agent is operating in */
declare type SessionMode_2 = "interactive" | "plan" | "autopilot";

declare type SessionModeApi = SessionApi["mode"];

declare type SessionModelApi = SessionApi["model"];

/** The list of models available to this session. */
declare interface SessionModelList {
    /** Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). */
    list: unknown[];
    /** Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. */
    modelPriceCategories?: SessionModelPriceCategory[];
    /** Per-quota snapshots returned alongside the model list, keyed by quota type. */
    quotaSnapshots?: Record<string, unknown>;
}

/** Cost-category metadata for a CAPI model. */
declare interface SessionModelPriceCategory {
    id: string;
    priceCategory: ModelPickerPriceCategory;
}

declare type SessionNameApi = SessionApi["name"];

/** Session construction options. */
declare interface SessionOpenOptions {
    /** Additional content-exclusion policies to merge into the session policy set. */
    additionalContentExclusionPolicies?: SessionOpenOptionsAdditionalContentExclusionPolicy[];
    /** Additional directories the agent may access beyond the working directory. Each entry is granted to the session's file-access allow-list and surfaced to the model (system prompt context and `@`-mention completion). Absolute paths are recommended; a relative path is resolved against the session's working directory. Nonexistent or unresolvable entries are skipped with a warning. This is applied on both session creation and resume, and is not persisted: a resumed session that omits this option does not retain previously supplied directories (re-supply them, exactly as the CLI re-passes `--add-dir`). */
    additionalDirectories?: string[];
    /** Runtime context discriminator for agent filtering. */
    agentContext?: string;
    /** Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. */
    allowAllMcpServerInstructions?: boolean;
    /** Whether ask_user is explicitly disabled. */
    askUserDisabled?: boolean;
    /** Initial authentication info for the session. */
    authInfo?: AuthInfo_2;
    /** Allowlist of available tool names. */
    availableTools?: string[];
    /** Options scoped to the built-in CAPI (Copilot API) provider. */
    capi?: CapiSessionOptions;
    /** Structured client kind used for runtime behavior gates. */
    clientKind?: string;
    /** Identifier of the client driving the session. */
    clientName?: string;
    /** Whether commit-message coauthor trailers are enabled. */
    coauthorEnabled?: boolean;
    /** Override Copilot configuration directory. */
    configDir?: string;
    /** Whether auto-mode continuation is enabled. */
    continueOnAutoMode?: boolean;
    /** Override URL for the Copilot API endpoint. */
    copilotUrl?: string;
    /** Whether custom agents default to local-only execution. */
    customAgentsLocalOnly?: boolean;
    /** Parent engagement ID for detached child telemetry rollup. */
    detachedFromSpawningParentEngagementId?: string;
    /** Parent session ID for detached child telemetry rollup. */
    detachedFromSpawningParentSessionId?: string;
    /** Instruction source IDs disabled for this session. */
    disabledInstructionSources?: string[];
    /** MCP server names disabled for this session. Disabled servers are not started or authenticated on create or cold resume. */
    disabledMcpServers?: string[];
    /** Skill IDs disabled for this session. */
    disabledSkills?: string[];
    /** Experimental: enable native model citations (Anthropic models today), normalized onto the `assistant.message` event. Off by default; may change or be removed while the citations surface is experimental. */
    enableCitations?: boolean;
    /** Opt in to capturing file changes for session rewind and session diff. Capture cannot reconstruct changes made before it was enabled. On create it starts capture from the first turn. It is also honored on resume: for a session that already has tracked prior turns, tracking continues automatically even if this is omitted; passing it on resume additionally enables tracking for an eligible session that has no prior root turn yet. Resuming a session whose prior root turns were never tracked has no restorable baseline, so tracking stays disabled for it and rewind reports file change tracking as unavailable; the resume itself still succeeds, so sessions that predate tracking remain loadable. The opt-in is only rejected when the session can never track (a subagent session, or one without local session storage). It is intentionally absent from the mutable options update because enabling it after edits have occurred would create an incomplete, misleading baseline. Subagents share the parent session's capture store and are not tracked as separate rewind points: a file a subagent writes is attributed to whichever root user turn was open when the capture was staged, just before the tool body ran. A turn cannot open while a staged capture is still in flight, so a subagent tool that staged under the spawning turn stays attributed to it however late the write lands, while a capture it stages after the user's next message belongs to that later turn. Attribution decides which turn's rewind point counts and file preview include that write; it does not narrow which rewinds revert it, because a rewind restores every capture from the selected turn onward, so the earlier spawning turn reverts it as well. */
    enableFileChangeTracking?: boolean;
    /** Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. */
    enableManagedSettings?: boolean;
    /** Whether on-demand custom instruction discovery is enabled. */
    enableOnDemandInstructionDiscovery?: boolean;
    /** Whether shell-script safety heuristics are enabled. */
    enableScriptSafety?: boolean;
    /** Whether model responses stream as delta events. */
    enableStreaming?: boolean;
    /** How MCP server environment values are interpreted. */
    envValueMode?: SessionOpenOptionsEnvValueMode;
    /** Override directory for session event logs. */
    eventsLogDirectory?: string;
    /** Whether subagent callback events should be forwarded into the session event log sink. */
    eventsLogIncludesSubagents?: boolean;
    /** Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. */
    excludedBuiltinAgents?: string[];
    /** Denylist of tool names. */
    excludedTools?: string[];
    /** ExP assignment ('flight') data injected by an SDK integrator, in the same JSON shape the Copilot CLI fetches from the experimentation service (CopilotExpAssignmentResponse). When supplied this is fed into the FeatureFlagService exactly like CLI-fetched assignments and ExP-backed flags wait for it. When absent the session does not block on ExP. */
    expAssignments?: unknown;
    /** Feature-flag values resolved by the host. */
    featureFlags?: Record<string, boolean>;
    /** Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. */
    includedBuiltinAgents?: string[];
    /** Installed plugins visible to the session. */
    installedPlugins?: InstalledPlugin[];
    /** Stable integration identifier for analytics. */
    integrationId?: string;
    /** Whether experimental behavior is enabled. */
    isExperimentalMode?: boolean;
    /** Whether interactive shell sessions are logged. */
    logInteractiveShells?: boolean;
    /** Identifier sent to LSP-style integrations. */
    lspClientName?: string;
    /** Permissions-only enterprise policy injected by the SDK host at session create or resume. Composes restrictively with self-fetched and device policy and is not persisted. */
    managedSettings?: SessionManagedSettings;
    /** Maximum decoded byte size of a single inline model-facing binary tool result persisted in session events (default 10 MB). */
    maxInlineBinaryBytes?: number;
    /** Memory configuration for this session. */
    memory?: MemoryConfiguration;
    /** Initial model identifier. */
    model?: string;
    /** Initial model capability overrides. */
    modelCapabilitiesOverrides?: ModelCapabilitiesOverride_2;
    /** BYOK model definitions added to the selectable model list, each referencing a provider name. */
    models?: ProviderModelConfig_2[];
    /** Optional human-friendly session name. */
    name?: string;
    /** Custom model-provider configuration (BYOK). */
    provider?: ProviderConfig_2;
    /** Named BYOK provider connections, additive to CAPI auth. Combining with `provider` is rejected. */
    providers?: NamedProviderConfig_2[];
    /** Initial reasoning effort level. CAPI values are model-defined and validated against the selected model; BYOK providers may define additional values. When omitted, no effort override is applied. */
    reasoningEffort?: string;
    /** Initial reasoning summary mode for supported model clients. */
    reasoningSummary?: SessionOpenOptionsReasoningSummary;
    /** Telemetry-only remote-defaulted flag. */
    remoteDefaultedOn?: boolean;
    /** Telemetry-only remote exporting flag. */
    remoteExporting?: boolean;
    /** Whether this session supports remote steering. */
    remoteSteerable?: boolean;
    /** Whether the host is an interactive UI. */
    runningInInteractiveMode?: boolean;
    /** Resolved sandbox configuration. */
    sandboxConfig?: SandboxConfig;
    /** Capabilities enabled for this session. */
    sessionCapabilities?: SessionCapability[];
    /** Optional stable session identifier to use for a new session. */
    sessionId?: string;
    /** Initial session limits. */
    sessionLimits?: SessionLimitsConfig_2;
    /** Per-session settings for built-in shell tools. */
    shell?: ShellOptions;
    /**
     * Use shell.initProfile instead. Shell init profile.
     * @deprecated
     */
    shellInitProfile?: string;
    /** PowerShell process flags applied to built-in and user-requested shell commands. */
    shellProcessFlags?: string[];
    /** Additional directories to search for skills. */
    skillDirectories?: string[];
    /** Whether to skip custom instruction sources. */
    skipCustomInstructions?: boolean;
    /** Optional trajectory output file path. */
    trajectoryFile?: string;
    /** Initial output verbosity level for supported models. */
    verbosity?: Verbosity_3;
    /** Working directory to anchor the session. */
    workingDirectory?: string;
    /** Pre-resolved working-directory context for session startup. */
    workingDirectoryContext?: SessionContext_2;
}

/** Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated data, and scope. */
declare interface SessionOpenOptionsAdditionalContentExclusionPolicy {
    last_updated_at: unknown;
    rules: SessionOpenOptionsAdditionalContentExclusionPolicyRule[];
    /** Allowed values for the `SessionOpenOptionsAdditionalContentExclusionPolicyScope` enumeration. */
    scope: SessionOpenOptionsAdditionalContentExclusionPolicyScope;
    [key: string]: unknown;
}

/** Single content-exclusion rule supplied to `sessions.open` options, with paths, match conditions, and source. */
declare interface SessionOpenOptionsAdditionalContentExclusionPolicyRule {
    ifAnyMatch?: string[];
    ifNoneMatch?: string[];
    paths: string[];
    /** Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. */
    source: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource;
    [key: string]: unknown;
}

/** Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. */
declare interface SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource {
    name: string;
    type: string;
}

/** Allowed values for the `SessionOpenOptionsAdditionalContentExclusionPolicyScope` enumeration. */
declare type SessionOpenOptionsAdditionalContentExclusionPolicyScope = "repo" | "all";

/** How MCP server environment values are interpreted. */
declare type SessionOpenOptionsEnvValueMode = "direct" | "indirect";

/** Initial reasoning summary mode for supported model clients. */
declare type SessionOpenOptionsReasoningSummary = "none" | "concise" | "detailed";

/** Open a session by creating, resuming, attaching, connecting to a remote, or handing off. */
declare type SessionOpenParams = SessionsOpenCreate | SessionsOpenResume | SessionsOpenResumeLast | SessionsOpenAttach | SessionsOpenRemote | SessionsOpenCloud | SessionsOpenHandoff;

/** Result of opening a session. */
declare interface SessionOpenResult {
    /** Remote session metadata, present when status is `connected`. */
    metadata?: RemoteSessionMetadataValue;
    /** Handoff progress steps, present when status is `handed_off`. */
    progress?: SessionsOpenProgress[];
    /** Remote session ID, present when status is `connected`. */
    remoteSessionId?: string;
    /** In-process SessionClientApi handle for the opened session, returned to CLI callers as a transitional shortcut. Marked internal so the public SDK surface does not expose it; SDK consumers should construct per-session clients from `sessionId` instead. */
    sessionApi?: unknown;
    /** Opened session ID. Omitted when status is `not_found`. */
    sessionId?: string;
    /** Startup prompts queued by user-level hook configs at session creation. Only populated when status is `created`; resumed sessions return an empty array. */
    startupPrompts?: string[];
    /** Outcome of the open request. */
    status: SessionsOpenStatus;
}

export declare interface SessionOptions extends Partial<SessionMetadata> {
    clientName?: string;
    /**
     * Structured client kind used for behavior gates.
     * Unlike clientName, this is not a telemetry branding identifier and should not depend on a literal name.
     */
    clientKind?: SessionClientKind;
    /**
     * Internal session correlation IDs forwarded into session telemetry.
     * This is intentionally not part of the generated public shared API schemas,
     * and is applied only at construction time (not via {@link UpdatableSessionOptions}).
     * @internal
     */
    internalCorrelationIds?: SessionCorrelationIds;
    model?: string;
    integrationId?: string;
    /**
     * Reasoning effort level for models that support it.
     * CAPI values are model-defined and validated against the selected model.
     * BYOK providers may define additional values, which are passed through unchanged.
     * When omitted, no effort override is applied.
     */
    reasoningEffort?: ReasoningEffort;
    /**
     * Reasoning summary mode for models that support it.
     * When omitted, the client uses model/runtime defaults.
     */
    reasoningSummary?: ReasoningSummary_2;
    /**
     * Output verbosity level for supported models.
     * Ignored by providers that do not expose a real wire-level verbosity setting.
     */
    verbosity?: Verbosity_2;
    /**
     * self-fetches enterprise managed settings at session bootstrap (server
     * `managed_settings` endpoint + device MDM) using {@link authInfo}, and
     * applies them fail-closed. Hosts that resolve managed settings themselves
     * (e.g. the Copilot CLI) leave this unset to avoid a redundant fetch.
     * @default false
     */
    enableManagedSettings?: boolean;
    /**
     * Permissions-only enterprise policy injected by an SDK host at create or
     * resume. Composes restrictively with self-fetched and device policy.
     */
    managedSettings?: ClientManagedSettings;
    /**
     * Explicit override for whether OpenAI reasoning summaries should be requested.
     * When omitted, the client does not request reasoning summaries.
     * @deprecated Use reasoningSummary: "detailed" instead.
     */
    enableReasoningSummaries?: boolean;
    /**
     * Custom API provider configuration (BYOK - Bring Your Own Key).
     * When set, bypasses Copilot API authentication and uses this provider instead.
     */
    provider?: ProviderConfig;
    /**
     * Named BYOK provider connections (transport + credentials). Unlike the legacy
     * singular {@link provider}, these are additive: they coexist with Copilot API
     * auth so CAPI and BYOK models can be mixed within one session and across
     * sub-agents. Combining `providers`/`models` with `provider` is rejected.
     */
    providers?: NamedProviderConfig[];
    /**
     * BYOK model definitions added to the session's selectable model list, each
     * referencing a {@link NamedProviderConfig.name}. Each model's `id` is its
     * provider-local id; the session-wide **selection id** is the provider-qualified
     * `provider/id` (e.g. `acme/claude-sonnet`), which is what appears in the model
     * list and is passed to `switchTo`. Because selection ids are provider-qualified
     * they never collide with bare CAPI ids; duplicate selection ids are rejected.
     */
    models?: ProviderModelConfig[];
    /**
     * When true, do not attach session telemetry.
     * Used by the SDK server for BYOK sessions or when the caller explicitly opts out.
     */
    disableSessionTelemetry?: boolean;
    /**
     * Controls when sessionEnd hooks fire.
     *
     * - `per-turn` (default): fire after each agentic loop, preserving SDK/query behavior.
     * - `interactive`: defer sessionEnd hooks until explicit session shutdown.
     */
    sessionLifecycleMode?: "per-turn" | "interactive";
    /** SDK-supplied overrides for model capabilities, deep-merged over runtime defaults. */
    modelCapabilitiesOverrides?: ModelCapabilitiesOverride;
    /**
     * Context tier selected for models with tiered context pricing. The session
     * uses this to derive an effective `modelCapabilitiesOverrides` field-wise,
     * so that compaction, truncation, token-display, and request limits all
     * honor the selected tier. Persisted in `session.start` (and refreshed in
     * `session.resume`) so resume restores the exact tier without app-level
     * repair logic.
     */
    contextTier?: "default" | "long_context";
    /**
     * Experimental: when true, enables native model citations (Anthropic models
     * today). Citable tool output (e.g. web-search results) is materialized into
     * `search_result` blocks and citation emission is turned on, with results
     * normalized onto `assistant.message` events. Off by default. May change or
     * be removed while the citations surface is experimental.
     */
    enableCitations?: boolean;
    /**
     * Opt in to capturing file changes from the first turn for session rewind
     * and cumulative session diff. This is immutable after session creation,
     * except that resume may (re-)enable tracking via the resume-time opt-in or
     * a durable marker from a prior tracked run (see
     * `enableFileChangeTrackingForResume`); it still cannot start mid-history
     * for a session whose earlier turns were never captured.
     */
    enableFileChangeTracking?: boolean;
    /** Internal manager inherited by subagent sessions from their owning root session. */
    rewindManager?: SessionRewindManager;
    /**
     * Internal: set by {@link Session.fromEvents} to mark that the session is
     * being rehydrated from persisted events (resume) rather than freshly
     * created.
     */
    resumedFromEvents?: boolean;
    featureFlags?: FeatureFlags;
    /** Internal: concrete service owned by an existing session and inherited by child sessions. */
    featureFlagService?: IFeatureFlagService;
    isExperimentalMode?: boolean;
    /**
     * ExP assignment ("flight") data injected by an SDK integrator. When
     * supplied, it is fed into the session's FeatureFlagService exactly like
     * Copilot-CLI-fetched assignments and the session waits on ExP resolution.
     * When absent the session does not block on ExP. Must be supplied on every
     * create/resume — it is not persisted.
     */
    expAssignments?: CopilotExpAssignmentResponse;
    /** Whether this session supports remote steering via GitHub. */
    remoteSteerable?: boolean;
    /**
     * Whether remote exporting (with or without steering) is enabled for this session.
     * Telemetry-only: not persisted in session events.
     */
    remoteExporting?: boolean;
    /**
     * Whether remote steering was enabled by default via config settings rather than an explicit --remote flag.
     * Telemetry-only: not persisted in session events.
     */
    remoteDefaultedOn?: boolean;
    /**
     * The session ID of a "parent" interactive session that spawned this
     * session (e.g., a detached headless rem-agent run launched on
     * shutdown). When set, telemetry from this session is reported under
     * the parent's session_id so all activity rolls up as part of the
     * same user-perceived session.
     */
    detachedFromSpawningParentSessionId?: string;
    /**
     * The engagement ID of a "parent" interactive session that spawned
     * this session. When set, the child's `SessionTelemetry` reuses this
     * UUID instead of generating a fresh one, so detached follow-up work
     * (e.g. the rem-agent consolidation run) groups under the same
     * engagement as the parent for analytics like active-sitting time
     * and prompts-per-engagement. Telemetry-only; not persisted on the
     * Session itself.
     */
    detachedFromSpawningParentEngagementId?: string;
    availableTools?: string[];
    excludedTools?: string[];
    /**
     * Controls how {@link availableTools} and {@link excludedTools} combine when both are set.
     * Defaults to `"available"` (allowlist wins when set; matches CLI flag behavior).
     * SDK clients can opt into `"excluded"` to model "all except X" by combining the two
     * lists.
     */
    toolFilterPrecedence?: ToolFilterPrecedence;
    /**
     * List of tool names to exclude from the default agent (the built-in agent
     * that handles turns when no custom agent is selected). These tools remain
     * available to custom sub-agents that reference them.
     */
    defaultAgentExcludedTools?: string[];
    /**
     * Built-in subagents to include in this session. When specified, only these
     * built-ins are available, subject to runtime availability and exclusions.
     * Custom agents with the same name remain available.
     */
    includedBuiltinAgents?: string[];
    /**
     * Built-in subagents to exclude from this session. Excluded built-ins are
     * removed from task-tool discovery and cannot be dispatched unless a custom
     * agent with the same name is available.
     */
    excludedBuiltinAgents?: string[];
    /**
     * Whether to enable tree-sitter-based script safety assessment for shell commands.
     * When true, shell commands are classified as read-only or write using tree-sitter parsing,
     * allowing read-only commands to auto-execute without a permission prompt.
     * When false or undefined, all commands require permission approval.
     */
    enableScriptSafety?: boolean;
    /**
     * When true, suppresses tools_changed_notice injection in user messages.
     * Used by subagent sessions where tool initialization before send() causes
     * spurious tool-change detection.
     */
    suppressToolChangedNotice?: boolean;
    /**
     * Workspace path inherited from a parent session. Used by subagent sessions
     * that don't have their own workspace but need the parent's path so the tool
     * pipeline creates the same tools (e.g., sql tool requires workspacePath).
     */
    parentWorkspacePath?: string;
    /**
     * Shell context inherited from a parent session. When set, the session shares
     * the parent's InteractiveShellToolContext so subagent shell commands appear in
     * the parent's /tasks dialog. The session will NOT shut down inherited shells on dispose.
     */
    parentShellContext?: InteractiveShellToolContext;
    /**
     * Session-root concurrency limiter inherited by child sessions.
     * @internal
     */
    subAgentLimiter?: SubAgentLimiter;
    /**
     * Callback for publishing inbox entries from sidekick agents.
     * Inherited by child sessions so the `send_inbox` tool is created in the tool pipeline.
     */
    sendInboxPublisher?: SendInboxPublisher;
    /**
     * The parent turn's agent task ID. Set on child sessions so CAPI requests
     * include X-Parent-Agent-Id for parent-child request correlation.
     */
    parentAgentTaskId?: string;
    /**
     * Native session whose event log defines this session's prompt-cache
     * lineage.
     *
     * A subagent runs on its own native session with its own event log, so its
     * root event is unique to it. Resolving a lineage from that log would give
     * every sibling in a fan-out a separate prompt-cache shard even though they
     * share one session id and a byte-identical prompt prefix, so
     * `createSubagentSession` points the child at the parent's log instead.
     *
     * This names the log rather than carrying a resolved id so a subagent
     * created before its parent recorded any durable event still reports the
     * parent's lineage once the parent has one.
     * @internal
     */
    promptCacheLineageSessionId?: string;
    /**
     * Controls which profile/startup scripts the shell sources during initialization.
     * @see ShellInitProfile
     */
    shellInitProfile?: ShellInitProfile_2;
    /**
     * Custom flags passed to the shell process on startup (e.g., PowerShell flags).
     * Overrides the default flags for the shell type.
     */
    shellProcessFlags?: string[];
    /** Process flags from grouped shell options, applied only to built-in shell tools. */
    shellToolProcessFlags?: string[];
    /** Startup scripts sourced by runtime-owned built-in shell tools. */
    shellInitScripts?: readonly ShellInitScript_2[];
    /** Sandbox configuration for shell commands. */
    sandboxConfig?: SandboxConfig_4;
    /** Whether to log raw interactive shell PTY data to the session state directory. */
    logInteractiveShells?: boolean;
    skillDirectories?: string[];
    /** Whether ambient repo/user config discovery is enabled for skills, commands, and custom agents. */
    enableConfigDiscovery?: boolean;
    /**
     * Whether to discover custom instructions on demand after successful file views
     * (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing).
     *
     * Combined with `skipCustomInstructions`.
     * Defaults to false. CLI sessions opt into this by spreading `cliSessionDefaults()`.
     */
    enableOnDemandInstructionDiscovery?: boolean;
    /**
     * Maximum decoded byte size of a single model-facing binary tool result
     * (e.g. an image) persisted inline in session events and re-presented to the
     * model on subsequent turns / resume. Results larger than this are persisted
     * as a metadata-only marker and replaced with a short text note on read-back.
     * Applies to both the persist and resume flows. Defaults to
     * the native default maximum inline binary size (10 MB).
     */
    maxInlineBinaryBytes?: number;
    disabledSkills?: Set<string>;
    /**
     * When true, enables loading of `.github/hooks/` filesystem hooks.
     * Separate from the `hooks` option (which provides SDK callback hook handlers).
     * SDK sessions default to false; CLI sessions set their own defaults.
     */
    enableFileHooks?: boolean;
    /**
     * When true, enables host git operations (context resolution, child repo scanning,
     * git info in system prompt). SDK sessions default to false.
     */
    enableHostGitOperations?: boolean;
    /**
     * When true, enables cross-session store writes and reads.
     * SDK sessions default to false.
     */
    enableSessionStore?: boolean;
    /**
     * When true, enables skill directory scanning and loading.
     * Falls back to enableConfigDiscovery when not explicitly set.
     */
    enableSkills?: boolean;
    installedPlugins?: InstalledPlugin[];
    pluginActivationPolicy?: SessionPluginActivationPolicy;
    pluginActivationSnapshot?: EffectivePluginSnapshot;
    mcpServers?: Record<string, MCPServerConfig>;
    /** Per-session GitHub MCP override persisted across cold resume. */
    githubMcpToolConfig?: GitHubMcpToolConfig_2;
    /** Whether the user explicitly widened the built-in GitHub MCP tool surface. */
    githubMcpUserOverride?: boolean;
    envValueMode?: EnvValueMode;
    disabledMcpServers?: string[];
    /**
     * When true, initialization instructions from all MCP servers are included
     * in the system prompt. Defaults to allowlisted servers only.
     */
    allowAllMcpServerInstructions?: boolean;
    customAgents?: SweCustomAgent[];
    selectedCustomAgent?: SweCustomAgent;
    /** When true, only load custom agents from local sources (skip remote org/enterprise agents). */
    customAgentsLocalOnly?: boolean;
    /**
     * When true, the selected custom agent's prompt is NOT injected into the user message.
     * Used by automation triggers (e.g. interval) where the agent prompt has already been
     * placed into the problem statement, to avoid duplicating the instruction. Skill context
     * configured on the agent is still injected.
     */
    suppressCustomAgentPrompt?: boolean;
    /**
     * Additional directories to search for external custom instruction files.
     * AGENTS.md files may live directly in these directories.
     * `*.instructions.md` files may live directly in these directories or under
     * a `.github/instructions` child directory.
     */
    instructionDirectories?: string[];
    organizationCustomInstructions?: string;
    skipCustomInstructions?: boolean;
    /** Set of instruction source IDs to exclude from the system prompt */
    disabledInstructionSources?: ReadonlySet<string>;
    /**
     * When true, skip embedding retrieval pipeline initialization and execution.
     * Used by subagent sessions — they inherit the parent's prompt context.
     */
    skipEmbeddingRetrieval?: boolean;
    /**
     * Controls how embedding cache data is stored.
     * - `"persistent"`: Uses a shared on-disk SQLite database (default for CLI; enables cross-restart caching).
     * - `"in-memory"`: Uses a session-scoped in-memory SQLite database (default for SDK; ensures per-session isolation).
     *
     * When unset, defaults to `"persistent"` behavior.
     */
    embeddingCacheStorage?: "persistent" | "in-memory";
    /** Whether to include co-authored-by trailer instructions in the system prompt. Defaults to true. */
    coauthorEnabled?: boolean;
    systemMessage?: SystemMessageConfig;
    /**
     * Runtime-owned hook session handle. Declarative hooks, policy ordering, and
     * SDK callback descriptors are held by the native runtime.
     * @internal
     */
    hookSessionHandle?: number;
    /**
     * Shared native hook facade for an in-process subagent session.
     * @internal
     */
    nativeHookProcessor?: NativeHookProcessor;
    /**
     * Whether this session must dispose its native hook session handle.
     * @internal
     */
    ownsHookSession?: boolean;
    externalToolDefinitions?: ExternalToolDefinition[];
    /**
     * SDK-supplied override for the runtime's built-in tool-search behavior. When
     * provided, the runtime swaps in the client's tool-search handler, prompt
     * instructions, and/or deferral threshold instead of the built-in defaults.
     */
    toolSearch?: SessionToolSearchOptions;
    /**
     * SDK-supplied per-session control over provider-native web search. Setting
     * `enabled: false` suppresses it for this session and for every subagent
     * dispatched from it.
     */
    webSearch?: SessionWebSearchOptions;
    trajectoryFile?: string;
    eventsLogDirectory?: string;
    eventsLogIncludesSubagents?: boolean;
    /**
     * Path to the session transcript (events.jsonl file).
     * Used by hooks to access the full conversation transcript.
     */
    transcriptPath?: string;
    /** Optional pre-created session filesystem. When omitted, a LocalSessionFs backed by the local disk is used. */
    sessionFs?: SessionFs;
    /**
     * Optional per-session MCP OAuth store. When provided, injects an {@link InMemoryMCPOAuthStore}
     * (or a custom implementation) so that per-session OAuth flows never touch
     * the host's system keychain or `~/.copilot/` filesystem.
     *
     * When omitted, a keychain-backed store is created via {@link getMCPOAuthStore}.
     */
    mcpOAuthStore?: MCPOAuthStoreInterface;
    /**
     * Optional host callback that supplies short-lived dynamic headers for
     * remote MCP servers. When set, all remote MCP servers may request dynamic
     * headers; per-server `headersRefreshTtlMs` only customizes cache TTL.
     */
    onMcpHeadersRefresh?: HeadersRefreshCallback;
    workingDirectory?: string;
    /**
     * Additional directories the agent may access beyond the working directory.
     *
     * Each entry is granted to the session's file-access allow-list (path
     * manager) and surfaced to the model (system prompt context and `@`-mention
     * completion). Absolute paths are recommended; a relative path is resolved
     * against the session's {@link workingDirectory}. Nonexistent or
     * unresolvable entries are skipped with a warning rather than failing a turn.
     *
     * Applied on both session creation and resume. Not persisted: a resumed
     * session that omits this option does not retain previously supplied
     * directories, so callers must re-supply them (this mirrors how the CLI
     * re-passes `--add-dir` on each launch). A later
     * `session.permissions.configure({ paths })` call is authoritative and
     * replaces the path policy, including these directories.
     */
    additionalDirectories?: string[];
    /**
     * Pre-resolved working directory context (git root, branch, HEAD, remote, merge-base).
     * When provided, createSession skips its own getWorkingDirectoryContext call,
     * using this value instead. Callers can start resolution early
     * to overlap with other async work (auth, terminal detection).
     */
    workingDirectoryContext?: Promise<GitWorkingDirectoryContext> | GitWorkingDirectoryContext;
    /**
     * Repository name for the session context.
     * Used for memory service scoping, code search, and other repository-aware features.
     * Format: "owner/repo" (e.g., "github/copilot-cli")
     */
    repositoryName?: string;
    authInfo?: AuthInfo;
    copilotUrl?: string;
    /**
     * When `true`, the runtime
     * self-fetches enterprise managed settings at session bootstrap (server
     * `managed_settings` endpoint + device MDM) using {@link authInfo}, and
     * applies them fail-closed. Hosts that resolve managed settings themselves
     * (e.g. the Copilot CLI) leave this unset to avoid a redundant fetch.
     * @default false
     */
    selfFetchManagedSettings?: boolean;
    enableStreaming?: boolean;
    /**
     * CAPI (Copilot API) provider options. Scoped under `capi` so transport and
     * behavior settings that only apply to the built-in Copilot provider stay
     * separate from BYOK provider configuration (which can coexist in the same
     * session).
     */
    capi?: CapiSessionOptions_2;
    largeOutput?: LargeToolOutputConfig;
    /** Whether ask_user is explicitly disabled (autonomous mode). When true, system prompt encourages independent action. */
    askUserDisabled?: boolean;
    /** When true, automatically switch to auto mode on eligible rate limit errors instead of pausing. */
    continueOnAutoMode?: boolean;
    /**
     * Session-level autopilot continuation driver. When enabled, the session
     * itself observes turn completion in autopilot mode and re-prompts the
     * agent when it stops without calling `task_complete`, rather than
     * requiring each host to implement the continuation loop.
     *
     * Hosts that want to drive the loop themselves (or interleave their own
     * UI between continuation turns) can leave this disabled and listen for
     * `session.idle` instead.
     */
    autopilotContinuation?: AutopilotContinuationConfig;
    /**
     * Callback invoked when exit_plan_mode tool is called. Shows approval dialog and returns user response.
     *
     * Note: setting this callback wires a responder for the tool, but the tool
     * is only exposed to the model while the session is in plan mode
     * (`agentMode === "plan"`). Outside plan mode the tool is hidden even if
     * this callback is set.
     */
    onExitPlanMode?: (request: ExitPlanModeRequest) => Promise<ExitPlanModeResponse>;
    /**
     * Whether to expose the `manage_schedule` tool to the agent. The
     * runtime always owns a per-session schedule registry (so schema
     * callers can list/add/stop entries unconditionally); this flag only
     * controls whether the agent itself can see the tool. Set by hosts
     * that want to enable scheduled-prompt behavior (e.g., the CLI for
     * staff users).
     */
    manageScheduleEnabled?: boolean;
    /**
     * Explicit tool names this session needs. Non-standard tools (send_inbox, etc.)
     * are only created by toolInit when listed here. Set by createSubagentSession
     * from the agent definition's tools array.
     */
    requestedTools?: string[];
    /** Runtime context for filtering builtin agents (e.g., "cli", "cca", "sdk"). */
    agentContext?: AgentContext;
    /** Whether the CLI is running in interactive mode. Defaults to true. When false, uses non-interactive identity and excludes plan mode instructions. */
    runningInInteractiveMode?: boolean;
    /**
     * Optional memory configuration for this session.
     * When omitted, the session uses its default memory capability behavior.
     */
    memory?: MemoryConfiguration;
    /**
     * Capabilities enabled for this session. Controls prompt content, tool availability, and behaviors.
     * If not specified, defaults to the Rust-owned default session capability set.
     * @see SessionCapability for available capabilities
     */
    sessionCapabilities?: Set<SessionCapability>;
    /**
     * Custom configuration directory for the session.
     * When set, overrides the default Copilot config directory (~/.copilot or $COPILOT_HOME).
     */
    configDir?: string;
    /**
     * Runtime settings for persistence and workspace resolution.
     * Used to resolve config/state paths consistently.
     */
    runtimeSettings?: RuntimeSettingsInput;
    /**
     * Infinite session configuration for persistent workspaces and automatic compaction.
     * When enabled, sessions automatically manage context limits and persist state.
     * Can be set to `true` for defaults, `false` to disable, or a config object for fine-tuning.
     * @default { enabled: true }
     */
    infiniteSessions?: InfiniteSessionConfig | boolean;
    /**
     * Optional session limits for the current accounting window.
     *
     * This is configuration-only at session construction/update time; runtime
     * enforcement is implemented by the limits-aware execution layer.
     */
    sessionLimits?: SessionLimitsConfig_3;
    /**
     * Additional content exclusion policies beyond those fetched from the API.
     * Session uses these along with authInfo and featureFlags.CONTENT_EXCLUSION
     * to auto-create the ContentExclusionService.
     */
    additionalContentExclusionPolicies?: ContentExclusionApiResponse[];
    /**
     * Client name to use for LSP sessions.
     */
    lspClientName?: string;
    /**
     /**
     * W3C Trace Context traceparent header for distributed tracing.
     * When set, the session's OTel spans are parented to the caller's trace context.
     */
    traceparent?: string;
    /** W3C Trace Context tracestate header for distributed tracing. */
    tracestate?: string;
    /** Runtime-internal resolver for OTel trace context propagation on MCP tool calls. */
    mcpTraceContextResolver?: TraceContextResolver;
    /** Runtime-internal resolver for updating or clearing the parent trace context for a turn. */
    otelParentContextResolver?: (traceparent: string | undefined, tracestate: string | undefined) => void;
    /** Runtime-internal delegate used by SDK server sessions to manage remote steering. */
    remoteDelegate?: SessionRemoteDelegate;
    /** Runtime-internal server-level sessions API used by session slash commands that manage persisted sessions. */
    sessionsApi?: SessionsApi;
    /** Runtime-internal sender used by SDK server sessions to stream shell output and exits. */
    shellNotifier?: ShellNotificationSender;
    /** Runtime-internal telemetry sender installed at construction time. */
    telemetrySender?: DisposableTelemetrySender;
    /** Runtime-internal extension controller installed at construction time. */
    extensionController?: ExtensionController;
    /**
     * When true on a resumed session, the agentic loop awaits in-flight
     * permission and external-tool requests until they reach a terminal state.
     * User sends are queued behind that pending work in the normal way.
     *
     * When false or omitted, and the session has no live work, resume
     * immediately marks any tool calls or permission requests that were in
     * flight at suspend as interrupted. The session resumes in a clean state,
     * and subsequent sends run with no resume-specific code paths active.
     * Joining a session with live work — an agent turn, a native queue run, a
     * queued resume continuation, or an in-flight send in this runtime — is
     * always passive and preserves work owned by the current client.
     */
    continuePendingWork?: boolean;
    /**
     * CAPI interaction type for this session's API requests.
     * Defaults to "conversation-agent". Subagent sessions use "conversation-subagent".
     */
    interactionType?: "conversation-agent" | "conversation-subagent";
    /**
     * If this session is for a sub-agent of another session, then the depth of this session
     * from its root ancestor. Defaults to 0 (top-level session). Subagent sessions are created
     * with parentDepth + 1.
     */
    subAgentDepth?: number;
    /**
     * Returns whether the plan-mode write gate is currently active in the
     * parent session, consulted live at each tool-call classification. Set on
     * subagent sessions spawned from a plan-mode parent so delegated work
     * inherits the same no-mutations behavior — and keeps inheriting it as the
     * parent's mode changes, rather than snapshotting the mode at construction.
     */
    parentPlanModeWriteGateActive?: () => boolean;
    /**
     * Native session ids of this session's plan-mode ancestors, outermost first.
     * The native write gate re-reads each ancestor's live mode on every tool
     * batch, so a background subagent that outlives its parent's mode change
     * still inherits the gate (the `parentPlanModeWriteGateActive` closure can
     * only be evaluated in-process, and is therefore a snapshot once it crosses
     * into the runtime).
     */
    parentPlanModeWriteGateSessionIds?: string[];
    /**
     * Stable child trajectory id (typically the dispatching task tool's `toolCallId`)
     * when this session represents a subagent invocation. Distinct from `sessionId`,
     * which identifies the CLI session as a whole.
     *
     * Outer sessions leave this undefined. Subagent sessions created via
     * `Session.createSubagentSession()` set this to the stable child trajectory id so that
     * hook payloads, which contract to surface the per-invocation id as their
     * `sessionId` field, can read the session's stable agent identity.
     */
    agentId?: string;
    /**
     * Stable identity of the immediate parent trajectory. Set for subagent
     * sessions and propagated to provider callbacks. Session events expose the
     * child `agentId` separately and do not include parent trajectory identity.
     */
    parentAgentId?: string;
    /**
     * Agent task ID that should be treated as this session's current registry
     * anchor for list_agent/write_agent visibility. Set only for subagent
     * sessions that are executing an already-registered multi-turn agent.
     */
    taskRegistryAgentId?: string;
    /** Runtime-derived factory run that owns this session's model usage. */
    factoryUsageRunId?: string;
    /** Shared accounting coordinator for the factory usage run. */
    factoryUsageCoordinator?: FactoryUsageCoordinator;
    /**
     * Optional handler for permission requests. When set, the session delegates
     * all permission requests (from tools like bash, edit, create) to this handler
     * instead of using its own `pendingRequests`.
     *
     * Used by subagent sessions to bubble permission dialogs up to the parent
     * session's CLI UI.
     *
     * When `request.managedApprovalRequired` is true, an approving handler must
     * set `managedApprovalHandled: true` only after obtaining a human response.
     * Managed session/location approvals are treated as one-time approvals.
     */
    parentPermissionRequestHandler?: (request: PermissionRequest_2) => Promise<PermissionRequestResult>;
    /** @deprecated Use {@link parentPermissionRequestHandler}. */
    permissionRequestHandler?: (request: PermissionRequest_2) => Promise<PermissionRequestResult>;
}

declare type SessionOptionsApi = SessionApi["options"];

declare type SessionPermissionsApi = SessionApi["permissions"];

declare type SessionPlanApi = SessionApi["plan"];

declare interface SessionPluginActivationPolicy {
    readonly includeAmbient: boolean;
    readonly explicitPlugins: readonly InstalledPlugin[];
    readonly trust: EffectivePluginTrustContext;
}

declare type SessionPluginsApi = SessionApi["plugins"];

declare type SessionProviderApi = SessionApi["provider"];

/** Outcome of the prune operation: deleted IDs, dry-run candidates, skipped IDs, total bytes freed, and the dry-run flag. */
declare interface SessionPruneResult {
    /** Session IDs that would be deleted in dry-run mode (always empty otherwise) */
    candidates: string[];
    /** Session IDs that were deleted (always empty in dry-run mode) */
    deleted: string[];
    /** True when no deletions were actually performed */
    dryRun: boolean;
    /** Total bytes freed (actual when not dry-run, projected when dry-run) */
    freedBytes: number;
    /** Session IDs that were skipped (e.g., named sessions) */
    skipped: string[];
}

declare type SessionQueueApi = SessionApi["queue"];

declare type SessionRemoteApi = SessionApi["remote"];

declare interface SessionRemoteDelegate {
    enable(mode?: "off" | "export" | "on"): Promise<{
        url?: string;
        remoteSteerable: boolean;
    }>;
    disable(): Promise<void>;
}

/**
 * Session-scoped owner of the native rewind capture store: turn bookkeeping,
 * capture draining, and the exclusivity needed by the rewind reads.
 *
 * **Subagent attribution.** Subagents do not get their own manager — they
 * inherit the root session's, so their file writes land in the same capture
 * store. A tracked write is attributed to whichever root user turn was open
 * when its capture was *staged* (in {@link stageToolPreimages}, before the tool
 * body runs), not to the turn that spawned the agent and not to the moment the
 * write itself lands: {@link beginTurn} drains active captures, so a turn
 * cannot open while a staged capture is still in flight, and a subagent tool
 * that staged under the spawning turn stays attributed to it however late it
 * settles. A subagent that stages a *new* capture after the user's next message
 * has opened a later turn is attributed to that later turn. Attribution decides
 * which turn's point counts and preview report the write, not whether an
 * earlier rewind reverts it: a restore replays every capture from the selected
 * turn onward, so rewinding to the spawning turn reverts the write too. This is
 * deliberate: the capture is a record of what the workspace looked like at each
 * turn boundary, and a turn boundary cannot "un-see" edits that were already on
 * disk when it opened.
 */
declare class SessionRewindManager implements FileSnapshotCapture {
    private readonly native;
    private readonly initialization;
    private readonly operationMutex;
    private activeCaptures;
    private captureDrain?;
    private closing;
    private disposed;
    constructor(sessionId: string, basePath: string);
    beginTurn(eventId: string, userMessage: string): Promise<void>;
    stageToolPreimages(paths: string[]): Promise<void>;
    recordToolResult(paths: string[]): Promise<void>;
    finalize(): Promise<void>;
    /**
     * Reads (`listRewindPoints`, `previewRestore`, `sessionDiff`) all
     * {@link finalize} first, and the session gates them behind its rewind
     * exclusivity, so they can only run when no work that might mutate files is
     * in flight. That is deliberate rather than incidental: the counts, preview,
     * and cumulative diff describe the capture set a restore would consider, and
     * a capture whose postimage has not landed yet would make them describe a
     * half-written turn. They are an upper bound rather than an exact prediction
     * — restore is ownership-safe and additionally skips any path whose current
     * content no longer matches the postimage Copilot last wrote, so a file the
     * user edited afterwards is previewed but reported as skipped. Callers that
     * hit the resulting `session-busy` reason should retry once the session
     * settles.
     */
    listRewindPoints(userTurns: RewindUserTurn[]): Promise<HistoryRewindPoint[]>;
    previewRestore(eventId: string, orderedEventIds: string[]): Promise<NativeRestorePreview>;
    restoreFiles(eventId: string, orderedEventIds: string[]): Promise<NativeRestoreResult>;
    prune(eventIds: string[]): Promise<void>;
    sessionDiff(cwd: string, ignoreWhitespace?: boolean): Promise<WorkspaceDiffFileChange[]>;
    dispose(): Promise<void>;
    runExclusive<T>(operation: () => Promise<T>): Promise<T>;
    private waitForActiveCaptures;
    /**
     * Like {@link waitForActiveCaptures} but resolves after `timeoutMs` even if
     * captures have not drained, so a stuck (never-recorded) capture cannot
     * block disposal indefinitely. The native `dispose()` that follows runs
     * under its own operation mutex, and a late `recordToolResult` no-ops once
     * `disposed` is set, so proceeding after the deadline is safe.
     */
    private waitForActiveCapturesBounded;
    private finishCapture;
    private throwIfDisposed;
}

/** Metadata for a session row. */
declare interface SessionRow {
    id: string;
    cwd?: string;
    repository?: string;
    host_type?: "github" | "ado";
    branch?: string;
    summary?: string;
    created_at?: string;
    updated_at?: string;
}

declare type SessionsApi = ServerApi["sessions"];

/** Session IDs to close, deactivate, and delete from disk. */
declare interface SessionsBulkDeleteRequest {
    /** Session IDs to close, deactivate, and delete from disk */
    sessionIds: string[];
}

/** Session IDs to test for live in-use locks. */
declare interface SessionsCheckInUseRequest {
    /** Session IDs to test for live in-use locks */
    sessionIds: string[];
}

/** Session IDs from the input set that are currently in use by another process. */
declare interface SessionsCheckInUseResult {
    /** Session IDs from the input set that are currently held by another running process via an alive lock file */
    inUse: string[];
}

declare type SessionScheduleApi = Omit<SessionApi["schedule"], "addSelfPaced"> & {
    setCommandResolver?(resolver: ScheduledCommandResolver | undefined): void;
    hasSelfPaced(): ScheduleHasSelfPacedResult | Promise<ScheduleHasSelfPacedResult>;
    add(params: ScheduleAddRequest & {
        origin?: ScheduleOrigin;
    }): ScheduleAddResult | Promise<ScheduleAddResult>;
    addCron(params: ScheduleAddCronRequest & {
        origin?: ScheduleOrigin;
    }): ScheduleAddResult | Promise<ScheduleAddResult>;
    addAt(params: ScheduleAddAtRequest & {
        origin?: ScheduleOrigin;
    }): ScheduleAddResult | Promise<ScheduleAddResult>;
    rearmSelfPaced(params: ScheduleRearmSelfPacedRequest): ScheduleAddResult | Promise<ScheduleAddResult>;
    stop(params: {
        id: number;
    }): ScheduleStopResult | Promise<ScheduleStopResult>;
    addSelfPaced?(params: ScheduleAddSelfPacedRequest & {
        origin?: ScheduleOrigin;
    }): ScheduleAddResult | Promise<ScheduleAddResult>;
};

/** Session ID to close. */
declare interface SessionsCloseRequest {
    /** Session ID to close */
    sessionId: string;
}

/** Closes a session: emits shutdown, flushes pending events to disk, releases the in-use lock, disposes the active session. Idempotent: succeeds even if the session is not currently active. */
declare interface SessionsCloseResult {
}

/** Session ID to delete from disk. */
declare interface SessionsDeleteRequest {
    /** Session ID to delete */
    sessionId: string;
    /** Internal resolved session directory path to delete */
    sessionPath?: string | null;
}

/**
 * Optional context for the session-search sidekick agent, used to populate
 * the system prompt with a snapshot of the current session's problem statement,
 * repo, and branch.
 */
declare type SessionSearchPromptContext = {
    settings: RuntimeSettings_2;
    logger: RunnerLoggerContract;
    problemStatement: string;
    repoNwo?: string;
    currentSessionId?: string;
    callback?: IAgentCallback;
    telemetryEmitter?: TelemetryEmitter;
};

/** Session metadata records to enrich with summary and context information. */
declare interface SessionsEnrichMetadataRequest {
    /** Session metadata records to enrich. Records that already have summary and context are returned unchanged. */
    sessions: LocalSessionMetadataValue[];
}

/** New auth credentials to install on the session. Omit to leave credentials unchanged. */
declare interface SessionSetCredentialsParams {
    /** The new auth credentials to install on the session. When omitted or `undefined`, the call is a no-op and the session's existing credentials are preserved. The runtime installs the supplied value immediately for outbound model/API requests. When the credential carries a raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous install) so plan/quota/billing metadata regains fidelity; on resolution failure the verbatim credential remains installed. It does NOT otherwise validate the credential. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. */
    credentials?: AuthInfo_2;
}

/** Indicates whether the credential update succeeded. */
declare interface SessionSetCredentialsResult {
    /** Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). */
    copilotUserResolved?: boolean;
    /** Whether the operation succeeded */
    success: boolean;
}

declare type SessionSettingsApi = SessionApi["settings"];

/** Availability of built-in job tools surfaced to boundary consumers. */
declare interface SessionSettingsBuiltInToolAvailabilitySnapshot {
    createPullRequest?: boolean;
    reportProgress?: boolean;
}

/** Named Rust-owned settings predicate to evaluate for this session. */
declare interface SessionSettingsEvaluatePredicateRequest {
    /** Predicate name. The runtime owns the raw feature-flag names and composition logic. */
    name: SessionSettingsPredicateName;
    /** Tool name for tool-scoped predicates such as trivial-change handling. */
    toolName?: string;
}

/** Result of evaluating a Rust-owned settings predicate. */
declare interface SessionSettingsEvaluatePredicateResult {
    enabled: boolean;
}

/** Redacted job settings for a session. The job nonce is excluded. */
declare interface SessionSettingsJobSnapshot {
    builtInToolAvailability?: SessionSettingsBuiltInToolAvailabilitySnapshot;
    eventType?: string;
    isTriggerJob?: boolean;
}

/** Redacted model routing settings for a session. */
declare interface SessionSettingsModelSnapshot {
    callbackUrl?: string;
    defaultReasoningEffort?: string;
    instanceId?: string;
    model?: string;
}

/** Online-evaluation settings safe to expose across the SDK boundary. */
declare interface SessionSettingsOnlineEvaluationSnapshot {
    disableOnlineEvaluation?: boolean;
    enableOnlineEvaluationOutputFile?: boolean;
}

/** Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names are intentionally not part of the contract. */
declare type SessionSettingsPredicateName = "securityToolsEnabled" | "thirdPartySecurityPromptEnabled" | "parallelValidationEnabled" | "runtimeTimingTelemetryEnabled" | "coAuthorHookEnabled" | "chronicleEnabled" | "contentExclusionSelfFetchEnabled" | "capClaudeOpusTokenLimitsEnabled" | "codeReviewFeatureEnabled" | "ccaUseTsAutofindEnabled" | "dependencyCheckerEnabled" | "dependabotCheckerEnabled" | "codeqlCheckerEnabled" | "trivialChangeEnabled" | "trivialChangeSkipEnabled" | "trivialChangeEnabledForCodeReview" | "trivialChangeSkipEnabledForCodeReview" | "trivialChangeEnabledForTool" | "trivialChangeSkipEnabledForTool";

/** Redacted repository and GitHub host settings for a session. */
declare interface SessionSettingsRepoSnapshot {
    branch?: string;
    commit?: string;
    host?: string;
    hostProtocol?: string;
    id?: number;
    name?: string;
    ownerId?: number;
    ownerName?: string;
    prCommitCount?: number;
    readWrite?: boolean;
    secretScanningUrl?: string;
    serverUrl?: string;
}

/** Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. */
declare interface SessionSettingsSnapshot {
    clientName?: string;
    job: SessionSettingsJobSnapshot;
    model: SessionSettingsModelSnapshot;
    onlineEvaluation: SessionSettingsOnlineEvaluationSnapshot;
    repo: SessionSettingsRepoSnapshot;
    startTimeMs?: number;
    timeoutMs?: number;
    validation: SessionSettingsValidationSnapshot;
    version?: string;
}

/** Redacted validation and memory-tool settings for a session. */
declare interface SessionSettingsValidationSnapshot {
    advisoryEnabled?: boolean;
    codeReviewEnabled?: boolean;
    codeReviewModel?: string;
    codeqlEnabled?: boolean;
    dependabotTimeout?: number;
    memoryStoreEnabled?: boolean;
    memoryVoteEnabled?: boolean;
    secretScanningEnabled?: boolean;
    timeout?: number;
}

/** UUID prefix to resolve to a unique session ID. */
declare interface SessionsFindByPrefixRequest {
    /** UUID prefix (>=7 hex chars, <36 chars). Returns the unique session ID, or undefined when there is no match or the prefix matches multiple sessions. */
    prefix: string;
}

/** Session ID matching the prefix, omitted when no unique match exists. */
declare interface SessionsFindByPrefixResult {
    /** Omitted when no unique session matches the prefix (no match or ambiguous) */
    sessionId?: string;
}

/** GitHub task ID to look up. */
declare interface SessionsFindByTaskIDRequest {
    /** GitHub task ID to look up */
    taskId: string;
}

/** ID of the local session bound to the given GitHub task, or omitted when none. */
declare interface SessionsFindByTaskIDResult {
    /** Omitted when no local session is bound to that GitHub task */
    sessionId?: string;
}

/** Source session identifier to fork from, optional event-ID boundary, and optional friendly name for the new session. */
declare interface SessionsForkRequest {
    /** Optional friendly name to assign to the forked session. */
    name?: string;
    /** Source session ID to fork from */
    sessionId: string;
    /** Optional event ID boundary. When provided, the fork includes only events before this ID (exclusive). When omitted, all events are included. */
    toEventId?: string;
}

/** Identifier and optional friendly name assigned to the newly forked session. */
declare interface SessionsForkResult {
    /** Friendly name assigned to the forked session, if any. */
    name?: string;
    /** The new forked session's ID */
    sessionId: string;
}

/** Session ID whose board entry count should be returned. */
declare interface SessionsGetBoardEntryCountRequest {
    /** Session ID whose board entry count should be returned. */
    sessionId: string;
}

/** Dynamic-context board entry count, when available. */
declare interface SessionsGetBoardEntryCountResult {
    /** Board entry count, when available. */
    count?: number;
}

/** Session ID whose event-log file path to compute. */
declare interface SessionsGetEventFilePathRequest {
    /** Session ID whose event-log file path to compute */
    sessionId: string;
}

/** Absolute path to the session's events.jsonl file on disk. */
declare interface SessionsGetEventFilePathResult {
    /** Absolute path to the session's events.jsonl file */
    filePath: string;
}

/** Optional working-directory context used to score session relevance. */
declare interface SessionsGetLastForContextRequest {
    /** Optional working-directory context used to score session relevance. When omitted the most-recently-modified session wins. */
    context?: SessionContext_2;
}

/** Most-relevant session ID for the supplied context, or omitted when no sessions exist. */
declare interface SessionsGetLastForContextResult {
    /** Most-relevant session ID for the supplied context, or omitted when no sessions exist */
    sessionId?: string;
}

/** Session ID whose persisted metadata should be read. */
declare interface SessionsGetMetadataRequest {
    /** Session ID to inspect */
    sessionId: string;
}

/** Persisted local session metadata when the session exists. */
declare interface SessionsGetMetadataResult {
    /** Local session metadata, omitted when the session does not exist. */
    session?: LocalSessionMetadataValue;
}

/** Session ID to look up the persisted remote-steerable flag for. */
declare interface SessionsGetPersistedRemoteSteerableRequest {
    /** Session ID to look up the persisted remote-steerable flag for */
    sessionId: string;
}

/** The session's persisted remote-steerable flag, or omitted when no value has been persisted. */
declare interface SessionsGetPersistedRemoteSteerableResult {
    /** The session's persisted remote-steerable flag if recorded; omitted when no value has been persisted */
    remoteSteerable?: boolean;
}

/** Map of sessionId -> on-disk size in bytes for each session's workspace directory. */
declare interface SessionSizes {
    /** Map of sessionId -> on-disk size in bytes for the session's workspace directory */
    sizes: Record<string, number>;
}

declare type SessionSkillsApi = SessionApi["skills"];

/** Limit for non-empty local session IDs. */
declare interface SessionsListNonEmptySessionIdsRequest {
    /** Maximum number of session IDs to return. */
    limit?: number;
}

/** Recent local session IDs that contain user-visible history. */
declare interface SessionsListNonEmptySessionIdsResult {
    /** Session IDs ordered newest-first. */
    sessionIds: string[];
}

/** Optional source filter, metadata-load limit, and context filter applied to the returned sessions. */
declare type SessionsListRequest = {
    filter?: SessionListFilter;
    includeDetached?: boolean;
    metadataLimit?: number;
    source?: SessionSource;
    throwOnError?: boolean;
};

/** Active session ID whose deferred repo-level hooks should be loaded. */
declare interface SessionsLoadDeferredRepoHooksRequest {
    /** Active session ID whose deferred repo-level hooks should be loaded */
    sessionId: string;
}

/** Parameters for attaching to an already-active session by ID. */
declare interface SessionsOpenAttach {
    /** Attach to an already-active in-process session by ID. Unlike `resume`, this does NOT re-load from disk; the session must already be loaded by an earlier `create`/`resume` call. Returns `status: 'not_found'` when no active session matches the id. Useful for in-process consumers that need a fresh API handle to a session opened elsewhere (e.g., a peer foreground-session switch). */
    kind: "attach";
    /** Session ID to attach to. */
    sessionId: string;
}

/** Parameters for creating a new cloud session. */
declare interface SessionsOpenCloud {
    /** Create a new cloud (coding-agent) session. */
    kind: "cloud";
    /** In-process callback invoked when the cloud task is created (before connection). Marked internal because a function reference cannot cross the JSON-RPC boundary. Disappears in the SDK migration: the field is purely cosmetic (it flips a single CLI phase label from 'creating' to 'connecting') and the wire-clean version just drops the intermediate phase. */
    onTaskCreated?: unknown;
    /** Session options for cloud session creation. */
    options?: SessionOpenOptions;
    /** Optional owner (user or organization login) to associate with the cloud session when no repository is provided. Ignored when `repository` is set (the repo's owner takes precedence). */
    owner?: string;
    /** Repository for the cloud session. */
    repository?: RemoteSessionRepository;
}

/** Parameters for creating a new local session. */
declare interface SessionsOpenCreate {
    /** Whether to emit session.start during creation. Defaults to true. */
    emitStart?: boolean;
    /** Create a new local session. */
    kind: "create";
    /** Session construction options. */
    options?: SessionOpenOptions;
}

/** Parameters for fetching a remote session and handing it off to a new local session. */
declare interface SessionsOpenHandoff {
    /** Fetch a remote session and hand it off to a new local session. */
    kind: "handoff";
    /** Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). */
    metadata: RemoteSessionMetadataValue;
    /** In-process confirmation callback `(request) => boolean | Promise<boolean>` invoked when the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch between the current working directory and the remote session). Returning `true` proceeds with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal because a function reference cannot cross the JSON-RPC boundary, for the same reasons as `onProgress`. */
    onConfirm?: unknown;
    /** In-process progress callback `(update) => void` invoked for each handoff step. Marked internal because a function reference cannot cross the JSON-RPC boundary. The host-side `handoffSession` is already declared as `AsyncGenerator<HandoffProgress, HandoffResult>`; the schema layer flattens it because it does not yet support streaming methods. The wire-clean replacement is to expose the AsyncGenerator directly (or use vscode-jsonrpc `$/progress` notifications) once the schema/transport layer supports it. */
    onProgress?: unknown;
    /** Session construction options for the new local session. */
    options?: SessionOpenOptions;
    /** Task type determines the handoff strategy (CCA fetches events; CLI prepares a transient session). */
    taskType?: SessionsOpenHandoffTaskType;
}

/** Task type determines the handoff strategy (CCA fetches events; CLI prepares a transient session). */
declare type SessionsOpenHandoffTaskType = "cca" | "cli";

/** `sessions.open` handoff progress update with step, status, and optional message. */
declare interface SessionsOpenProgress {
    /** Optional step message. */
    message?: string;
    /** Step status. */
    status: SessionsOpenProgressStatus;
    /** Handoff step. */
    step: SessionsOpenProgressStep;
}

/** Step status. */
declare type SessionsOpenProgressStatus = "in-progress" | "complete";

/** Handoff step. */
declare type SessionsOpenProgressStep = "load-session" | "validate-repo" | "check-changes" | "checkout-branch" | "create-session" | "save-session";

/** Parameters for connecting to a live remote session. */
declare interface SessionsOpenRemote {
    /** Connect to a live remote session. */
    kind: "remote";
    /** Session options for the connection. */
    options?: SessionOpenOptions;
    /** Remote session identifier to connect to. */
    remoteSessionId: string;
    /** Repository context for the remote session. */
    repository?: RemoteSessionRepository;
}

/** Parameters for resuming a specific local session. */
declare interface SessionsOpenResume {
    /** Resume a specific local session by ID or prefix. */
    kind: "resume";
    /** Session resume options. */
    options?: SessionOpenOptions;
    /** Whether to emit session.resume after loading. Defaults to true. */
    resume?: boolean;
    /** Session ID or unique prefix to resume. */
    sessionId: string;
    /** Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. */
    suppressResumeWorkspaceMetadataWriteback?: boolean;
}

/** Parameters for resuming the most relevant local session. */
declare interface SessionsOpenResumeLast {
    /** Working-directory context used to choose the most relevant session. */
    context?: SessionContext_2;
    /** Resume the most relevant existing local session. */
    kind: "resumeLast";
    /** Session resume options. */
    options?: SessionOpenOptions;
    /** Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. */
    suppressResumeWorkspaceMetadataWriteback?: boolean;
}

/** Outcome of the open request. */
declare type SessionsOpenStatus = "created" | "resumed" | "not_found" | "connected" | "handed_off";

/** Which session sources to include. Defaults to `local` for backward compatibility. */
declare type SessionSource = "local" | "remote" | "all";

/** Age threshold and optional flags controlling which old sessions are pruned (or simulated when dryRun is true). */
declare interface SessionsPruneOldRequest {
    /** When true, only report what would be deleted without performing any deletion */
    dryRun?: boolean;
    /** Session IDs that should never be considered for pruning */
    excludeSessionIds?: string[];
    /** When true, named sessions (set via /rename) are also eligible for pruning */
    includeNamed?: boolean;
    /** Delete sessions whose modifiedTime is at least this many days old */
    olderThanDays: number;
}

/** Optional registration options. */
declare interface SessionsRegisterExtensionToolsOnSessionOptions {
    /** In-process `() => boolean` gating callback (CLI-only optimization). Marked internal: replaced by runtime-side enable/disable RPCs in the SDK migration. */
    enabled?: unknown;
}

/** Session ID whose in-use lock should be released. */
declare interface SessionsReleaseLockRequest {
    /** Session ID whose in-use lock should be released */
    sessionId: string;
}

/** Release the in-use lock held by this process for the given session. No-op when this process does not currently hold a lock for the session. */
declare interface SessionsReleaseLockResult {
}

/** Active session ID and an optional flag for deferring repo-level hooks until folder trust. */
declare interface SessionsReloadPluginHooksRequest {
    /** When true, skip repo-level hooks. Use before folder trust is confirmed; loadDeferredRepoHooks loads them post-trust. */
    deferRepoHooks?: boolean;
    /** Active session ID to reload hooks for */
    sessionId: string;
}

/** Reload all hooks (user, plugin, optionally repo) and apply them to the active session. Call after installing or removing plugins so their hooks take effect immediately. No-op when no active session matches the given sessionId. */
declare interface SessionsReloadPluginHooksResult {
}

/** Session ID whose pending events should be flushed to disk. */
declare interface SessionsSaveRequest {
    /** Session ID whose pending events should be flushed to disk */
    sessionId: string;
}

/** Flush a session's pending events to disk. No-op when no writer exists for the session (e.g., already closed). */
declare interface SessionsSaveResult {
}

/** Manager-wide additional plugins to register; replaces any previously-configured set. */
declare interface SessionsSetAdditionalPluginsRequest {
    /** Manager-wide additional plugins to register. Replaces any previously-configured set. Pass an empty array to clear. */
    plugins: InstalledPlugin[];
}

/** Replace the manager-wide additional plugins. New session creations and subsequent hook reloads see the new set; already-running sessions keep their existing hook installation until the next reload. */
declare interface SessionsSetAdditionalPluginsResult {
}

/** Patch for the singleton's steering state. */
declare interface SessionsSetRemoteControlSteeringRequest {
    /** Target steering state. Today only `true` is actionable on the underlying exporter; `false` is reserved for future use. */
    enabled: boolean;
}

/** Parameters for attaching the remote-control singleton to a session. */
declare interface SessionsStartRemoteControlRequest {
    /** Configuration for the runtime-managed remote-control singleton. */
    config: RemoteControlConfig;
    /** Local session id to attach remote control to. */
    sessionId: string;
}

/** Parameters for stopping the remote-control singleton. */
declare type SessionsStopRemoteControlRequest = {
    expectedSessionId?: string;
    force?: boolean;
};

/**
 * Public contract for the global session store.
 *
 * Every method is implemented natively by `nativeRuntime.SessionStoreHandle`:
 * SQLite access, dynamic value revival, row normalization, default timestamps,
 * input serialization, connection caching, transactions, and lifecycle all
 * live in the Rust runtime. This interface is only a typed view over the
 * native handle — no behavior lives in TypeScript.
 */
declare interface SessionStore {
    getPath(): string;
    close(checkpoint?: boolean): boolean;
    upsertSession(session: SessionRow): void;
    insertTurn(turn: TurnRow): void;
    insertCheckpoint(checkpoint: CheckpointRow): void;
    flushTrackingForSession(sessionId: string): {
        nonFatalError?: string;
    };
    handleTrackingEventForSession(sessionId: string, eventJson: string, forgeTrackingEnabled: boolean, workspacePath?: string): {
        nonFatalError?: string;
        postToolUseInputJson?: string;
        needsTextResult: boolean;
    };
    applyPostToolUseTrackingAndForgeSummaryForSession(sessionId: string, inputJson: string): {
        errorsJson: string;
        artifactToIndex?: string;
    };
    insertFile(file: FileRow): void;
    insertRef(ref: RefRow): void;
    insertForgeTrajectoryEvent(event: ForgeTrajectoryEventRow): void;
    insertAssistantUsageEvent(event: AssistantUsageEventRow): Promise<void>;
    getForgeTrajectoryEvents(sessionId: string): Promise<ForgeTrajectoryEventRow[]>;
    getForgeTrajectoryEventsForScope(scope?: ForgeTrajectoryScope): Promise<ForgeTrajectoryEventRow[]>;
    forgeSummaryTelemetryEventJsonForSession(sessionId: string, trackingEnabled: boolean): Promise<string | null>;
    getForgeSkillProposalById(id: string): ForgeSkillProposalRecord | undefined;
    listForgeSkillProposals(scope: ForgeSkillProposalScope, statuses?: readonly ForgeSkillProposalStatus[]): Promise<ForgeSkillProposalRecord[]>;
    getForgeSkillProposalByFingerprint(scope: ForgeSkillProposalScope, fingerprint: string, statuses?: readonly ForgeSkillProposalStatus[]): ForgeSkillProposalRecord | undefined;
    beginForgeSkillProposalGeneration(input: {
        id: string;
        scope: ForgeSkillProposalScope;
        triggerMode: ForgeSkillProposalTriggerMode;
        workspaceBeforeByPath?: Record<string, string>;
        createdAt?: string;
    }): ForgeSkillProposalRecord;
    getForgeSkillProposalWorkspaceBefore(id: string): Record<string, string> | undefined;
    completeForgeSkillProposalGeneration(input: {
        id: string;
        fingerprint: string;
        manifest: ForgeSkillProposalManifestEntry[];
        summary?: ForgeSkillProposalSummary;
        updatedAt?: string;
    }): ForgeSkillProposalRecord | undefined;
    transitionForgeSkillProposalStatus(input: {
        id: string;
        status: ForgeSkillProposalStatus;
        expectedStatuses?: readonly ForgeSkillProposalStatus[];
        supersededBy?: string;
        failureReason?: string;
        updatedAt?: string;
    }): boolean;
    failStaleGeneratingForgeSkillProposals(scope: ForgeSkillProposalScope, staleBeforeIso: string): number;
    getDynamicContextBoard(repository: string, branch: string): Promise<DynamicContextBoardEntry[]>;
    getDynamicContextItem(repository: string, branch: string, src: string, name: string): DynamicContextItemRow | undefined;
    incrementDynamicContextReadCount(repository: string, branch: string, src: string, name: string): boolean;
    incrementDynamicContextCount(repository: string, branch: string): void;
    insertDynamicContextItem(item: DynamicContextItemRow): boolean;
    upsertDynamicContextItem(item: DynamicContextItemRow): void;
    deleteDynamicContextItem(repository: string, branch: string, src: string, name: string): boolean;
    indexWorkspaceArtifact(sessionId: string, filePath: string, content: string): Promise<void>;
    indexWorkspaceArtifactByPath(sessionId: string, filePath: string): Promise<void>;
    search(query: string, limit?: number): Promise<SearchResult[]>;
    getSession(sessionId: string): SessionRow | undefined;
    getTurns(sessionId: string): TurnRow[];
    getCheckpoints(sessionId: string): CheckpointRow[];
    getFiles(sessionId: string): FileRow[];
    getRefs(sessionId: string): RefRow[];
    executeReadOnly<T = Record<string, unknown>>(sql: string): T[];
    executeReadOnlyAsync<T = Record<string, unknown>>(sql: string): Promise<T[]>;
    executeReadOnlyWithCap(sql: string, limit: number): Promise<LocalQueryResult>;
    getMaxTurnIndex(sessionId: string): number;
    getStats(): StoreStats;
    reindexLocal(sessionStatePath: string, nowIso: string): Promise<StoreStats>;
    exec(sql: string): void;
}

/**
 * The session store is a native class owned by the Rust runtime. Constructing
 * it with a database path returns a handle whose SQLite connection is lazily
 * opened and shared (cached by path) inside the runtime.
 */
declare const SessionStore: {
    new (dbPath: string): SessionStore;
};

/** Parameters for atomically rebinding the remote-control singleton. */
declare interface SessionsTransferRemoteControlRequest {
    /** When provided, the transfer is rejected unless the singleton currently points at this session id (compare-and-swap semantics to avoid clobbering newer state). */
    expectedFromSessionId?: string;
    /** Local session id to point remote control at. */
    toSessionId: string;
}

declare type SessionTasksApi = SessionApi["tasks"];

declare type SessionTelemetryApi = SessionApi["telemetry"];

/** Telemetry engagement ID for the session, when available. */
declare interface SessionTelemetryEngagement {
    /** Current telemetry engagement ID, when available. */
    engagementId?: string;
}

declare type SessionToolsApi = SessionApi["tools"];

/**
 * SDK-supplied configuration for the runtime's built-in tool-search behavior.
 *
 * To override the tool's model-facing definition and/or its execution, register
 * an {@link SessionOptions.externalToolDefinitions} entry named `tool_search_tool`
 * with `overridesBuiltInTool: true`. To customize the in-prompt tool-search
 * guidance, use the `tool_instructions` section of
 * {@link SessionOptions.systemMessage} in `customize` mode.
 */
declare interface SessionToolSearchOptions {
    /**
     * Explicit on/off switch that overrides the `TOOL_SEARCH` feature flag /
     * experiment assignment in both directions. When `true`, models with native
     * search keep that path and other function-calling models use generic
     * client-side search regardless of the model rollout allowlist or the general
     * `TOOL_SEARCH` flag. Generic search still requires the
     * `TOOL_SEARCH_CLIENT_GENERIC` feature flag. The `TOOL_SEARCH_DISABLED` kill
     * switch remains authoritative. When `false`, tool search is forced off.
     * Leave unset to defer to rollout configuration.
     */
    enabled?: boolean;
    /**
     * Overrides the total tool count at which MCP and external tools are
     * automatically deferred behind tool search. Defaults to the built-in
     * threshold (30) when omitted.
     */
    deferThreshold?: number;
}

declare type SessionUiApi = SessionApi["ui"];

/** Patch of mutable session options to apply to the running session. */
declare interface SessionUpdateOptionsParams {
    /** Additional content-exclusion policies to merge into the session's policy set. */
    additionalContentExclusionPolicies?: OptionsUpdateAdditionalContentExclusionPolicy[];
    /** Runtime context discriminator (e.g., `cli`, `actions`). */
    agentContext?: string;
    /** Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. */
    allowAllMcpServerInstructions?: boolean;
    /** Whether to disable the `ask_user` tool (encourages autonomous behavior). */
    askUserDisabled?: boolean;
    /** Allowlist of tool names available to this session. */
    availableTools?: string[];
    /** Options scoped to the built-in CAPI (Copilot API) provider. */
    capi?: CapiSessionOptions;
    /** Identifier of the client driving the session. */
    clientName?: string;
    /** Whether to include the `Co-authored-by` trailer in commit messages. */
    coauthorEnabled?: boolean;
    /** Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. */
    contextTier?: OptionsUpdateContextTier;
    /** Whether to allow auto-mode continuation across turns. */
    continueOnAutoMode?: boolean;
    /** Override URL for the Copilot API endpoint. */
    copilotUrl?: string;
    /** Whether to default custom agents to local-only execution. */
    customAgentsLocalOnly?: boolean;
    /** Instruction source IDs to exclude from the system prompt. */
    disabledInstructionSources?: string[];
    /** Skill IDs that should be excluded from this session. */
    disabledSkills?: string[];
    /** Whether to enable loading of `.github/hooks/` filesystem hooks. Separate from the SDK callback hook mechanism. */
    enableFileHooks?: boolean;
    /** Whether to enable host git operations (context resolution, child repo scanning, git info in system prompt). */
    enableHostGitOperations?: boolean;
    /** Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions`. */
    enableOnDemandInstructionDiscovery?: boolean;
    /** Whether to surface reasoning-summary events from the model. */
    enableReasoningSummaries?: boolean;
    /** Whether shell-script safety heuristics are enabled. */
    enableScriptSafety?: boolean;
    /** Whether to enable cross-session store writes and reads. */
    enableSessionStore?: boolean;
    /** Whether to enable skill directory scanning and loading. Falls back to enableConfigDiscovery when unset. */
    enableSkills?: boolean;
    /** Whether to stream model responses. */
    enableStreaming?: boolean;
    /** How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). */
    envValueMode?: OptionsUpdateEnvValueMode;
    /** Override directory for the session-events log. When unset, the runtime's default events log directory is used. */
    eventsLogDirectory?: string;
    /** Whether subagent callback events should be forwarded into the session event log sink. */
    eventsLogIncludesSubagents?: boolean;
    /** Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. */
    excludedBuiltinAgents?: string[];
    /** Denylist of tool names for this session. */
    excludedTools?: string[];
    /** Map of feature-flag IDs to their boolean enabled state. */
    featureFlags?: Record<string, boolean>;
    /** Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. */
    includedBuiltinAgents?: string[] | null;
    /** Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. */
    installedPlugins?: SessionInstalledPlugin[];
    /** Stable integration identifier used for analytics and rate-limit attribution. */
    integrationId?: string;
    /** Whether experimental capabilities are enabled. */
    isExperimentalMode?: boolean;
    /** Whether interactive shell sessions are logged. */
    logInteractiveShells?: boolean;
    /** Identifier sent to LSP-style integrations. */
    lspClientName?: string;
    /** Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the per-session schedule registry; this flag only controls tool exposure (typically gated to staff users). */
    manageScheduleEnabled?: boolean;
    /** Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. */
    maxInlineBinaryBytes?: number;
    /** The model ID to use for assistant turns. */
    model?: string;
    /** Per-property model capability overrides for the selected model. */
    modelCapabilitiesOverrides?: ModelCapabilitiesOverride_2;
    /** Organization-level custom instructions to inject into the system prompt. */
    organizationCustomInstructions?: string;
    /** Custom model-provider configuration (BYOK). */
    provider?: ProviderConfig_2;
    /** Reasoning effort for the selected model. CAPI values are model-defined and validated against the selected model; BYOK providers may define additional values. When omitted, no effort override is applied. */
    reasoningEffort?: string;
    /** Reasoning summary mode for supported model clients. */
    reasoningSummary?: OptionsUpdateReasoningSummary;
    /** Whether the session is running in an interactive UI. */
    runningInInteractiveMode?: boolean;
    /** Resolved sandbox configuration. */
    sandboxConfig?: SandboxConfig;
    /** Replaces the session's capability set with the given list. Use to enable or disable capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the field to leave the existing capability set unchanged. */
    sessionCapabilities?: SessionCapability[];
    /** Optional session limits. Pass null to clear the session limits. */
    sessionLimits?: SessionLimitsConfig_2 | null;
    /** Per-session settings for built-in shell tools. */
    shell?: ShellOptions;
    /**
     * Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`).
     * @deprecated
     */
    shellInitProfile?: string;
    /** PowerShell process flags applied to built-in and user-requested shell commands. */
    shellProcessFlags?: string[];
    /** Additional directories to search for skills. */
    skillDirectories?: string[];
    /** Whether to skip loading custom instruction sources. */
    skipCustomInstructions?: boolean;
    /** Whether to skip embedding retrieval pipeline initialization and execution. */
    skipEmbeddingRetrieval?: boolean;
    /** When true, the selected custom agent's prompt is not injected into the user message (skill context is still injected). Used by automation triggers where the agent prompt is already in the problem statement. */
    suppressCustomAgentPrompt?: boolean;
    /** Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. */
    toolFilterPrecedence?: OptionsUpdateToolFilterPrecedence;
    /** Optional path for trajectory output. */
    trajectoryFile?: string;
    /** Output verbosity level for supported models. */
    verbosity?: Verbosity_3;
    /** Absolute working-directory path for shell tools. */
    workingDirectory?: string;
}

/** Indicates whether the session options patch was applied successfully. */
declare interface SessionUpdateOptionsResult {
    /** Number of hooks loaded from installed plugins, returned when installedPlugins is updated */
    pluginHookCount?: number;
    /** Whether the operation succeeded */
    success: boolean;
}

declare type SessionUsageApi = SessionApi["usage"];

declare type SessionVisibilityApi = SessionApi["visibility"];

/** Sharing status for a synced session. "repo" makes the session visible to anyone with read access to the repository; "unshared" restricts it to the creator and collaborators. */
declare type SessionVisibilityStatus = "repo" | "unshared";

/**
 * SDK-supplied, per-session control over provider-native ("hosted") web search —
 * the `web_search` tool OpenAI executes server-side on the Responses wire.
 *
 * Unlike {@link SessionToolSearchOptions}, whose shape this mirrors, this option
 * is INHERITED BY SUBAGENTS: a child session copies the parent's resolved value
 * whenever the child's own options are silent. Without that, a consumer could
 * disable hosted web search on a parent and still have every subagent attach it,
 * which would make the product's only explicit opt-out a false guarantee.
 */
declare interface SessionWebSearchOptions {
    /**
     * Explicit off switch for provider-native web search.
     *
     * `false` suppresses it regardless of the experiment assignment. `true` is
     * NOT an override that forces the feature on: the model must still advertise
     * the capability, run on the Responses wire, be assigned the experiment, and
     * satisfy the user-control gate — so it behaves exactly as leaving the option
     * unset does. Leave unset to defer entirely to that decision.
     */
    enabled?: boolean;
}

/** Updated working directory and git context. Emitted as the new payload of `session.context_changed`. */
declare interface SessionWorkingDirectoryContext {
    /** Merge-base commit SHA (fork point from the remote default branch) */
    baseCommit?: string;
    /** Current git branch name */
    branch?: string;
    /** Current working directory path */
    cwd: string;
    /** Root directory of the git repository, resolved via git rev-parse */
    gitRoot?: string;
    /** Head commit of the current git branch */
    headCommit?: string;
    /** Hosting platform type of the repository */
    hostType?: SessionWorkingDirectoryContextHostType;
    /** Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps) */
    repository?: string;
    /** Raw host string from the git remote URL (e.g. "github.com", "dev.azure.com") */
    repositoryHost?: string;
}

/** Hosting platform type of the repository */
declare type SessionWorkingDirectoryContextHostType = "github" | "ado";

declare type SessionWorkspaceApi = SessionApi["workspaces"];

declare function settingsFilePath(subDir?: string, settings?: SettingsStorageContext): string;

/**
 * Minimal context needed to locate Copilot user/state configuration files.
 *
 * This is intentionally narrower than runtime settings so storage callers do
 * not depend on a runtime-owned settings object just to pass a config-dir
 * override through to persistence helpers.
 */
declare interface SettingsStorageContext {
    configDir?: string;
}

declare type ShellApi = SessionApi["shell"];

export declare type ShellAttachmentMode = TaskShellInfoAttachmentMode;

/** User-requested shell execution cancellation handle. */
declare interface ShellCancelUserRequestedRequest {
    /** Request ID previously passed to executeUserRequested */
    requestId: string;
}

declare type ShellCommandCompletionCallback = (shellId: string, output: ShellOutput, description?: string, startedAt?: number) => void;

/**
 * Thin host value around native immutable shell configuration.
 */
declare class ShellConfig {
    private readonly nativeConfig;
    readonly safetyEnabled: boolean;
    private static bashConfig;
    private static powerShellConfig;
    private constructor();
    readonly shellType: ShellType;
    readonly displayName: string;
    readonly shellToolName: string;
    readonly readShellToolName: string;
    readonly stopShellToolName: string;
    readonly listShellsToolName: string;
    readonly descriptionLines: string[];
    readonly sandbox: SandboxConfig_2;
    readonly initProfile: ShellInitProfile_2;
    readonly processFlags: readonly string[];
    static get bash(): ShellConfig;
    static get powerShell(): ShellConfig;
    static fromNative(nativeConfig: NativeShellConfig, safetyEnabled: boolean): ShellConfig;
    withSafetyEnabled(safetyEnabled: boolean): ShellConfig;
    withSandbox(sandbox: SandboxConfig_2): ShellConfig;
    withInitProfile(initProfile: ShellInitProfile_2): ShellConfig;
    withProcessFlags(processFlags: readonly string[]): ShellConfig;
    withToolNames(shellToolName: string, readShellToolName: string): ShellConfig;
}

/**
 * JS keeps the public context value; Rust owns its generation and creation
 * lease so concurrent tool construction cannot create competing contexts.
 */
declare class ShellContextHolder<T = InteractiveShellToolContext> {
    readonly native: ShellContextHandle;
    private currentValue?;
    private createdCurrentValue;
    get value(): T | undefined;
    /** Adopts a context created elsewhere — a subagent inheriting its parent's. */
    set value(value: T | undefined);
    /**
     * Whether this holder created the context it holds, making it the only holder
     * allowed to tear that context down.
     *
     * Subagents share the parent's `InteractiveShellToolContext`, whose `ToolConfig`
     * still points at the *parent's* holder, so shutting an adopted context down kills
     * the parent's shells and marks the parent's holder terminated — permanently
     * failing every later turn of the still-live parent with {@link HolderTerminatedError}.
     */
    get ownsCurrentValue(): boolean;
    get generation(): number;
    get invalidated(): boolean;
    set invalidated(value: boolean);
    get terminated(): boolean;
    set terminated(value: boolean);
    isCurrent(generation: number): boolean;
    getOrCreate(create: () => Promise<T>, dispose?: (value: T) => void): Promise<T>;
}

/** Shell command to run, with optional working directory and timeout in milliseconds. */
declare interface ShellExecRequest {
    /** Shell command to execute */
    command: string;
    /** Working directory (defaults to session working directory) */
    cwd?: string;
    /** Timeout in milliseconds (default: 30000) */
    timeout?: number;
}

/** Identifier of the spawned process, used to correlate streamed output and exit notifications. */
declare interface ShellExecResult {
    /** Unique identifier for tracking streamed output */
    processId: string;
}

/** User-requested shell command and cancellation handle. */
declare interface ShellExecuteUserRequestedRequest {
    /** Shell command to execute */
    command: string;
    /** Caller-provided cancellation handle for this execution */
    requestId: string;
}

export declare type ShellExecutionMode = TaskExecutionMode;

/** Sent when a shell command exits (after all output has been streamed). */
declare interface ShellExitNotification {
    /** Process identifier returned by `shell.exec`. */
    processId: string;
    /** Process exit code (0 = success). */
    exitCode: number;
}

/** Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. */
declare type ShellInitProfile = "none" | "non-interactive";

declare const ShellInitProfile_2: {
    readonly None: "none";
    readonly NonInteractive: "non-interactive";
};

declare type ShellInitProfile_2 = (typeof ShellInitProfile_2)[keyof typeof ShellInitProfile_2];

/** A host-provided script sourced before each built-in shell command when its shell target matches the active shell. */
declare interface ShellInitScript {
    /** Path to the script to source. */
    path: string;
    /** Built-in shell that may source this script. */
    shell: ShellInitScriptShell;
}

/** A host-provided script path and the built-in shell that may source it. */
declare type ShellInitScript_2 = {
    shell: ShellType;
    path: string;
};

/** Supported built-in shells for initialization scripts. */
declare type ShellInitScriptShell = "bash" | "powershell";

/** Identifier of a process previously returned by "shell.exec" and the signal to send. */
declare interface ShellKillRequest {
    /** Process identifier returned by shell.exec */
    processId: string;
    /** Signal to send (default: SIGTERM) */
    signal?: ShellKillSignal;
}

/** Indicates whether the signal was delivered; false if the process was unknown or already exited. */
declare interface ShellKillResult {
    /** Whether the signal was sent successfully */
    killed: boolean;
}

/** Signal to send (default: SIGTERM) */
declare type ShellKillSignal = "SIGTERM" | "SIGKILL" | "SIGINT";

declare interface ShellNotificationSender {
    sendOutput(notification: ShellOutputNotification): void;
    sendExit(notification: ShellExitNotification): void;
}

/** Per-session settings for built-in shell tools. */
declare interface ShellOptions {
    /** Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. */
    initProfile?: ShellInitProfile;
    /**
     * Ordered host-provided script paths sourced before each built-in shell command when the
     * entry's shell target matches the active shell. Use these for rc files, environment setup scripts,
     * or other custom scripts. A script that returns a nonzero status is reported, and later scripts
     * and the user command continue while the shell remains running. Because scripts are sourced into
     * the command shell, `exit`, `exec`, failures under `set -e`, or other shell-terminating behavior
     * can prevent continuation. Script standard output is preserved; Bash script stderr is discarded,
     * PowerShell exception messages are replaced, and runtime-generated failure notices omit
     * configured script paths. When sandboxing is enabled, each script must already be readable under
     * the active sandbox filesystem policy. Pass an empty array to clear the list.
     */
    initScripts?: ShellInitScript[];
    /**
     * Flags passed to the active built-in shell process on startup, replacing its default flags.
     * When omitted, the built-in Bash shell uses `--norc --noprofile`,
     * and the built-in PowerShell shell uses `-NoProfile -NoLogo`.
     */
    processFlags?: string[];
}

/** Native shell-driver output exposed to session notifications. */
declare type ShellOutput = {
    output: string;
    exitCode?: number;
    largeOutputFilePath?: string;
    largeOutputTotalBytes?: number;
};

/** Streamed output from a shell command started via `shell.exec`. */
declare interface ShellOutputNotification {
    /** Process identifier returned by `shell.exec`. */
    processId: string;
    /** Which output stream produced this chunk. */
    stream: "stdout" | "stderr";
    /** The output data (UTF-8 string, up to 64KB per notification). */
    data: string;
}

/**
 * A permission request for executing shell commands.
 */
declare type ShellPermissionRequest = {
    readonly kind: "shell";
    /** The full command that the user is being asked to approve, e.g. `echo foo && find -exec ... && git push` */
    readonly fullCommandText: string;
    /** A concise summary of the user's intention, e.g. "Echo foo and find a file and then run git push" */
    readonly intention: string;
    /**
     * The commands that are being invoked in the shell invocation.
     *
     * As a special case, which might be better represented in the type system, if there were no parsed commands
     * e.g. `export VAR=value`, then this will have a single entry with identifier equal to the fullCommandText.
     */
    readonly commands: ReadonlyArray<Command>;
    /** Parsed command segments, including arguments, used for managed policy matching. */
    readonly commandSegments?: ReadonlyArray<CommandSegment>;
    /**
     * Possible file paths that the command might access.
     *
     * This is entirely heuristic, so it's pretty untrustworthy.
     */
    readonly possiblePaths: ReadonlyArray<PossiblePath>;
    /**
     * Possible URLs that the command might access.
     *
     * This is entirely heuristic, so it's pretty untrustworthy.
     */
    readonly possibleUrls: ReadonlyArray<PossibleUrl>;
    /**
     * Indicates whether any command in the script has redirection to write to a file.
     */
    readonly hasWriteFileRedirection: boolean;
    /**
     * If there are complicated constructs, then persistent approval is not supported.
     * e.g. `cat $(echo "foo")` should not be persistently approvable because it's hard
     * for the user to understand the implications.
     */
    readonly canOfferSessionApproval: boolean;
    /**
     * Optional warning message to display (e.g., when the shell parser is unavailable).
     */
    readonly warning?: string;
    /**
     * True when the model has requested to run this command outside the
     * sandbox (it set `requestSandboxBypass: true` and the host opted in via
     * `sandbox.allowBypass`). This is a request, not a grant: the command runs
     * unsandboxed only if the user approves this permission request. Hosts
     * should highlight the elevated risk in the approval UI.
     */
    readonly requestSandboxBypass?: boolean;
    /**
     * Model-provided justification for the sandbox-bypass request
     * ({@link requestSandboxBypass}). Only meaningful when
     * `requestSandboxBypass` is true.
     */
    readonly requestSandboxBypassReason?: string;
    /** Managed policy requires an explicit human response for this shell command. */
    readonly managedApprovalRequired?: boolean;
};

export declare type ShellTask = {
    type: "shell";
    id: string;
    description: string;
    status: BackgroundTaskStatus;
    startedAt: number;
    completedAt?: number;
    command: string;
    attachmentMode: ShellAttachmentMode;
    executionMode: ShellExecutionMode;
    canPromoteToBackground?: boolean;
    logPath?: string;
    pid?: number;
};

/**
 * Fields specific to shell tasks.
 */
declare interface ShellTaskFields {
    type: "shell";
    /** Identifier of the underlying shell session */
    shellId: string;
    /** Process exit code when finished */
    exitCode?: number;
    /** Whether the shell is a fully-detached background process */
    detached: boolean;
    /** Path to the log file for detached processes */
    logPath?: string;
    /** Working directory used when the shell command was started. */
    cwd?: string;
    /** The command being executed */
    command?: string;
    /** Process ID (read from .pid file for detached processes) */
    pid?: number;
    /** Whether the detached command was launched inside the sandbox */
    sandboxApplied?: boolean;
    /** Whether completion should emit a system notification */
    notifyOnComplete?: boolean;
    /**
     * Set while a user- or agent-initiated kill of this detached shell is in
     * progress, and left set once the kill takes effect. Suppresses the
     * detached-shell completion notification independently of
     * {@link notifyOnComplete}, so an overlapping read that temporarily clears
     * and restores `notifyOnComplete` cannot re-enable the notification the kill
     * is suppressing (and vice versa). Cleared again only when the last in-flight
     * kill attempt finishes with the shell still running, so a genuinely
     * surviving shell still notifies on its natural exit.
     */
    killRequested?: boolean;
    /**
     * Number of in-flight {@link killDetachedShell} attempts for this shell.
     * {@link killRequested} is cleared only when this returns to zero with the
     * shell still running, so overlapping kill attempts - e.g. a `/tasks` cancel
     * (which bypasses the per-shell tool queue) racing the agent's stop tool -
     * cannot clear each other's suppression while one is still signalling.
     */
    killAttemptsInFlight?: number;
}

export declare type ShellTaskProgress = TaskShellProgress;

declare type ShellType = NativeShellConfig["shellType"];

/** Aggregate code change metrics for the session */
export declare interface ShutdownCodeChanges {
    /** List of file paths that were modified during the session */
    filesModified: string[];
    /** Total number of lines added during the session */
    linesAdded: number;
    /** Total number of lines removed during the session */
    linesRemoved: number;
}

/** Session termination metrics including usage statistics, code changes, and shutdown reason */
declare interface ShutdownData {
    /** Aggregate code change metrics for the session */
    codeChanges: ShutdownCodeChanges;
    /** Non-system message token count at shutdown */
    conversationTokens?: number;
    /** Model that was selected at the time of shutdown */
    currentModel?: string;
    /** Total tokens in context window at shutdown */
    currentTokens?: number;
    /** Error description when shutdownType is "error" */
    errorReason?: string;
    /** On-disk byte size of the session's persisted events.jsonl file at shutdown time; omitted when the file does not exist or cannot be stat'd */
    eventsFileSizeBytes?: number;
    /** Per-model usage breakdown, keyed by model identifier */
    modelMetrics: Record<string, ShutdownModelMetric>;
    /** Unix timestamp (milliseconds) when the session started */
    sessionStartTime: number;
    /** Whether the session ended normally ("routine") or due to a crash/fatal error ("error") */
    shutdownType: ShutdownType;
    /** System message token count at shutdown */
    systemTokens?: number;
    /** Session-wide per-token-type accumulated token counts */
    tokenDetails?: Record<string, ShutdownTokenDetail>;
    /** Tool definitions token count at shutdown */
    toolDefinitionsTokens?: number;
    /** Cumulative time spent in API calls during the session, in milliseconds */
    totalApiDurationMs: number;
    /** Session-wide accumulated nano-AI units cost */
    totalNanoAiu?: number;
    /** Total number of premium API requests used during the session */
    totalPremiumRequests?: number;
}
export { ShutdownData as SessionShutdownData }
export { ShutdownData }

/** Session event "session.shutdown". Session termination metrics including usage statistics, code changes, and shutdown reason */
declare interface ShutdownEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session termination metrics including usage statistics, code changes, and shutdown reason */
    data: ShutdownData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.shutdown". */
    type: "session.shutdown";
}
export { ShutdownEvent as SessionShutdownEvent }
export { ShutdownEvent }

/** Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details. */
export declare interface ShutdownModelMetric {
    /** Request count and cost metrics */
    requests: ShutdownModelMetricRequests;
    /** Token count details per type */
    tokenDetails?: Record<string, ShutdownModelMetricTokenDetail>;
    /** Accumulated nano-AI units cost for this model */
    totalNanoAiu?: number;
    /** Token usage breakdown */
    usage: ShutdownModelMetricUsage;
}

/** Request count and cost metrics */
export declare interface ShutdownModelMetricRequests {
    /** Cumulative cost multiplier for requests to this model */
    cost?: number;
    /** Total number of API requests made to this model */
    count?: number;
}

/** A token-type entry in a shutdown model metric, storing the accumulated token count. */
export declare interface ShutdownModelMetricTokenDetail {
    /** Accumulated token count for this token type */
    tokenCount: number;
}

/** Token usage breakdown */
export declare interface ShutdownModelMetricUsage {
    /** Total tokens read from prompt cache across all requests */
    cacheReadTokens: number;
    /** Total tokens written to prompt cache across all requests */
    cacheWriteTokens: number;
    /** Total input tokens consumed across all requests to this model */
    inputTokens: number;
    /** Total output tokens produced across all requests to this model */
    outputTokens: number;
    /** Total reasoning tokens produced across all requests to this model */
    reasoningTokens?: number;
}

declare type ShutdownParams = ShutdownRequest;

/** Parameters for shutting down the session */
declare interface ShutdownRequest {
    /** Optional human-readable reason. Typically the message of the error that triggered shutdown when type is 'error'. */
    reason?: string;
    /** Why the session is being shut down. Defaults to "routine" when omitted. */
    type?: ShutdownType_2;
}

/** A session-wide shutdown token-type entry storing the accumulated token count. */
export declare interface ShutdownTokenDetail {
    /** Accumulated token count for this token type */
    tokenCount: number;
}

/** Whether the session ended normally ("routine") or due to a crash/fatal error ("error") */
export declare type ShutdownType = "routine" | "error";

/** Why the session is being shut down. Defaults to "routine" when omitted. */
declare type ShutdownType_2 = "routine" | "error";

declare class SidekickAgentManager {
    /**
     * Session id the native inbox store is keyed by. Sidekick agents only run
     * on top-level sessions, whose native session id is the session id.
     */
    private get inboxSessionId();
    /**
     * Thin forwarding surface over the native, session-scoped inbox store
     * (`src/runtime/src/session/services/inbox_service.rs`). Persistence,
     * schema, pruning, and ID generation all live in Rust; these methods are
     * pure passthroughs so callers (and this file's tests) can keep the same
     * shape the previous hand-written TS `Inbox` class exposed.
     */
    readonly inbox: {
        send: (input: SendInboxEntryInput) => Promise<InboxEntry>;
        read: (options?: ReadInboxEntryOptions) => Promise<InboxEntry | undefined>;
        getById: (entryId: string) => Promise<InboxEntry | undefined>;
        markNotified: (entryId: string) => Promise<InboxEntry | undefined>;
        getUnreadUnnotifiedEntries: () => Promise<InboxEntry[]>;
        getEntriesBySenderAndInteraction: (senderId: string, interactionId: string) => Promise<InboxEntry[]>;
        markRead: (entryId: string) => Promise<InboxEntry | undefined>;
    };
    private readonly taskRegistry;
    private readonly latestAgentIds;
    /**
     * Per-session fire counts keyed by `${agentName}:${event}`. Only triggers
     * with a resolved limit are tracked; unlimited triggers are never recorded.
     */
    private readonly triggerFireCounts;
    private readonly unsubscribers;
    private initPromise?;
    private sessionContext?;
    private readonly _registeredAgentNames;
    /**
     * Per-agent inline-forwarding threshold (character count), keyed by agent name.
     * Populated at init from each definition's `sidekick.inlineForwardMaxChars`. An
     * entry is present only for agents that opted in; absence disables inline
     * forwarding for that sender. Consulted by {@link sendInboxNotification}.
     */
    private readonly inlineForwardMaxChars;
    /**
     * Live runtime state for persistent sidekick agents, keyed by agent name.
     * A persistent agent runs a single long-lived executor loop; this state lets
     * the manager find the running task for message delivery and lets the agent's
     * send_inbox publisher read the current turn's interaction id + send budget.
     */
    private readonly persistentRuntimes;
    /**
     * Per-agent-name launch serialization. Rapid triggers must not race to both
     * launch a fresh persistent agent or reorder runtime/latestAgentIds state, so
     * launch/reuse decisions for a given agent run one-at-a-time. The chain is
     * built so a rejected run can't poison future launches.
     */
    private readonly launchChains;
    /**
     * The main agent's most recent user request. Captured from `user.message`
     * events and passed to context-refresh trigger prompts (e.g.
     * `session.memory_changed`) so the sidekick has a current task to judge
     * relevance against — those triggers carry no task context of their own.
     */
    private lastUserRequest;
    /** Current main-agent user-turn generation and the interaction counted for it. */
    private readonly userTurnState;
    /** Per-agent generation for committed restart-mode launches. */
    private readonly restartLaunchGenerations;
    /** Queued main-agent events per sidekick agent name, in occurrence order. */
    private readonly queuedEvents;
    /** Trigger events that are queued but have not completed launch processing. */
    private readonly pendingTriggerEventIds;
    private nextQueuedEventId;
    /**
     * Returns whether any sidekick agents registered during initialization.
     * Awaits initialization so the answer is final.
     */
    hasSidekickAgents(): Promise<boolean>;
    /** Lists all entries in the sidekick task registry. */
    listTasks(): TaskEntry[];
    /**
     * Whether any sidekick executor closure belongs to a *cancelled* agent whose
     * body has not yet returned. Mirrors
     * {@link TaskRegistry.hasDrainingCancelledExecutionsInTree} so rewind
     * admission refuses only while a cancelled sidekick executor could still
     * reach a wrapped editing tool — an idle-parked persistent sidekick is a safe
     * steady state and does not block rewind.
     */
    hasDrainingCancelledExecutions(): boolean;
    /**
     * Collect the in-flight executor-body promises owned by the sidekick task
     * registry. Mirrors {@link TaskRegistry.collectPendingExecutionsInTree} so
     * session disposal can await sidekick executors (which live in this separate
     * registry, not the main task-registry tree) before the shared rewind
     * manager is torn down, capturing any final in-flight workspace write for
     * rewind. The stored promises never reject, so callers can await them
     * directly. Disposal bounds the wait with its own quiescence deadline.
     */
    collectPendingExecutions(): Promise<void>[];
    /** Wire a callback that fires whenever sidekick tasks change (for UI updates). */
    setOnTaskChange(callback: () => void): void;
    /**
     * Initialize sidekick agents: load definitions and register event hooks.
     * Store the promise so it can be awaited before the first model call.
     */
    initialize(context: SidekickAgentSessionContext): void;
    /** Await initialization. Call before first model loop to avoid missing the first turn. */
    ensureInitialized(): Promise<void>;
    /** Forcefully cancel all running sidekick agents. */
    cancelAll(): void;
    private cancelRunningTasks;
    /** True once {@link dispose} has run; guards against double teardown. */
    private disposed;
    /**
     * Idempotently tear down the manager: detach event listeners, cancel any
     * running agents, drop the task-change callback, and dispose the owned task
     * registry. Without disposing the registry its native `TaskRegistryStore`
     * entry and its `registriesByNativeHandle` static-map entry (whose value
     * closes over the owning Session) leak for the process lifetime — one per
     * session in a long-lived CLI. Safe to call more than once.
     */
    dispose(): void;
    /** Drains every event subscription, including partially initialized state. */
    private drainSubscribers;
    private shouldHandleEvent;
    private queueEvent;
    private trimRetainedContextEvents;
    private completeQueuedTrigger;
    private buildPromptForQueuedEvents;
    private clearEventsThrough;
    /** Removes a handled non-context trigger from an agent's queue. */
    private pruneHandledNonContextEvent;
    /**
     * Sends a notification for an inbox entry when its originating run is still
     * current. Stale persisted entries are marked read so no later path surfaces
     * them.
     */
    private sendInboxNotification;
    /** Flush any unread/unnotified inbox entries as system notifications. */
    flushPendingNotifications(): Promise<void>;
    private doInitialize;
    /**
     * Serializes launch/reuse decisions for a given agent name. Runs `task` after
     * any in-flight launch for the same name completes. The chain is built with a
     * swallow-on-error link so one failed launch can't permanently wedge future
     * launches for that agent.
     */
    private enqueueLaunch;
    /**
     * Single owner of triggerFireCounts — check and increment live together,
     * both inside the per-name serialized chain, so two enqueued events can't
     * both proceed. Only increments when launchAgent commits (launched or
     * delivered) AND the trigger has a fire limit; unlimited triggers are never
     * recorded so they keep firing on every occurrence.
     */
    private launchAndRecord;
    private extractInteractionId;
    private launchAgent;
}

/**
 * Session context interface — only the fields the sidekick agent manager needs.
 * Keeps the manager testable without requiring a full Session instance.
 */
declare type SidekickAgentSessionContext = {
    sessionId: string;
    workingDir: string;
    isDetached: boolean;
    featureFlagService: IFeatureFlagService;
    logger: RunnerLoggerContract_2;
    getDynamicContextConfig?(): LaunchCheckDynamicContextConfig | null;
    getExecutorSettings(): SidekickExecutorSettings | undefined | Promise<SidekickExecutorSettings | undefined>;
    /**
     * The session's explicitly configured `repositoryName`, if any. When set, it
     * is the authoritative memory-scope identity and suppresses the
     * `session.context_changed` repository overlay (see
     * {@link overlayContextChangedRepository}).
     */
    getExplicitRepositoryName?(): string | undefined;
    getResponseLimitsStatus?(): ResponseLimitsStatusResult | undefined;
    getToolConfig(): ToolConfig | undefined;
    isProcessing(): boolean;
    blocksAgentStart(): boolean;
    sendSystemNotification(message: string, kind: SystemNotification, options?: {
        passive?: PassivePolicy;
    }): void;
    sendTelemetry(event: TelemetryEvent_2): void;
    on(eventType: string, handler: (event: SessionEvent) => void): () => void;
    /** Creates a child session for session-based sidekick execution. */
    createSubagentSession?: (agentId: string, options: SubagentSessionOptions) => LocalSession;
};

declare type SidekickExecutorSettings = RuntimeSettings_2;

/**
 * A single sidekick trigger. Accepts either a bare event-name string (unlimited
 * firing) or an object with per-event metadata. Bare strings are normalized to
 * `{ event }` by the Rust parser before reaching TypeScript.
 */
declare type SidekickTrigger = string | {
    /** Session event type that launches this agent (e.g. "user.message"). */
    event: string;
    /**
     * Maximum number of times this trigger may fire per session. Omit for
     * unlimited. Must be a positive integer when present.
     */
    limit?: number;
};

/** Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. */
declare interface Skill {
    /** Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field */
    argumentHint?: string;
    /** Canonical slash command name used to invoke the skill, without the leading '/' */
    commandName?: string;
    /** Description of what the skill does */
    description: string;
    /** Whether the skill is currently enabled */
    enabled: boolean;
    /** Unique identifier for the skill */
    name: string;
    /** Absolute path to the skill file */
    path?: string;
    /** Name of the plugin that provides the skill, when source is 'plugin' */
    pluginName?: string;
    /** Source location type (e.g., project, personal-copilot, plugin, builtin) */
    source: SkillSource_2;
    /** Whether the skill can be invoked by the user as a slash command */
    userInvocable: boolean;
}

/**
 * A fully loaded skill definition. Discriminated union of local and remote skills.
 * Use `skill.source === "remote"` to narrow to RemoteSkill.
 */
declare type Skill_2 = LocalSkill | RemoteSkill;

/**
 * Shared properties between local and remote skills.
 */
declare interface SkillBase {
    /** Unique identifier for the skill (from frontmatter). */
    name: string;
    /** Description of what the skill does (from frontmatter). */
    description: string;
    /** Optional list of tools that are auto-allowed when skill is active. */
    allowedTools?: string[];
    /** Whether this skill can be invoked by the user as a slash command. Defaults to true. */
    userInvocable: boolean;
    /** Whether the model is prevented from invoking this skill. Defaults to false. */
    disableModelInvocation: boolean;
    /** Optional freeform hint describing the skill's expected arguments (from the `argument-hint` frontmatter field). */
    argumentHint?: string;
    /** Name of the plugin this skill came from (only set when source is "plugin"). */
    pluginName?: string;
    /** Version of the plugin this skill came from (only set when source is "plugin"). */
    pluginVersion?: string;
    /** Tool-facing name when same-named plugin skills must be disambiguated. */
    invocationName?: string;
    /** Canonical slash command name, including plugin qualification when needed. */
    commandName?: string;
    /** Whether this is a command (from .claude/commands/) rather than a skill. */
    isCommand?: boolean;
}

/** Canonical directory where skills can be discovered or created, with scope, preference, and optional project path. */
declare interface SkillDiscoveryPath {
    /** Absolute path of the create/discovery target (may not exist on disk yet) */
    path: string;
    /** Whether this is the canonical directory to create a new skill in its tier. At most one entry per tier is preferred; the `personal-agents` and `custom` scopes are never preferred. */
    preferredForCreation: boolean;
    /** The input project path this directory was derived from (only for project scope) */
    projectPath?: string;
    /** Which tier this directory belongs to */
    scope: SkillDiscoveryScope;
}

/** Canonical locations where skills can be created so the runtime will recognize them. */
declare interface SkillDiscoveryPathList {
    /** Canonical skill create/discovery directories, in priority order */
    paths: SkillDiscoveryPath[];
}

/** Which tier this directory belongs to */
declare type SkillDiscoveryScope = "project" | "personal-copilot" | "personal-agents" | "custom";

declare type SkillInvocation = Omit<SkillInvocationRecord, "allowedTools" | "trigger"> & {
    model?: string;
    allowedTools?: string[];
    trigger?: SkillInvocationTrigger;
};

declare type SkillInvocationTrigger = "user-invoked" | "agent-invoked" | "context-load";

/** Skill invocation details including content, allowed tools, and plugin metadata */
export declare interface SkillInvokedData {
    /** Tool names that should be auto-approved when this skill is active */
    allowedTools?: string[];
    /** Full content of the skill file, injected into the conversation for the model */
    content: string;
    /** Description of the skill from its SKILL.md frontmatter */
    description?: string;
    /** Model identifier active when the skill was invoked, when known */
    model?: string;
    /** Name of the invoked skill */
    name: string;
    /** File path to the SKILL.md definition */
    path: string;
    /** Name of the plugin this skill originated from, when applicable */
    pluginName?: string;
    /** Version of the plugin this skill originated from, when applicable */
    pluginVersion?: string;
    /** Source identifier for where the skill was discovered. Known values include: project (workspace skill), inherited (parent-directory skill), personal-copilot (~/.copilot/skills), personal-agents (~/.agents/skills), custom (configured directory), plugin (installed plugin), builtin (bundled runtime skill), and remote (org/enterprise skill) */
    source?: string;
    /** What triggered the skill invocation: `user-invoked` (explicit user action, such as via a slash command or UI affordance), `agent-invoked` (agent requested the skill), or `context-load` (loaded as part of another context, such as preloading skills configured on a custom agent or subagent) */
    trigger?: SkillInvokedTrigger;
}

/** Session event "skill.invoked". Skill invocation details including content, allowed tools, and plugin metadata */
export declare interface SkillInvokedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Skill invocation details including content, allowed tools, and plugin metadata */
    data: SkillInvokedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "skill.invoked". */
    type: "skill.invoked";
}

/** What triggered the skill invocation: `user-invoked` (explicit user action, such as via a slash command or UI affordance), `agent-invoked` (agent requested the skill), or `context-load` (loaded as part of another context, such as preloading skills configured on a custom agent or subagent) */
export declare type SkillInvokedTrigger = "user-invoked" | "agent-invoked" | "context-load";

/** Skills available to the session, with their enabled state. */
declare interface SkillList {
    /** Available skills */
    skills: Skill[];
}

/** Skill names to mark as disabled in global configuration, replacing any previous list. */
declare interface SkillsConfigSetDisabledSkillsRequest {
    /** List of skill names to disable */
    disabledSkills: string[];
}

/** Name of the skill to disable for the session. */
declare interface SkillsDisableRequest {
    /** Name of the skill to disable */
    name: string;
}

/** Optional project paths and additional skill directories to include in discovery. */
declare interface SkillsDiscoverRequest {
    /** When true, omit skills from the host's global sources (personal, custom, plugin, and built-in), returning only project-scoped skills. For multitenant deployments. */
    excludeHostSkills?: boolean;
    /** Optional list of project directory paths to scan for project-scoped skills */
    projectPaths?: string[];
    /** Optional list of additional skill directory paths to include */
    skillDirectories?: string[];
}

/** Name of the skill to enable for the session. */
declare interface SkillsEnableRequest {
    /** Name of the skill to enable */
    name: string;
}

/** Optional project paths to enumerate. */
declare interface SkillsGetDiscoveryPathsRequest {
    /** When true, omit the host's personal and custom skill directories, leaving only project directories. For multitenant deployments. */
    excludeHostSkills?: boolean;
    /** Optional list of project directory paths. When omitted or empty, only personal and custom directories are returned. */
    projectPaths?: string[];
}

/** Skills invoked during this session, ordered by invocation time (most recent last). */
declare interface SkillsGetInvokedResult {
    /** Skills invoked during this session, ordered by invocation time (most recent last) */
    skills: SkillsInvokedSkill[];
}

/** Skill invocation record with name, path, content, allowed tools, and turn number. */
declare interface SkillsInvokedSkill {
    /** Tools that should be auto-approved when this skill is active, captured at invocation time */
    allowedTools?: string[];
    /** Full content of the skill file */
    content: string;
    /** Turn number when the skill was invoked */
    invokedAtTurn: number;
    /** Unique identifier for the skill */
    name: string;
    /** Path to the SKILL.md file */
    path: string;
}

/** Diagnostics from reloading skill definitions, with warnings and errors as separate lists. */
declare interface SkillsLoadDiagnostics {
    /** Errors emitted while loading skills (e.g. skills that failed to load entirely) */
    errors: string[];
    /** Warnings emitted while loading skills (e.g. skills that loaded but had issues) */
    warnings: string[];
}

/** Payload of `session.skills_loaded` listing resolved skill metadata. */
export declare interface SkillsLoadedData {
    /** Array of resolved skill metadata */
    skills: SkillsLoadedSkill[];
}

/** Session event "session.skills_loaded". Payload of `session.skills_loaded` listing resolved skill metadata. */
declare interface SkillsLoadedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.skills_loaded` listing resolved skill metadata. */
    data: SkillsLoadedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.skills_loaded". */
    type: "session.skills_loaded";
}
export { SkillsLoadedEvent as SessionSkillsResolvedEvent }
export { SkillsLoadedEvent }

/** A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. */
export declare interface SkillsLoadedSkill {
    /** Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field */
    argumentHint?: string;
    /** Canonical slash command name used to invoke the skill, without the leading '/' */
    commandName?: string;
    /** Description of what the skill does */
    description: string;
    /** Whether the skill is currently enabled */
    enabled: boolean;
    /** Unique identifier for the skill */
    name: string;
    /** Absolute path to the skill file, if available */
    path?: string;
    /** Source location type (e.g., project, personal-copilot, plugin, builtin) */
    source: SkillSource;
    /** Whether the skill can be invoked by the user as a slash command */
    userInvocable: boolean;
}

/** Source location type (e.g., project, personal-copilot, plugin, builtin) */
export declare type SkillSource = "project" | "inherited" | "personal-copilot" | "personal-agents" | "plugin" | "custom" | "builtin";

/** Source location type (e.g., project, personal-copilot, plugin, builtin) */
declare type SkillSource_2 = "project" | "inherited" | "personal-copilot" | "personal-agents" | "plugin" | "custom" | "builtin";

/** Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. */
declare interface SlashCommandAgentPromptResult {
    /** Prompt text to display to the user */
    displayPrompt: string;
    /** Agent prompt result discriminator */
    kind: "agent-prompt";
    /** Optional target session mode for the agent prompt */
    mode?: SessionMode_2;
    /** Optional user-facing notice to show before the prompt is submitted */
    notice?: string;
    /** Prompt to submit to the agent */
    prompt: string;
    /** True when the invocation mutated user runtime settings; consumers caching settings should refresh */
    runtimeSettingsChanged?: boolean;
}

/** Slash-command invocation result indicating completion, with optional message and settings-change flag. */
declare interface SlashCommandCompletedResult {
    /** Completed result discriminator */
    kind: "completed";
    /** Optional user-facing message describing the completed command */
    message?: string;
    /** True when the invocation mutated user runtime settings; consumers caching settings should refresh */
    runtimeSettingsChanged?: boolean;
}

/** Slash-command metadata with name, aliases, description, kind, input hint, execution allowance, and schedulability. */
declare interface SlashCommandInfo {
    /** Canonical aliases without leading slashes */
    aliases?: string[];
    /** Whether the command may run while an agent turn is active */
    allowDuringAgentExecution: boolean;
    /** Human-readable command description */
    description: string;
    /** Whether the command is experimental */
    experimental?: boolean;
    /** Optional unstructured input hint */
    input?: SlashCommandInput;
    /** Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command */
    kind: SlashCommandKind;
    /** Canonical command name without a leading slash */
    name: string;
    /** Whether the command may be the target of `/every` / `/after` schedules. Resolution happens at every tick, so only set this when the command is safe to re-invoke and produces an agent prompt. */
    schedulable?: boolean;
}

/** Optional unstructured input hint */
declare interface SlashCommandInput {
    /** Optional literal choices the input accepts, each with a human-facing description; clients may render these as selectable options */
    choices?: SlashCommandInputChoice[];
    /** Optional completion hint for the input (e.g. 'directory' for filesystem path completion) */
    completion?: SlashCommandInputCompletion;
    /** Hint to display when command input has not been provided */
    hint: string;
    /** When true, clients should pass the full text after the command name as a single argument rather than splitting on whitespace */
    preserveMultilineInput?: boolean;
    /** When true, the command requires non-empty input; clients should render the input hint as required */
    required?: boolean;
}

/** A literal choice the command input accepts, with a human-facing description */
declare interface SlashCommandInputChoice {
    /** Human-readable description shown alongside the choice */
    description: string;
    /** The literal choice value (e.g. 'on', 'off', 'show') */
    name: string;
}

/** Optional completion hint for the input (e.g. 'directory' for filesystem path completion) */
declare type SlashCommandInputCompletion = "directory";

/** Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). */
declare type SlashCommandInvocationResult = SlashCommandTextResult | SlashCommandAgentPromptResult | SlashCommandCompletedResult | SlashCommandSelectSubcommandResult;

/** Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command */
declare type SlashCommandKind = "builtin" | "skill" | "client";

/** Selectable slash-command subcommand option with name, description, and optional group label. */
declare interface SlashCommandSelectSubcommandOption {
    /** Human-readable description of the subcommand */
    description: string;
    /** Optional group label for organizing options */
    group?: string;
    /** Subcommand name to invoke */
    name: string;
}

/** Slash-command invocation result asking the client to present subcommand options for a parent command. */
declare interface SlashCommandSelectSubcommandResult {
    /** Parent command name that requires subcommand selection */
    command: string;
    /** Select subcommand result discriminator */
    kind: "select-subcommand";
    /** Available subcommand options for the client to present */
    options: SlashCommandSelectSubcommandOption[];
    /** True when the invocation mutated user runtime settings; consumers caching settings should refresh */
    runtimeSettingsChanged?: boolean;
    /** Human-readable title for the selection UI */
    title: string;
}

/** Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. */
declare interface SlashCommandTextResult {
    /** Text result discriminator */
    kind: "text";
    /** Whether text contains Markdown */
    markdown?: boolean;
    /** Whether ANSI sequences should be preserved */
    preserveAnsi?: boolean;
    /** True when the invocation mutated user runtime settings; consumers caching settings should refresh */
    runtimeSettingsChanged?: boolean;
    /** Text output for the client to render */
    text: string;
}

/** Session rewind details including target event and count of removed events */
export declare interface SnapshotRewindData {
    /** Number of events that were removed by the rewind */
    eventsRemoved: number;
    /** Event ID that was rewound to; this event and all after it were removed */
    upToEventId: string;
}

/** Session event "session.snapshot_rewind". Session rewind details including target event and count of removed events */
declare interface SnapshotRewindEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session rewind details including target event and count of removed events */
    data: SnapshotRewindData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.snapshot_rewind". */
    type: "session.snapshot_rewind";
}
export { SnapshotRewindEvent as SessionSnapshotRewindEvent }
export { SnapshotRewindEvent }

declare type SqliteBindValue = string | number | null;

/**
 * How the sqlite query should be executed:
 * - `"exec"` — DDL or multi-statement (CREATE/ALTER/DROP, batches): no result rows.
 * - `"query"` — SELECT / WITH / EXPLAIN: returns rows.
 * - `"run"` — INSERT / UPDATE / DELETE / PRAGMA: returns rowsAffected / lastInsertRowid.
 */
declare type SqliteQueryType = "exec" | "query" | "run";

/** Session initialization metadata including context and configuration */
export declare interface StartData {
    /** Whether the session was already in use by another client at start time */
    alreadyInUse?: boolean;
    /** Working directory and git context at session start */
    context?: WorkingDirectoryContext;
    /** Context tier selected at session creation time for models with tiered context pricing; null when no tier is selected (e.g., non-tiered model) */
    contextTier?: ContextTier | null;
    /** Version string of the Copilot application */
    copilotVersion: string;
    /** When set, identifies a parent session whose context this session continues — e.g., a detached headless rem-agent run launched on the parent's interactive shutdown. Telemetry from this session is reported under the parent's session_id. */
    detachedFromSpawningParentSessionId?: string;
    /** Per-session GitHub MCP override persisted for cold resume */
    githubMcpToolConfig?: GitHubMcpToolConfig;
    /** Identifier of the software producing the events (e.g., "copilot-agent") */
    producer: string;
    /** Reasoning effort level used for model calls, if applicable (e.g. "none", "low", "medium", "high", "xhigh", "max") */
    reasoningEffort?: string;
    /** Reasoning summary mode used for model calls, if applicable (e.g. "none", "concise", "detailed") */
    reasoningSummary?: ReasoningSummary;
    /** Whether this session supports remote steering via GitHub */
    remoteSteerable?: boolean;
    /** Model selected at session creation time, if any */
    selectedModel?: string;
    /** Unique identifier for the session */
    sessionId: string;
    /** Session limits configured at session creation time, if any */
    sessionLimits?: SessionLimitsConfig;
    /** ISO 8601 timestamp when the session was created */
    startTime: string;
    /** Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") */
    verbosity?: Verbosity;
    /** Schema version number for the session event format */
    version: number;
}

/** Session event "session.start". Session initialization metadata including context and configuration */
declare interface StartEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session initialization metadata including context and configuration */
    data: StartData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.start". */
    type: "session.start";
}
export { StartEvent as SessionStartEvent }
export { StartEvent }

/**
 * The result of starting MCP servers via {@link McpHost.startServers}.
 */
declare interface StartServersResult {
    /** Servers that were removed by a config filter (e.g. allowlist enforcement). */
    filteredServers: McpFilteredServer_2[];
    /** Non-default servers that passed the config filter. */
    allowedServers?: McpAllowedServer_2[];
}

declare type StaticContextBudgetEvent = {
    tokenLimit?: number;
    systemTokens?: number;
    toolDefinitionsTokens?: number;
};

/**
 * Static override operation for a single system prompt section.
 * Used for declarative mutations that don't require reading the current content.
 */
declare interface StaticSectionOverride {
    /**
     * The operation to perform on this section.
     * - "replace": Replace section content entirely
     * - "remove": Remove the section
     * - "append": Append to existing section content
     * - "prepend": Prepend to existing section content
     */
    action: "replace" | "remove" | "append" | "prepend";
    /**
     * Content for the override. Optional for all actions.
     * For append/prepend, the current section content is preserved when omitted.
     * For replace, omitting content is equivalent to replacing with an empty string.
     * Ignored for the remove action.
     */
    content?: string;
}

declare type StoreItem = {
    id?: string;
};

/** Aggregate row counts across the store's core tables. */
declare type StoreStats = {
    sessions: number;
    turns: number;
    checkpoints: number;
    files: number;
    refs: number;
};

declare type StreamingChunkContext = {
    /**
     * The streaming ID of the message.
     */
    streamingId: string;
    /**
     * True when this chunk represents the start of a streamed assistant message.
     */
    messageStart?: boolean;
    /**
     * Stable generation phase metadata for the streamed assistant message.
     */
    phase?: string;
    /**
     * Text content delta from this chunk.
     */
    content?: string;
    /**
     * Reasoning content delta from this chunk (chain-of-thought summaries).
     */
    reasoningContent?: string;
    /**
     * Set when the server begins a server_tool_use block for the advisor.
     * Used to show the advisor intent in the thinking animation spinner.
     */
    advisorStarted?: boolean;
    /**
     * Set when the server returns an advisor_tool_result block.
     * Used to clear the advisor intent.
     */
    advisorCompleted?: boolean;
    /**
     * Set when the streaming source observes the start of a new reasoning
     * item in the response, signaling that the next streamed deltas belong
     * to a new chunk of the same API call. Used by `StreamingChunkDisplay`
     * to rotate `messageId` / `reasoningId` so each chunk lands in its own
     * UI bubble and aligns with the per-chunk `assistant.message` events
     * the model client yields.
     */
    chunkBoundary?: boolean;
    /**
     * Tool-call input deltas carried by this chunk.
     */
    toolCallDeltas?: StreamingToolCallDelta[];
    /**
     * Live lifecycle signal for a provider-hosted server tool (today only
     * hosted web search). Carries the `outputIndex` (the item's stable position
     * in the response output, used to correlate the lifecycle events since CAPI
     * rotates the per-event item id), the tool kind, and the current status
     * (`in_progress` | `searching` | `completed`). Used to surface an
     * in-progress "Searching the web…" timeline row before the finalized
     * `serverTools` envelope lands on the terminal `assistant.message`.
     */
    serverToolProgress?: {
        outputIndex: number;
        kind: string;
        status: string;
    };
    /**
     * Approximate byte size of this chunk, calculated from content and all tool call data.
     */
    size: number;
};

/** Streaming delta forwarded from a sub-agent's chunk processor through the callback chain. */
declare type StreamingDeltaEvent = {
    kind: "streaming_delta";
    deltaType: "message_start";
    messageId: string;
    /**
     * Stable generation phase metadata for the streamed assistant message.
     */
    phase?: string;
} | {
    kind: "streaming_delta";
    deltaType: "message";
    messageId?: string;
    deltaContent?: string;
} | {
    kind: "streaming_delta";
    deltaType: "reasoning";
    reasoningId?: string;
    deltaContent?: string;
} | {
    kind: "streaming_delta";
    deltaType: "tool_call";
    toolCallId: string;
    toolName?: string;
    toolType?: "function" | "custom";
    inputDelta: string;
} | {
    kind: "streaming_delta";
    deltaType: "streaming_size";
    totalResponseSizeBytes?: number;
};

/**
 * Simplified streaming chunk context containing only the essential delta information
 * needed by processors. This avoids the complexity of converting between different
 * API formats (e.g., Responses API to ChatCompletion chunks).
 *
 * @deprecated In the future, we will move to a model where the individual API clients emit Core Runtime events, instead of the current model where ChatCompletions are the defacto interface.
 * Please avoid adding new streaming chunk processors, and instead consider if now is the right time to fix the abstraction gap between the ChatCompletionsClient and the ResponsesClient.
 * Talk to @jmoseley or @mrayermannmsft for more context.
 */
declare type StreamingToolCallDelta = {
    /**
     * The stable ID of the tool call this delta belongs to.
     */
    toolCallId: string;
    /**
     * Name of the tool being invoked, when known from the stream.
     */
    toolName?: string;
    /**
     * Tool call type, when known from the stream.
     */
    toolType?: "function" | "custom";
    /**
     * Raw provider tool input fragment to append for this tool call. Function/tool-use providers
     * stream serialized JSON argument text, so newlines inside JSON string values may appear as
     * escaped `\n` until the accumulated JSON is parsed. Custom tool calls stream raw custom input.
     */
    inputDelta: string;
};

declare type StrictKnownMarketplaces = StrictMarketplaceSource[];

/** Individual source entry in the strictKnownMarketplaces allowlist. */
declare type StrictMarketplaceSource = {
    source: "github";
    repo: string;
    ref?: string;
    path?: string;
} | {
    source: "git";
    url: string;
    ref?: string;
    path?: string;
} | {
    source: "url";
    url: string;
    headers?: Record<string, string>;
} | {
    source: "npm";
    package: string;
} | {
    source: "file";
    path: string;
} | {
    source: "directory";
    path: string;
} | {
    source: "hostPattern";
    hostPattern: string;
} | {
    source: "pathPattern";
    pathPattern: string;
};

export declare const SUBAGENT_ONLY_MODELS: ReadonlySet<string>;

/** Sub-agent completion details for successful execution */
export declare interface SubagentCompletedData {
    /** Human-readable display name of the sub-agent */
    agentDisplayName: string;
    /** Internal name of the sub-agent */
    agentName: string;
    /** Whether the sub-agent was torn down by cancellation - its own abort, or an ancestor being killed - instead of finishing its work. Cancellation is not a failure, so the run still reports completion; this distinguishes a torn-down sub-agent from one that ran to the end. */
    cancelled?: boolean;
    /** Wall-clock duration of the sub-agent execution in milliseconds */
    durationMs?: number;
    /** Model used by the sub-agent */
    model?: string;
    /** Tool call ID of the parent tool invocation that spawned this sub-agent */
    toolCallId: string;
    /** Total tokens (input + output) consumed by the sub-agent */
    totalTokens?: number;
    /** Total number of tool calls made by the sub-agent */
    totalToolCalls?: number;
}

/** Session event "subagent.completed". Sub-agent completion details for successful execution */
export declare interface SubagentCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Sub-agent completion details for successful execution */
    data: SubagentCompletedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "subagent.completed". */
    type: "subagent.completed";
}

/** Empty payload; the event signals that the custom agent was deselected, returning to the default agent */
export declare interface SubagentDeselectedData {
}

/** Session event "subagent.deselected". Empty payload; the event signals that the custom agent was deselected, returning to the default agent */
export declare interface SubagentDeselectedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Empty payload; the event signals that the custom agent was deselected, returning to the default agent */
    data: SubagentDeselectedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "subagent.deselected". */
    type: "subagent.deselected";
}

/** Sub-agent failure details including error message and agent information */
export declare interface SubagentFailedData {
    /** Human-readable display name of the sub-agent */
    agentDisplayName: string;
    /** Internal name of the sub-agent */
    agentName: string;
    /** Wall-clock duration of the sub-agent execution in milliseconds */
    durationMs?: number;
    /** Error message describing why the sub-agent failed */
    error: string;
    /** Model selected for the sub-agent, when known */
    model?: string;
    /** Tool call ID of the parent tool invocation that spawned this sub-agent */
    toolCallId: string;
    /** Total tokens (input + output) consumed before the sub-agent failed */
    totalTokens?: number;
    /** Total number of tool calls made before the sub-agent failed */
    totalToolCalls?: number;
}

/** Session event "subagent.failed". Sub-agent failure details including error message and agent information */
export declare interface SubagentFailedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Sub-agent failure details including error message and agent information */
    data: SubagentFailedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "subagent.failed". */
    type: "subagent.failed";
}

/**
 * Session-scoped limiter that atomically tracks sub-agent concurrency and the
 * effective depth limit. Shared by reference through ToolConfig across all
 * nesting levels. The running-count state machine — atomic acquire, underflow-
 * safe release, and the `[1, cap]` clamping applied by the update methods —
 * lives in the Rust runtime; this class is a thin wrapper over the shared
 * native handle.
 */
declare class SubAgentLimiter {
    private readonly handle;
    constructor(maxConcurrent?: number, maxDepth?: number);
    get maxConcurrent(): number;
    get maxDepth(): number;
    /**
     * Update the concurrency limit. Takes effect for future tryAcquire() calls.
     * Does not evict agents that are already running above the new limit.
     */
    updateMaxConcurrent(maxConcurrent: number): void;
    /** Update the sub-agent depth limit. Takes effect for future dispatches. */
    updateMaxDepth(maxDepth: number): void;
    /**
     * Atomically check limits and acquire a slot. Returns rejection info if rejected, undefined on success.
     * @param reacquire If true, uses a different error message for resuming idle agents.
     */
    tryAcquire(reacquire?: boolean): SubAgentLimitRejection | undefined;
    /** Release a running slot. Must be called in a finally block. Underflow-safe. */
    release(): void;
    get runningCount(): number;
}

declare interface SubAgentLimiterInfo {
    runningCount: number;
    maxConcurrent: number;
}

declare interface SubAgentLimitRejection {
    error: string;
    limitType: "concurrent";
}

/** Custom agent selection details including name and available tools */
export declare interface SubagentSelectedData {
    /** Human-readable display name of the selected custom agent */
    agentDisplayName: string;
    /** Internal name of the selected custom agent */
    agentName: string;
    /** List of tool names available to this agent, or null for all tools */
    tools: string[] | null;
}

/** Session event "subagent.selected". Custom agent selection details including name and available tools */
export declare interface SubagentSelectedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Custom agent selection details including name and available tools */
    data: SubagentSelectedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "subagent.selected". */
    type: "subagent.selected";
}

declare type SubagentSelection = {
    model?: string;
    effortLevel?: string;
    contextTier?: "inherit" | "default" | "long_context";
    autoInvoke?: boolean;
    [key: string]: unknown;
};

declare type SubagentSessionBoundary = {
    kind: "subagent_session_boundary";
    /**
     * The type of session boundary event: start, end, or failed.
     */
    sessionBoundaryType: "start" | "end" | "failed";
    agentName: string;
    agentId?: string;
    /**
     * Optional error message when the subagent failed.
     * Present on "failed" boundary events when the agent encountered an error.
     */
    error?: string;
    /**
     * Optional display name for the agent. Used by task tool agents where
     * the agent may not be in the session's customAgents list.
     */
    agentDisplayName?: string;
    /**
     * Optional description for the agent. Used by task tool agents where
     * the agent may not be in the session's customAgents list.
     */
    agentDescription?: string;
    /**
     * Resolved model the sub-agent is running with, when known.
     */
    model?: string;
};

/**
 * Options for creating a subagent session via `Session.createSubagentSession()`.
 * These control what differs from the parent session; everything else is inherited.
 */
export declare interface SubagentSessionOptions {
    /** Capabilities enabled for the subagent session. If not specified, inherits all capabilities. */
    sessionCapabilities?: Set<SessionCapability>;
    /** Whether to skip loading custom instructions (repo-level .github/copilot-instructions.md, etc.). */
    skipCustomInstructions?: boolean;
    /**
     * Whether to enable on-demand instruction discovery for the subagent
     * (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing).
     *
     * Defaults to inheriting the parent session's setting. Effective behavior also requires
     * `skipCustomInstructions` to be false (gated at `buildSettingsAndTools()`).
     */
    enableOnDemandInstructionDiscovery?: boolean;
    /**
     * Maximum decoded byte size of an inline model-facing binary tool result for
     * the subagent. Defaults to inheriting the parent session's setting.
     */
    maxInlineBinaryBytes?: number;
    /** MCP servers the subagent needs (from the agent definition). */
    mcpServers?: Record<string, MCPServerConfig>;
    /**
     * Legacy BYOK provider config inherited by the subagent. Undefined for
     * registry BYOK sessions, which propagate providers/models instead.
     */
    providerConfig?: ProviderConfig;
    /**
     * Tool allowlist for the subagent. If not specified, inherits the parent
     * session's allowlist; when specified, it is still constrained by the
     * effective denylist inherited from the parent.
     */
    availableTools?: string[];
    /**
     * Additional tools to deny for the subagent. The parent session's denylist
     * is always inherited and merged with this list. Child-specific denylists
     * follow the resolved `toolFilterPrecedence`; inherited denylists are enforced
     * as an absolute floor when the child narrows the parent with a new allowlist.
     */
    excludedTools?: string[];
    /**
     * Controls how the subagent's allowlist and denylist combine. Defaults to
     * the parent session's precedence, except inherited denylists are enforced
     * as an absolute floor when a child-specific allowlist is present.
     */
    toolFilterPrecedence?: ToolFilterPrecedence;
    /**
     * System message configuration for the subagent session.
     * Use `{ mode: "replace", content: "..." }` to provide a complete custom system prompt
     * (e.g., for subagents whose prompt is built by assembleAgentPrompt).
     * If not specified, the session uses its default CLI system prompt.
     */
    systemMessage?: SystemMessageConfig;
    /** Agent name for subagent lifecycle events (subagent.started/subagent.completed). */
    agentName?: string;
    /** Agent display name for subagent lifecycle events. */
    agentDisplayName?: string;
    /** Agent description for subagent lifecycle events. */
    agentDescription?: string;
    /**
     * Event types to suppress when bridging from child to parent session.
     * Events in this set are not re-emitted on the parent. Used by
     * sidekick agents whose parent-bridge suppresses session events and
     * streaming.
     */
    suppressedBridgeEvents?: Set<string>;
    /**
     * Callback for publishing inbox entries from sidekick agents.
     * Passed through to the child session so it can create the send_inbox tool.
     */
    sendInboxPublisher?: SendInboxPublisher;
    /**
     * The parent turn's agent task ID, propagated so child CAPI requests
     * include the X-Parent-Agent-Id header for request correlation.
     */
    parentAgentTaskId?: string;
    /** Agent task ID in the TaskRegistry for the current multi-turn agent. */
    taskRegistryAgentId?: string;
    /** Runtime-derived factory run that owns this subagent session's model usage. */
    factoryUsageRunId?: string;
    /** Shared accounting coordinator for the factory usage run. */
    factoryUsageCoordinator?: FactoryUsageCoordinator;
    /**
     * Explicit tool names the subagent needs. Non-standard tools (send_inbox, etc.)
     * are only created when listed here. Resolved from the agent definition's tools
     * array — ["*"] should be omitted (pass undefined instead).
     */
    requestedTools?: string[];
    /**
     * Resolved model the subagent will run with, when known at dispatch.
     * Forwarded to the `subagent.started` event so consumers (e.g. the CLI
     * timeline) can show the model the sub-agent is using.
     */
    modelOverride?: string;
    /**
     * A dedicated auto-mode session token minted for this subagent and paired
     * with a specific model (e.g. the rubber-duck critic running a complementary
     * model under its own `Copilot-Session-Token`). When the subagent resolves to
     * `pairedModel`, the child session forwards `token` so the request bills under
     * this independent auto session instead of the parent's. Set only for
     * complementary-strategy subagents dispatched from a CAPI auto-mode parent.
     */
    autoModeSession?: AutoModeSession;
    /**
     * When true, the subagent opts into lazy/deferred tool loading even when it
     * explicitly lists tools. Mirrors the `deferredToolLoading` flag on the agent
     * definition; honored by `clearDeferralForAgentTools`.
     */
    deferredToolLoading?: boolean;
    /**
     * Tool-search override for the subagent session, mirroring
     * {@link SessionOptions.toolSearch}. Set by dispatch sites that want to
     * change the subagent's deferral behavior independently of the parent.
     */
    toolSearch?: SessionToolSearchOptions;
    /**
     * Provider-native web-search option for the subagent session, mirroring
     * {@link SessionOptions.webSearch}. Unlike {@link toolSearch}, leaving this
     * unset does NOT mean "no override": child construction copies the parent's
     * resolved value, so a parent's opt-out reaches the child.
     *
     * The merge is monotone in the off direction. A dispatch site can narrow —
     * pass `{ enabled: false }` to disable hosted web search for this one
     * subagent under a permissive parent — but it cannot re-enable: an explicit
     * `false` anywhere up the chain wins, so passing `{ enabled: true }` under
     * an opted-out parent leaves the child opted out.
     */
    webSearch?: SessionWebSearchOptions;
    /**
     * Optional hard cap on the number of model turns (tool-call rounds) the subagent's
     * agentic loop runs. Used by constrained subagents (e.g. the search subagent) to
     * bound their iterations: the session enforces the cap by aborting itself once the
     * budget (plus one grace turn) is exceeded, and the value also drives the last-turn
     * warning. When unset, the loop runs until the model stops requesting tools.
     */
    maxAgentTurns?: number;
    /**
     * Optional warning message injected before the subagent's final allotted turn
     * (only meaningful alongside `maxAgentTurns`). Coaxes the model to produce its
     * final answer instead of issuing more tool calls.
     */
    lastTurnWarning?: string;
}

/** Subagent settings to apply, or null to clear the live session override */
declare type SubagentSettings = {
    agents?: Record<string, SubagentSettingsEntry>;
    disabledSubagents?: string[];
    maxConcurrency?: number;
    maxDepth?: number;
} | null;

/** Subagent model, reasoning effort, and context tier settings */
declare interface SubagentSettingsEntry {
    /** Context tier override for matching subagents */
    contextTier?: SubagentSettingsEntryContextTier;
    /** Reasoning effort override for matching subagents */
    effortLevel?: string;
    /** Model override for matching subagents */
    model?: string;
}

/** Context tier override for matching subagents */
declare type SubagentSettingsEntryContextTier = "inherit" | "default" | "long_context";

/** Sub-agent startup details including parent tool call and agent information */
export declare interface SubagentStartedData {
    /** Description of what the sub-agent does */
    agentDescription: string;
    /** Human-readable display name of the sub-agent */
    agentDisplayName: string;
    /** Internal name of the sub-agent */
    agentName: string;
    /** Model the sub-agent will run with, when known at start. */
    model?: string;
    /** Tool call ID of the parent tool invocation that spawned this sub-agent */
    toolCallId: string;
}

/** Session event "subagent.started". Sub-agent startup details including parent tool call and agent information */
export declare interface SubagentStartedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Sub-agent startup details including parent tool call and agent information */
    data: SubagentStartedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "subagent.started". */
    type: "subagent.started";
}

export declare type SubagentTimelineEntry = {
    kind: SubagentTimelineEntryKind;
    timestamp: number;
    summary: string;
    toolName?: string;
    success?: boolean;
};

declare type SubagentTimelineEntryKind = "assistant" | "tool_inflight" | "tool_done" | "skill" | "lifecycle";

export declare const SUPPORTED_MODELS: SupportedModelsTuple;

export declare type SupportedModel = SupportedModelsTuple[number];

declare type SupportedModelsTuple = readonly [
"claude-sonnet-5",
"claude-sonnet-4.6",
"claude-sonnet-4.5",
"claude-haiku-4.5",
"claude-fable-5",
"claude-opus-5",
"claude-opus-4.8",
"claude-opus-4.8-fast",
"claude-opus-4.7",
"claude-opus-4.6",
"claude-opus-4.5",
"gpt-5.6-sol",
"gpt-5.6-terra",
"gpt-5.6-luna",
"gpt-5.5",
"gpt-5.4",
"gpt-5.3-codex",
"gpt-5.4-mini",
"gpt-5-mini",
"mai-code-1-flash-picker",
"exec-agent-a",
"exec-agent-b",
"exec-agent-c",
"gemini-3.7-flash",
"gemini-3.6-flash",
"gemini-3.5-flash",
"gemini-3.1-pro-preview",
"grok-4.5",
"kimi-k3",
"kimi-k2.7-code",
"copilot-search-a",
"copilot-search-b",
"copilot-search-c"
];

/**
 * Subset of src/clients/types.ts that is required to actually run
 * a custom agent.
 */
export declare type SweCustomAgent = {
    name: string;
    displayName: string;
    description: string;
    tools: string[] | null;
    prompt: () => Promise<string>;
    mcpServers?: Record<string, MCPServerConfig>;
    disableModelInvocation: boolean;
    /** Git commit SHA or version identifier for this agent. Passed to MCP servers for OIDC token cache keying. */
    version?: string;
    /**
     * Model to use for this agent. When unset, inherits the outer agent's model.
     * When set but unavailable, falls back to the outer agent's model.
     */
    model?: string;
    /**
     * Reasoning effort for this agent (e.g. `"low"`, `"medium"`, `"high"`,
     * `"xhigh"`). When unset, the agent inherits the outer/main agent's reasoning
     * effort. A per-call or `/subagents` override still takes precedence.
     */
    reasoningEffort?: string;
    /**
     * GitHub-specific configuration for this agent.
     */
    github?: {
        /**
         * GitHub MCP toolsets to enable for this agent.
         * When set, a github-mcp-server entry is automatically added/adapted in
         * the agent's mcpServers with the X-MCP-Toolsets header.
         */
        toolsets?: string[];
        /**
         * GitHub permission levels for this agent's resource scopes.
         * Used to determine whether the github-mcp-server operates in readonly mode.
         */
        permissions?: Record<string, string>;
    };
    /** List of skill names to preload into this agent's context. When omitted, no skills are preloaded. */
    skills?: string[];
    /**
     * Opt-in to lazy/deferred tool loading even when the agent explicitly lists tools.
     * By default, tools the agent names in `tools` are eagerly visible to the model.
     * When true, MCP tools the agent lists stay deferred and are discovered via `tool_search_tool`.
     */
    deferredToolLoading?: boolean;
    /**
     * When true, the agent receives only the tools it explicitly lists in `tools`,
     * without the implicit required tools (e.g. `view`) that are otherwise
     * force-added to every custom-agent-as-tool. Use for agents with a
     * deliberately constrained toolset.
     *
     * Only meaningful alongside an explicit, non-wildcard `tools` list: the tool
     * filter short-circuits to "every tool" when `tools` is `["*"]`, `null`, or
     * absent, so this flag is ignored in those cases.
     */
    strictToolsList?: boolean;
    /**
     * When set, replaces the CLI system prompt entirely during send().
     * Called with the resolved tool list and cwd after tool filtering.
     * Used by built-in YAML agents running as the outer/top-level agent
     * to get the same prompt they would receive as a subagent.
     */
    buildSystemPrompt?: (tools: Tool[], cwd: string, consolidationContext?: ConsolidationContext, sessionSearchPromptContext?: SessionSearchPromptContext, options?: {
        authoredPromptOverride?: string;
    }) => Promise<SystemMessageContent>;
    /**
     * Absolute local file path of the agent definition.
     * Only set for file-based agents loaded from disk (user `~/.copilot/agents`,
     * project `.github/agents`, project `.claude/agents`, and plugin agents).
     * Not set for remote agents (loaded from CAPI) or for agents constructed in
     * memory by CCA mappers, since the runtime does not have a local file path
     * for those.
     */
    path?: string;
};

/**
 * Append mode: Use CLI foundation with optional appended content (default).
 */
declare interface SystemMessageAppendConfig {
    mode?: "append";
    /**
     * Additional instructions added to the `runtime_instructions` section.
     */
    content?: string;
}

/**
 * A single block of system message content.
 * When `isStatic` is true, the block contains content that is identical
 * across users on the same build/model/tool configuration (e.g., identity,
 * guidelines, code-change instructions). This enables independent cache
 * breakpoints for static vs per-user content.
 */
declare type SystemMessageBlock = {
    content: string;
    isStatic?: boolean;
};

/**
 * System message configuration for session creation.
 * - Append mode (default): SDK foundation + optional custom content
 * - Replace mode: Full control, caller provides entire system message
 * - Customize mode: Section-level overrides with graceful fallback
 */
declare type SystemMessageConfig = SystemMessageAppendConfig | SystemMessageReplaceConfig | SystemMessageCustomizeConfig;

/**
 * System message content that can be either a plain string (single block,
 * backward compatible) or a structured array of blocks (enabling split
 * cache breakpoints for static vs per-user content).
 */
declare type SystemMessageContent = string | {
    blocks: SystemMessageBlock[];
};

/**
 * Customize mode: Override individual sections of the system prompt.
 * Keeps the SDK-managed prompt structure while allowing targeted modifications.
 */
declare interface SystemMessageCustomizeConfig {
    mode: "customize";
    /**
     * Override specific sections or groups of the system prompt.
     *
     * **Group IDs** (e.g., "identity") target named collections of sections:
     * - **remove**: clears all members that don't have an explicit leaf entry.
     * - **replace**: clears ALL members, places content at the group's anchor.
     * - **transform**: concatenates all members, passes to transform callback
     *   (keyed by group ID), places result at anchor, clears all members.
     * - **prepend**: prepends content to the first member in the group.
     * - **append**: appends content to the last member in the group.
     * - **preserve**: no-op.
     *
     * Unknown section IDs gracefully fall back: content-bearing overrides are
     * appended to additional instructions, and "remove" on unknown sections is
     * a silent no-op.
     */
    sections?: Partial<Record<SystemPromptSection | SystemPromptSectionGroup, SectionOverride>> & Record<string, SectionOverride | undefined>;
    /**
     * Additional content added to the `runtime_instructions` section.
     * Equivalent to append mode's content field — provided for convenience.
     */
    content?: string;
}

/** System/developer instruction content with role and optional template metadata */
export declare interface SystemMessageData {
    /** The system or developer prompt text sent as model input */
    content: string;
    /** Logical interaction identifier for the model run receiving this prompt */
    interactionId?: string;
    /** Metadata about the prompt template and its construction */
    metadata?: SystemMessageMetadata;
    /** Optional name identifier for the message source */
    name?: string;
    /** Message role: "system" for system prompts, "developer" for developer-injected instructions */
    role: SystemMessageRole;
}

/** Session event "system.message". System/developer instruction content with role and optional template metadata */
export declare interface SystemMessageEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** System/developer instruction content with role and optional template metadata */
    data: SystemMessageData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "system.message". */
    type: "system.message";
}

/** Metadata about the prompt template and its construction */
export declare interface SystemMessageMetadata {
    /** Version identifier of the prompt template used */
    promptVersion?: string;
    /** Template variables used when constructing the prompt */
    variables?: Record<string, unknown>;
}

/**
 * Replace mode: Use caller-provided system message entirely.
 * Removes all SDK guardrails including security restrictions.
 */
declare interface SystemMessageReplaceConfig {
    mode: "replace";
    /**
     * Complete system message content.
     * Replaces the entire SDK-managed system message.
     *
     * May contain {@link MEMORY_PLACEHOLDER}; when the session has the `memory`
     * capability the runtime replaces it with the store instructions and the
     * `<memories>` block. See {@link MEMORY_PLACEHOLDER} for the exact semantics.
     */
    content: string;
    /**
     * Structured system message blocks for providers that support split cache
     * breakpoints. When provided, `content` remains the flattened fallback.
     *
     * Each block's content may contain {@link MEMORY_PLACEHOLDER}, which is
     * substituted per block under the same rules as `content`.
     */
    contentBlocks?: SystemMessageBlock[];
}

/** Message role: "system" for system prompts, "developer" for developer-injected instructions */
export declare type SystemMessageRole = "system" | "developer";

/** Structured metadata identifying what triggered this notification */
declare type SystemNotification = SystemNotificationAgentCompleted | SystemNotificationAgentIdle | SystemNotificationNewInboxMessage | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted | SystemNotificationInstructionDiscovered | SystemNotificationFactoryCompleted | SystemNotificationUnclassified;
export { SystemNotification }
export { SystemNotification as SystemNotificationKind }

/** System notification metadata for a background agent that completed or failed, including agent ID, type, status, description, and prompt. */
export declare interface SystemNotificationAgentCompleted {
    /** Unique identifier of the background agent */
    agentId: string;
    /** Type of the agent (e.g., explore, task, general-purpose) */
    agentType: string;
    /** Human-readable description of the agent task */
    description?: string;
    /** The full prompt given to the background agent */
    prompt?: string;
    /** Whether the agent completed successfully or failed */
    status: SystemNotificationAgentCompletedStatus;
    /** Type discriminator. Always "agent_completed". */
    type: "agent_completed";
}

/** Whether the agent completed successfully or failed */
export declare type SystemNotificationAgentCompletedStatus = "completed" | "failed";

/** System notification metadata for a background agent that became idle, including agent ID, type, and description. */
export declare interface SystemNotificationAgentIdle {
    /** Unique identifier of the background agent */
    agentId: string;
    /** Type of the agent (e.g., explore, task, general-purpose) */
    agentType: string;
    /** Human-readable description of the agent task */
    description?: string;
    /** Type discriminator. Always "agent_idle". */
    type: "agent_idle";
}

/** System-generated notification for runtime events like background task completion */
export declare interface SystemNotificationData {
    /** The notification text, typically wrapped in <system_notification> XML tags */
    content: string;
    /** Structured metadata identifying what triggered this notification */
    kind: SystemNotification;
}

/** Session event "system.notification". System-generated notification for runtime events like background task completion */
export declare interface SystemNotificationEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** System-generated notification for runtime events like background task completion */
    data: SystemNotificationData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "system.notification". */
    type: "system.notification";
}

/** System notification metadata for a factory execution attempt that reached a terminal state. */
export declare interface SystemNotificationFactoryCompleted {
    /** Execution attempt that reached this terminal state. */
    attempt: number;
    /** Consumed AI usage in nano-AIU. */
    consumedNanoAiu: number;
    /** Subagents consumed by the run across all attempts. */
    consumedSubagents: number;
    /** Accumulated active execution time in milliseconds. */
    elapsedMs: number;
    /** Persisted factory name. */
    factoryName: string;
    /** Machine-readable terminal failure details, when present. */
    failure?: unknown;
    /** Bounded prompt-safe preview of the completed result. */
    resultPreview?: string;
    /** Actionable run_factory resume guidance for a resource-limit failure. */
    retryGuidance?: string;
    /** Factory run identifier. */
    runId: string;
    /** Terminal status reached by this execution attempt. */
    status: SystemNotificationFactoryCompletedStatus;
    /** Type discriminator. Always "factory_completed". */
    type: "factory_completed";
}

/** Terminal status reached by a factory execution attempt. */
export declare type SystemNotificationFactoryCompletedStatus = "completed" | "halted" | "cancelled" | "error";

/** System notification metadata for an instruction file discovered during tool access, including source, trigger file, and tool. */
export declare interface SystemNotificationInstructionDiscovered {
    /** Human-readable label for the timeline (e.g., 'AGENTS.md from packages/billing/') */
    description?: string;
    /** Relative path to the discovered instruction file */
    sourcePath: string;
    /** Path of the file access that triggered discovery */
    triggerFile: string;
    /** Tool command that triggered discovery (currently always 'view') */
    triggerTool: string;
    /** Type discriminator. Always "instruction_discovered". */
    type: "instruction_discovered";
}

/** System notification metadata for a new inbox message, including entry ID, sender details, and summary. */
export declare interface SystemNotificationNewInboxMessage {
    /** Unique identifier of the inbox entry */
    entryId: string;
    /** Human-readable name of the sender */
    senderName: string;
    /** Category of the sender (e.g., sidekick-agent, plugin, hook) */
    senderType: string;
    /** Short summary shown before the agent decides whether to read the inbox */
    summary: string;
    /** Type discriminator. Always "new_inbox_message". */
    type: "new_inbox_message";
}

/** System notification metadata for a shell session that completed, including shell ID, optional exit code, and description. */
export declare interface SystemNotificationShellCompleted {
    /** Human-readable description of the command */
    description?: string;
    /** Exit code of the shell command, if available */
    exitCode?: number;
    /** Unique identifier of the shell session */
    shellId: string;
    /** Type discriminator. Always "shell_completed". */
    type: "shell_completed";
}

/** System notification metadata for a detached shell session that completed, including shell ID and description. */
export declare interface SystemNotificationShellDetachedCompleted {
    /** Human-readable description of the command */
    description?: string;
    /** Unique identifier of the detached shell session */
    shellId: string;
    /** Type discriminator. Always "shell_detached_completed". */
    type: "shell_detached_completed";
}

/** System notification metadata from an external host that does not match a runtime-owned notification kind. */
export declare interface SystemNotificationUnclassified {
    /** Opaque metadata supplied by the external host, when present. */
    metadata?: unknown;
    /** Type discriminator. Always "unclassified". */
    type: "unclassified";
}

/**
 * Known system prompt section identifiers for the "customize" mode.
 * Each section corresponds to a leaf-level part of the system prompt.
 *
 * `custom_instructions` targets repository and organization custom instruction
 * sources. `runtime_instructions` targets runtime-provided context and instructions,
 * assembled into the CLI prompt's internal `additionalInstructions` slot from
 * sources such as `systemMessage.content`, system notifications, memories,
 * workspace context, mode-specific instructions, and content-exclusion policy.
 */
declare type SystemPromptSection = "preamble" | "tone" | "tool_efficiency" | "environment_context" | "code_change_rules" | "guidelines" | "safety" | "custom_instructions" | "runtime_instructions" | "last_instructions";

/**
 * Named groups of sections for bulk operations.
 * Groups support all section actions via a two-pass model:
 * leaf operations apply first, then group operations apply on the post-leaf state.
 */
declare type SystemPromptSectionGroup = "identity" | "tool_instructions";

/** Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. */
declare interface TaskAgentInfo {
    /** ISO 8601 timestamp when the current active period began */
    activeStartedAt?: string;
    /** Accumulated active execution time in milliseconds */
    activeTimeMs?: number;
    /** Type of agent running this task */
    agentType: string;
    /** Whether the task is currently in the original sync wait and can be moved to background mode. False once it is already backgrounded, idle, finished, or no longer has a promotable sync waiter. */
    canPromoteToBackground?: boolean;
    /** ISO 8601 timestamp when the task finished */
    completedAt?: string;
    /** Short description of the task */
    description: string;
    /** Error message when the task failed */
    error?: string;
    /** Whether task execution is synchronously awaited or managed in the background */
    executionMode?: TaskExecutionMode;
    /** Unique task identifier */
    id: string;
    /** ISO 8601 timestamp when the agent entered idle state */
    idleSince?: string;
    /** Most recent response text from the agent */
    latestResponse?: string;
    /** Requested model override for the task when specified */
    model?: string;
    /** Most recent prompt delivered to the agent. Updated whenever the agent receives a follow-up message. */
    prompt: string;
    /** Runtime model resolved for the task when available */
    resolvedModel?: string;
    /** Result text from the task when available */
    result?: string;
    /** ISO 8601 timestamp when the task was started */
    startedAt: string;
    /** Current lifecycle status of the task */
    status: TaskStatus_2;
    /** Tool call ID associated with this agent task */
    toolCallId: string;
    /** Task kind */
    type: "agent";
}

/** Progress snapshot for an agent task, with recent activity lines and optional latest intent. */
declare interface TaskAgentProgress {
    /** The most recent intent reported by the agent */
    latestIntent?: string;
    /** Recent tool execution events converted to display lines */
    recentActivity: TaskProgressLine[];
    /** Progress kind */
    type: "agent";
}

declare interface TaskAugmentedRequestParams {
    _meta?: RequestMeta;
    task?: TaskMetadata;
}

/**
 * Callback invoked whenever the set of tracked tasks changes.
 */
declare type TaskChangeCallback = () => void;

/** Task completion notification with summary from the agent */
export declare interface TaskCompleteData {
    /** Active autopilot objective ID evaluated by the completion reviewer */
    objectiveId?: number;
    /** Semantic completion decision. Absent on legacy events and invalid tool calls */
    outcome?: TaskCompletionOutcome;
    /** Label-safe runtime rationale for the completion decision (e.g. a cancellation or pause/resume downgrade), when one applies. Reviewer-authored rationale is intentionally omitted here because this event has no IFC label channel; the reviewer's findings remain available through its own labeled sub-agent events */
    reason?: string;
    /** Whether the task was accepted as complete. False when validation failed or completion was rejected or blocked by the reviewer */
    success?: boolean;
    /** Summary of the completed task, provided by the agent */
    summary?: string;
}

/** Session event "session.task_complete". Task completion notification with summary from the agent */
declare interface TaskCompleteEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Task completion notification with summary from the agent */
    data: TaskCompleteData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.task_complete". */
    type: "session.task_complete";
}
export { TaskCompleteEvent as SessionTaskCompleteEvent }
export { TaskCompleteEvent }

/**
 * Callback invoked when any task completes, fails, or is cancelled.
 */
declare type TaskCompletionCallback = (task: TaskEntry) => void;

declare class TaskCompletionCriteriaTelemetry implements Disposable_2 {
    private readonly session;
    private state;
    private unsubscribeUserMessage;
    private unsubscribeTaskComplete;
    constructor(session: Session);
    dispose(): void;
    handleTaskComplete(event: TaskCompleteEvent): void;
    handleUserMessage(event: UserMessageEvent): Promise<void>;
    /**
     * Resolves the `TASK_COMPLETION_CRITERIA` A/B experiment
     * (`copilot_cli_task_completion_criteria`) via its ExP-aware accessor, mirroring
     * {@link usePlanImplementationGuardEnabled}. Only the treatment arm runs the
     * judge and emits `task_completion_criteria` telemetry; the control arm is fully
     * inert. Fails closed (returns `false`) if the flag cannot be resolved so the
     * control arm never leaks events.
     */
    private isExperimentEnabled;
    private judgeTaskCompletionCriteria;
}

/**
 * Semantic result of a valid autopilot `task_complete` request, produced by the
 * independent completion reviewer. `completed` accepts the completion,
 * `continue` keeps the objective running, and `blocked` pauses it.
 */
declare interface TaskCompletionDecision {
    readonly outcome: TaskCompletionOutcome_2;
    readonly reason?: string;
    readonly objectiveId?: number;
    /**
     * IFC (FIDES) label metadata (`ifc`/`ifc_full`) captured from the completion
     * reviewer sub-agent result. The reviewer can read private or untrusted files,
     * so its label must travel with any reviewer-derived text that flows into the
     * `task_complete` result; this is merged into the final tool result's
     * `mcpMeta` so the parent joins the child's label on ingress instead of
     * treating the reviewer output as unlabeled.
     * @internal
     */
    readonly reviewerResultMeta?: Record<string, unknown>;
    /**
     * Whether `reason` was derived from reviewer-produced text (as opposed to a
     * constant runtime string). The reviewer reads potentially private files, so
     * its verdict text carries an IFC label on the tool result; the host gates
     * this text off its unlabeled channels (the `session.task_complete` event and
     * persisted state) when `reviewerDerived` is true.
     * @internal
     */
    readonly reviewerDerived?: boolean;
    /**
     * Set when `outcome` is a fail-open `completed` produced because the
     * consecutive-reviewer-rejection budget was exhausted (the reviewer never
     * accepted the objective), rather than a real PASS. The host emits a generic
     * `session.warning` when set. Omitted (falsy) for every other decision.
     * @internal
     */
    readonly completionRejectionBudgetExhausted?: boolean;
    /**
     * Eligibility token captured when the decision was evaluated. Used to detect a
     * pause/resume that starts a new objective turn (same objective ID, new token)
     * between evaluation and when the result is applied, so a stale decision is not
     * used to complete or block the resumed turn.
     * @internal
     */
    readonly completionEligibilityToken?: number;
}

/** Semantic result of evaluating a task completion request */
export declare type TaskCompletionOutcome = "completed" | "continue" | "blocked";

declare type TaskCompletionOutcome_2 = TaskCompletionOutcome;

/**
 * A task entry in the registry — an agent, a shell, or a long-lived service.
 */
declare type TaskEntry = TaskEntryBase & (AgentTaskFields | ShellTaskFields | ServiceTaskFields);

/**
 * Common fields shared by every task entry.
 */
declare interface TaskEntryBase {
    /** Unique task identifier */
    id: string;
    /** ID of the agent that spawned this task ("session" for root) */
    ownerId: string;
    /** Parent task ID for cascading abort */
    parentId?: string;
    /** Controller whose signal is wired to the underlying work */
    abortController: AbortController;
    /** Current lifecycle status */
    status: TaskStatus;
    /** Human-readable description */
    description?: string;
    /** Timestamp when the task was registered */
    startedAt: number;
    /** Timestamp when the task finished */
    completedAt?: number;
    /** Accumulated milliseconds the task has spent actively running (excludes idle time) */
    activeTimeMs: number;
    /** Timestamp when the current active period began (undefined while idle or finished) */
    activeStartedAt?: number;
    /** Timestamp when the task entered idle state (undefined while running or finished) */
    idleSince?: number;
}

/** Whether task execution is synchronously awaited or managed in the background */
declare type TaskExecutionMode = "sync" | "background";

/** Tracked task union returned by task APIs, containing either an agent task or a shell task. */
declare type TaskInfo = TaskAgentInfo | TaskShellInfo;

/** Background tasks currently tracked by the session. */
declare interface TaskList {
    /** Currently tracked tasks */
    tasks: TaskInfo[];
}

/**
 * Options for {@link TaskRegistry.list}.
 */
declare interface TaskListOptions {
    /** Filter by task type */
    type?: TaskType;
    /** Filter by owner */
    ownerId?: string;
    /** Include non-running tasks (default: true) */
    includeCompleted?: boolean;
}

declare interface TaskMetadata {
    ttl?: number;
}

/** Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. */
declare type TaskProgress = TaskAgentProgress | TaskShellProgress | null;

/** Timestamped display line for task progress output or recent agent activity. */
declare interface TaskProgressLine {
    /** Display message, e.g., "▸ bash", "✓ edit src/foo.ts" */
    message: string;
    /** ISO 8601 timestamp when this event occurred */
    timestamp: string;
}

/**
 * Unified registry for tracking background agents and shell processes.
 *
 * Each task has an owner, optional parent for cascading abort,
 * and lifecycle callbacks for UI updates and completion notifications.
 */
declare class TaskRegistry {
    private static readonly registriesByNativeHandle;
    private readonly nativeHandle;
    /**
     * Native handle id captured at construction. Reading `nativeHandle.id` after
     * {@link dispose} throws ("TaskRegistryHandle has been disposed"), so we cache
     * the id here to keep {@link getNativeHandleId} and the map cleanup in
     * {@link dispose} safe across the shutdown race. Handle ids are minted from a
     * process-global monotonic counter and are not reissued within any realistic
     * session lifetime, so a cached id resolves to "unknown handle" (never another
     * live registry) once disposed.
     */
    private readonly nativeHandleId;
    private readonly liveHandles;
    private parentRegistry?;
    private parentAgentId?;
    private readonly childRegistries;
    private readonly pendingPromises;
    /**
     * Agent ids whose executor was cancelled and whose body has not yet returned
     * (its {@link pendingPromises} entry still lingers). Tracked independently of
     * the task record so the "still unwinding" signal survives the record being
     * removed — e.g. a cancelled background agent read with `removeAgent=true`.
     * Populated when {@link cancelTaskFromPlan} cancels an agent that still has a
     * pending executor promise and cleared when that promise settles.
     */
    private readonly cancelledDrainingAgents;
    /** Resolvers for waking idle agents when a new message arrives */
    private readonly messageResolvers;
    /** Resolvers for callers waiting on the next turn to complete */
    private readonly turnWaiters;
    /** Resolvers for promotable sync waits waiting to be released into background mode */
    private readonly promotionWaiters;
    /** Resolvers for waitForAgents() callers waiting on a task to leave the running state */
    private readonly statusWaiters;
    private onChangeCallback?;
    private onCompletionCallback?;
    private onAgentIdleCallback?;
    private onAgentStartedCallback?;
    private readonly factoryLifecycleObservers;
    private subAgentLimiter?;
    private readonly agentLimiterSlots;
    /**
     * Agents started without a multi-turn continuation loop (see
     * `Session.prepareSubagent`'s `suppressMultiTurn`, used for factory agents).
     * Nothing ever drains their message queue, so accepting a message would
     * silently swallow it: {@link sendMessage} rejects for these instead.
     */
    private readonly nonMessageableAgentIds;
    private factoryUsageRunId?;
    private factoryUsageCoordinator?;
    private readonly factoryUsageLeases;
    constructor();
    private disposed;
    /**
     * Tear down the native registry handle. After this returns the registry is
     * **inert**: every method that would otherwise touch the freed
     * {@link nativeHandle} short-circuits to an empty/not-found default instead of
     * calling through (which would throw "TaskRegistryHandle has been disposed").
     *
     * `dispose()` runs only at session shutdown, so late async continuations —
     * background-agent completion/idle callbacks, progress updates, status/list
     * reads, `waitForAgents`, `sendMessage`, shell-task updates — can still land
     * on this object after it is gone. Because `disposed` flips to `true`
     * synchronously *before* the handle is freed, guarding on it reliably covers
     * the whole post-dispose window and cannot mask a live-registry bug. Idempotent.
     */
    dispose(): void;
    setParentRegistry(registry: TaskRegistry | undefined, parentAgentId?: string): void;
    hasParentRegistry(): boolean;
    getRootRegistry(): TaskRegistry;
    /**
     * Set the sub-agent limiter for concurrent agent tracking.
     * The registry will acquire/release slots automatically during agent lifecycle.
     */
    setSubAgentLimiter(limiter: SubAgentLimiter): void;
    setFactoryUsageContext(runId: string | undefined, coordinator: FactoryUsageCoordinator | undefined): void;
    /** Returns a snapshot of the current sub-agent concurrency state. */
    getSubAgentLimiterInfo(): SubAgentLimiterInfo | undefined;
    /** Update the sub-agent concurrency limit (e.g., when auth/plan tier changes). */
    updateSubAgentMaxConcurrent(maxConcurrent: number): void;
    /**
     * Returns the effective sub-agent depth limit held on the shared limiter,
     * or undefined when no limiter is set.
     */
    getSubAgentMaxDepth(): number | undefined;
    /** Update the sub-agent depth limit (e.g., when auth/plan tier or settings change). */
    updateSubAgentMaxDepth(maxDepth: number): void;
    /**
     * Runs an unregistered agent while accounting for it in the session-wide
     * concurrency limit.
     */
    runWithSubAgentLimit<T>(executeAgent: () => Promise<T>): Promise<T>;
    /**
     * Set a callback that fires whenever a task is registered, removed, or
     * changes status. Useful for UI re-renders.
     */
    setOnChangeCallback(callback: TaskChangeCallback | undefined): void;
    /** Manually trigger the change callback (e.g., after mutating an entry in-place). */
    notifyChange(): void;
    /** Deliver a terminal transition that was committed by a native tool driver. */
    notifyNativeCompletion(id: string): void;
    /**
     * Record that a read already delivered an agent's idle or terminal state.
     * Native storage keeps this bounded state alive across proxy refreshes and
     * task removal, avoiding a late duplicate notification.
     */
    recordReadCommunicatedState(agentId: string, kind: "idle" | "terminal", turnCount: number): void;
    isReadCommunicatedStateRedundant(agentId: string, kind: "idle" | "terminal", turnCount: number): boolean;
    /**
     * Set a callback that fires when any task reaches a terminal state
     * (completed, failed, or cancelled).
     */
    setOnCompletionCallback(callback: TaskCompletionCallback | undefined): void;
    /**
     * Set a callback that fires when a multi-turn agent enters idle state
     * (finished processing a turn and waiting for the next message).
     * Used to send system notifications so the parent model knows results are available.
     */
    setOnAgentIdleCallback(callback: ((task: AgentTaskEntry) => void) | undefined): void;
    /**
     * Set a callback that fires when a new agent task is registered.
     * Used to emit session events (e.g. subagent.started) for background agents.
     */
    setOnAgentStartedCallback(callback: ((task: AgentTaskEntry) => void) | undefined): void;
    addFactoryLifecycleObserver(observer: FactoryTaskLifecycleObserver): () => void;
    /**
     * Register a new task. Throws if a task with the same ID already exists.
     */
    register(entry: TaskEntry): void;
    /**
     * Retrieve a single task by ID.
     */
    get(id: string): TaskEntry | undefined;
    /**
     * Retrieve only the lifecycle status of a task by ID, without exposing the
     * mutable task entry. Returns undefined when the task is unknown.
     */
    getTaskStatus(id: string): TaskStatus | undefined;
    /** Numeric native handle for Rust drivers that update this registry directly. */
    getNativeHandleId(): number;
    /** Serialized registry-tree topology for native agent tool resolution. */
    getAgentToolGraphJson(): string;
    registerAgentToolCallbacks(): number;
    private static readAgentToolHost;
    private static deliverAgentToolHost;
    private static applyAgentToolReadEffects;
    /**
     * List tasks with optional filters. Every agent can see every task.
     */
    list(options?: TaskListOptions): TaskEntry[];
    getBackgroundAgentTasks(): AgentTask_2[];
    getServiceTasks(): ServiceTask_2[];
    private promotionWaiterIds;
    private liveResultOverlay;
    private hydrateTask;
    private serializeTask;
    listAgents(options?: AgentListOptions): ListedAgentTask[];
    findAgent(agentId: string, options?: AgentLookupOptions): AgentLookupResult | undefined;
    resolveAgentRecipients(options: {
        agentIds?: string[];
        scope?: "siblings" | "children";
        taskRegistryAgentId?: string;
        siblingCommunicationEnabled: boolean;
    }): AgentRecipientResolution;
    private getAgentEntries;
    /**
     * Serialize the live registry tree into the structural view consumed by the
     * native agent-visibility resolver. JavaScript owns the live registry
     * objects and entries; Rust owns the graph traversal, relation labeling,
     * dedup, and completion filtering. Registries are emitted in pre-order DFS
     * from the root so their assigned indices match the traversal order the
     * resolver expects, and `registriesByIndex` maps those indices back to the
     * live registries so results re-hydrate into live entry objects.
     */
    private buildVisibilityInput;
    /**
     * Cancel a task and all of its descendants.
     *
     * Only the task's owner or the root session (`"session"`) may cancel.
     * Returns `true` if the task was found **and** running (and is now cancelled).
     */
    cancel(id: string, requesterId: string): boolean;
    /**
     * Promote an active agent task into background mode.
     *
     * If a sync caller is currently waiting on the agent's first turn, that
     * wait is released so the caller can continue while the agent keeps running.
     */
    promoteAgentToBackground(id: string, requesterId: string): boolean;
    /**
     * Whether the given agent task currently has a promotable sync wait.
     */
    canPromoteAgentToBackground(id: string): boolean;
    /**
     * Mark a task as completed.
     */
    complete(id: string, result?: unknown): void;
    /**
     * Mark a task as failed.
     */
    fail(id: string, error: string): void;
    /** Re-dispatch a terminal completion notification without mutating native state. */
    renotifyCompletion(id: string): void;
    /**
     * Remove a non-running task from the registry.
     *
     * Only the task's owner or the root session may remove.
     */
    remove(id: string, requesterId: string): boolean;
    /**
     * Returns `true` if any task is currently in the "running" state.
     */
    hasRunningTasks(): boolean;
    /**
     * Get all direct children of a given parent task.
     */
    getChildren(parentId: string): TaskEntry[];
    /**
     * Wait for every currently-running agent task to reach a terminal state.
     *
     * Shell tasks are excluded because their registry status reflects the
     * session lifetime, not individual command activity.  Use
     * `shellContext.waitForActiveShells()` to wait for in-progress
     * shell commands.
     *
     * Resolves immediately if nothing is running.
     */
    waitForAgents(): Promise<void>;
    /**
     * Whether any multi-turn agent is currently `"running"` in this registry or
     * any descendant child registry. Unlike `list()`, which only inspects this
     * registry, this recurses the `childRegistries` tree so that a running
     * nested subagent whose parent task is parked (idle) is still observed. Used
     * to gate rewind admission, which must not proceed while any agent anywhere
     * in the shared tree can still mutate files.
     */
    hasRunningAgentsInTree(): boolean;
    /** Cancel agent executors owned by this registry and all child registries. */
    cancelAgentExecutions(includeIdle?: boolean): number;
    /**
     * Collect the in-flight executor-body promises owned by this registry and
     * all descendant child registries. Each promise settles only when an
     * agent's executor closure actually returns — i.e. after it observes
     * cancellation and its current tool call finishes — unlike task status,
     * which `cancelAgentExecutions()` flips to `cancelled` synchronously before
     * the body unwinds. Disposal awaits these (bounded by a deadline) so a final
     * in-flight file write is still captured before the shared rewind manager is
     * torn down. The stored promises never reject (their chain is
     * `.then().catch().finally()`), so callers can await them directly.
     */
    collectPendingExecutionsInTree(): Promise<void>[];
    /**
     * Whether any executor closure in this registry or a descendant belongs to a
     * *cancelled* agent whose body has not yet returned (its `pendingPromises`
     * entry still lingers).
     *
     * This is deliberately narrower than "any pending promise": a multi-turn or
     * persistent agent parked in an idle `waitForMessage` also keeps an unsettled
     * `pendingPromises` entry, yet it is a safe steady state (it is not executing
     * a tool and cannot write) and must NOT block rewind — the original
     * status-based gate ({@link hasRunningAgentsInTree}) correctly allowed it.
     * The genuinely dangerous window is a *cancelled* executor: `cancel()` flips
     * status to `cancelled` synchronously, but the closure keeps unwinding and
     * its in-flight tool call can still land one last untracked write. Rewind
     * admission refuses in exactly that window so a late write cannot re-modify
     * files that were just rolled back, while still admitting rewind when agents
     * are merely idle-parked. Running agents are covered separately by
     * {@link hasRunningAgentsInTree}; completed/failed tasks are past their last
     * write, so only `cancelled` is checked here.
     */
    hasDrainingCancelledExecutionsInTree(): boolean;
    /**
     * Starts a background agent execution, registers it, and tracks the promise.
     * @param agentType - The type of agent to run
     * @param description - Short description of the task
     * @param prompt - The prompt to send to the agent
     * @param executeAgent - Function that actually executes the agent, receives an AbortSignal
     * @param options - Optional agent metadata
     * @returns The agent ID for tracking
     */
    startAgent(agentType: string, description: string, prompt: string, executeAgent: (abortSignal: AbortSignal) => Promise<unknown>, options?: {
        modelOverride?: string;
        toolCallId?: string;
        ownerId?: string;
        parentId?: string;
        preGeneratedAgentId?: string;
        executionMode?: AgentExecutionMode;
        factoryRunId?: string;
        factoryUsageRunId?: string;
        factoryUsageCoordinator?: FactoryUsageCoordinator;
        /**
         * Whether this agent runs a multi-turn continuation loop that will
         * consume queued messages. Defaults to `true`; pass `false` for
         * agents started with the continuation loop suppressed so
         * {@link sendMessage} rejects instead of queueing a message no one
         * will ever read.
         */
        acceptsMessages?: boolean;
    }): string;
    private _startAgentInner;
    /**
     * Gets the result of a background agent, optionally waiting for completion.
     * @param agentId - The agent ID to query
     * @param wait - Whether to wait for completion if still running
     * @param timeoutMs - Maximum time to wait in milliseconds (default: 30000).
     * Pass null to wait without a timeout.
     * @param releaseOnPromotion - Whether explicit background promotion should release this wait early.
     * Use this only for the initial sync task-tool wait; background/read_agent waits should continue
     * waiting for the next turn or completion.
     * @returns The task entry and optional result, or undefined if not found
     */
    getAgentResult(agentId: string, wait?: boolean, timeoutMs?: number | null, releaseOnPromotion?: boolean): Promise<{
        task: AgentTaskEntry;
        result?: unknown;
        timedOut?: boolean;
        promoted?: boolean;
    } | undefined>;
    /**
     * Register a long-lived background service (e.g. an LSP server) whose
     * initialization the user and agent want to observe. Starts in the
     * `running` state with `ready === false`.
     *
     * @returns the task id (also used as the `agent_id` for `read_agent`).
     */
    registerService(opts: {
        id: string;
        ownerId?: string;
        serviceKind: string;
        serviceId: string;
        clientKey?: string;
        description?: string;
        phase?: string;
        initialLog?: string;
    }): string;
    /**
     * Reset a service that is not actively initializing — either a terminal
     * state (`failed`/`completed`/`cancelled`) or a ready `idle` state — back to
     * `running`, clearing its readiness/error and progress.
     *
     * A service entry is keyed by its stable id, but the underlying instance can
     * be recreated: an LSP client is respawned after a failed start, or after the
     * cache evicts a previously-ready one, producing a fresh reporter that targets
     * the same id. Without this reset, `onStart`/`onReady` would no-op against the
     * lingering entry (its `registerService` is skipped, and a stale `failed`
     * entry can't be re-readied), so a recovered server would keep reporting the
     * old `failed`/`ready` state in the `/lsp` panel, `read_agent`, and the
     * `<lsp_servers>` reminder. No-op (returns `false`) if the service is absent
     * or already `running` (actively initializing — nothing to reset).
     */
    restartService(id: string, message?: string): boolean;
    /**
     * Cheap count of service tasks matching an optional filter, without
     * materializing or copying any service logs. Used by render paths (e.g. the
     * "N LSP servers initializing" statusbar hint) that fire on every forwarded
     * log line and must not pay O(log) per service per event.
     */
    countServices(filter?: {
        status?: TaskStatus;
        serviceKind?: string;
    }): number;
    /**
     * Append a line to a service's server log and optionally update its
     * current phase/percentage. Wakes any `getServiceResult({ wait: true })`
     * callers so a blocked agent resumes on the next log line.
     */
    appendServiceLog(id: string, message: string, update?: {
        phase?: string;
        percentage?: number;
    }): void;
    /**
     * Mark a service as initialized and ready to serve requests. The entry moves
     * to the `idle` state (alive but not actively initializing) and is NOT
     * garbage-collected, mirroring a language server that stays up for the rest
     * of the session.
     */
    markServiceReady(id: string, message?: string): void;
    /**
     * Read a service's current state, optionally blocking until the next log
     * line, readiness, or failure. Reuses the same wait machinery as
     * `getAgentResult`, so `read_agent({ wait: true })` tails the server log.
     */
    getServiceResult(id: string, wait?: boolean, timeoutMs?: number | null): Promise<{
        task: ServiceTaskEntry;
        timedOut?: boolean;
    } | undefined>;
    /** Wake callers blocked in {@link getServiceResult} for this service. */
    private wakeServiceWaiters;
    /**
     * Sends a message to an agent's message queue.
     * If the agent is idle, wakes it up to process the message.
     */
    sendMessage(agentId: string, message: AgentMessage): Promise<true | string>;
    /**
     * Waits for a message to arrive in the agent's queue.
     * Called by the agent executor loop when the agent has finished a turn.
     * Sets the agent status to "idle" while waiting.
     */
    waitForMessage(agentId: string, abortSignal?: AbortSignal): Promise<AgentMessage | undefined>;
    /**
     * Records a turn response for an agent.
     * Updates both latestResponse and appends to turnHistory.
     */
    setLatestResponse(agentId: string, response: string, inboundMessage?: AgentMessage, responseWasModified?: boolean): void;
    /**
     * Updates only the display-facing latest response for an agent, without
     * appending to turnHistory or waking turn waiters. Used for mid-turn updates
     * (e.g. a persistent sidekick publishing inbox content during a turn) where a
     * full {@link setLatestResponse} would fabricate spurious turns and prematurely
     * wake read_agent waiters.
     */
    setLatestDisplayResponse(agentId: string, response: string): void;
    setAgentNotificationResultConsumed(agentId: string, consumed: boolean): boolean;
    /** Updates the lightweight progress snapshot for an agent identified by its parent tool call ID. */
    setAgentProgress(toolCallId: string, progress: AgentProgressInfo | undefined): void;
    /** Records the latest reported intent for an agent identified by its parent tool call ID. */
    setAgentIntent(toolCallId: string, latestIntent: string | undefined): void;
    /**
     * Updates MCP-task-specific progress data on an agent identified by its
     * agent ID (NOT its tool call ID — see why below). Absent fields on
     * `update` are left untouched.
     *
     * Looking up by agent ID rather than tool call ID matters because MCP
     * tasks are registered with a synthetic tool call ID that the consumer
     * doesn't generally know. The agent ID, by contrast, is returned from
     * `startAgent` and threaded through the stream consumer directly.
     *
     * Side effect: when `update.statusMessage` is provided as a string we also
     * mirror it into `progress.latestIntent` so existing TUI surfaces (which
     * consume the generic intent line) light up without needing MCP-specific
     * awareness. A `null` status message explicitly clears both the stored
     * MCP-task message and `progress.latestIntent`.
     *
     * A `null` `ttlMs` likewise clears the stored TTL, so a caller holding a
     * full task snapshot can retract a TTL the server no longer advertises
     * rather than leaving the previous value on display.
     */
    updateMcpTask(agentId: string, update: Omit<Partial<McpTaskInfo>, "statusMessage" | "ttlMs"> & {
        statusMessage?: string | null;
        ttlMs?: number | null;
    }): void;
    /** Increments the completed tool call count for an agent identified by its parent tool call ID. */
    incrementAgentToolCalls(toolCallId: string): void;
    /** Sets the resolved model name for an agent identified by its parent tool call ID. */
    setAgentModel(toolCallId: string, model: string): void;
    /** Accumulates token usage for an agent identified by its parent tool call ID. */
    addAgentTokens(toolCallId: string, inputTokens: number, outputTokens: number): void;
    /** Returns the progress info for an agent identified by its parent tool call ID, or undefined if not found. */
    getAgentProgress(toolCallId: string): AgentProgressInfo | undefined;
    /** Returns the activeTimeMs for an agent identified by its parent tool call ID, or undefined if not found. */
    getAgentActiveTime(toolCallId: string): number | undefined;
    beginAgentBlockingRead(agentId: string): boolean;
    endAgentBlockingRead(agentId: string): boolean;
    setAgentLastReadTurnIndex(agentId: string, turnIndex: number): void;
    setServiceLastReadLogIndex(serviceId: string, logIndex: number): void;
    updateShellTask(shellId: string, update: Partial<ShellTaskFields> & {
        status?: TaskStatus;
        description?: string;
        startedAt?: number;
        completedAt?: number;
        activeTimeMs?: number;
        activeStartedAt?: number;
        idleSince?: number;
    }, notify?: boolean): boolean;
    /**
     * Sets executor-provided telemetry on an agent's progress info.
     * Looked up by agent ID (not toolCallId).
     */
    setExecutorTelemetry(agentId: string, telemetry: AgentProgressInfo["executorTelemetry"]): void;
    private updateAgentProgress;
    private releaseAgentLimiterSlot;
    /** Resolve all waitForAgents() waiters blocked on a given task. */
    private resolveStatusWaiters;
    private dequeueAgentMessage;
    private cancelTaskFromPlan;
    private notifyFactoryLifecycle;
    /**
     * Fire the completion callback, swallowing errors to avoid breaking callers.
     */
    private notifyCompletion;
    /**
     * Fire the idle callback when a multi-turn agent enters idle state,
     * swallowing errors to avoid breaking callers.
     */
    private notifyAgentIdle;
    /**
     * Remove a specific turn waiter from the waiter list to prevent leaks on timeout.
     */
    private removeTurnWaiter;
    /**
     * Remove a specific promotion waiter from the waiter list to prevent leaks on timeout.
     */
    private removePromotionWaiter;
}

/** Identifier of the background task to cancel. */
declare interface TasksCancelRequest {
    /** Task identifier */
    id: string;
}

/** Indicates whether the background task was successfully cancelled. */
declare interface TasksCancelResult {
    /** Whether the task was successfully cancelled */
    cancelled: boolean;
}

/** The first sync-waiting task that can currently be promoted to background mode. */
declare interface TasksGetCurrentPromotableResult {
    /** The first sync-waiting task (agent first, then shell) that can currently be promoted to background mode. Omitted if no such task exists. The returned task is guaranteed to have executionMode='sync' and canPromoteToBackground=true at the time of the call. */
    task?: TaskInfo;
}

/** Identifier of the background task to fetch progress for. */
declare interface TasksGetProgressRequest {
    /** Task identifier (agent ID or shell ID) */
    id: string;
}

/** Progress information for the task, or null when no task with that ID is tracked. */
declare interface TasksGetProgressResult {
    /** Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. */
    progress: TaskProgress;
}

/** Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. */
declare interface TaskShellInfo {
    /** Whether the shell runs inside a managed PTY session or as an independent background process */
    attachmentMode: TaskShellInfoAttachmentMode;
    /** Whether this shell task can be promoted to background mode */
    canPromoteToBackground?: boolean;
    /** Command being executed */
    command: string;
    /** ISO 8601 timestamp when the task finished */
    completedAt?: string;
    /** Short description of the task */
    description: string;
    /** Whether task execution is synchronously awaited or managed in the background */
    executionMode?: TaskExecutionMode;
    /** Unique task identifier */
    id: string;
    /** Path to the detached shell log, when available */
    logPath?: string;
    /** Process ID when available */
    pid?: number;
    /** ISO 8601 timestamp when the task was started */
    startedAt: string;
    /** Current lifecycle status of the task */
    status: TaskStatus_2;
    /** Task kind */
    type: "shell";
}

/** Whether the shell runs inside a managed PTY session or as an independent background process */
declare type TaskShellInfoAttachmentMode = "attached" | "detached";

/** Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. */
declare interface TaskShellProgress {
    /** Process ID when available */
    pid?: number;
    /** Recent stdout/stderr lines from the running shell command */
    recentOutput: string;
    /** Progress kind */
    type: "shell";
}

/** The promoted task as it now exists in background mode, omitted if no promotable task was waiting. */
declare interface TasksPromoteCurrentToBackgroundResult {
    /** The promoted task as it now exists in background mode, omitted if no promotable task was waiting. Atomic operation: avoids the race window of getCurrentPromotable + promoteToBackground. */
    task?: TaskInfo;
}

/** Identifier of the task to promote to background mode. */
declare interface TasksPromoteToBackgroundRequest {
    /** Task identifier */
    id: string;
}

/** Indicates whether the task was successfully promoted to background mode. */
declare interface TasksPromoteToBackgroundResult {
    /** Whether the task was successfully promoted to background mode */
    promoted: boolean;
}

/** Refresh metadata for any detached background shells the runtime knows about. Use after a long pause to pick up exit/output state for shells running outside the agent loop. */
declare interface TasksRefreshResult {
}

/** Identifier of the completed or cancelled task to remove from tracking. */
declare interface TasksRemoveRequest {
    /** Task identifier */
    id: string;
}

/** Indicates whether the task was removed. False when the task does not exist or is still running/idle. */
declare interface TasksRemoveResult {
    /** Whether the task was removed. Returns false if the task does not exist or is still running/idle (cancel it first). */
    removed: boolean;
}

/** Identifier of the target agent task, message content, and optional sender agent ID. */
declare interface TasksSendMessageRequest {
    /** Agent ID of the sender, if sent on behalf of another agent */
    fromAgentId?: string;
    /** Agent task identifier */
    id: string;
    /** Message content to send to the agent */
    message: string;
}

/** Indicates whether the message was delivered, with an error message when delivery failed. */
declare interface TasksSendMessageResult {
    /** Error message if delivery failed */
    error?: string;
    /** Whether the message was successfully delivered or steered */
    sent: boolean;
}

/** Agent type, prompt, name, and optional description and model override for the new task. */
declare interface TasksStartAgentRequest {
    /** Type of agent to start (e.g., 'explore', 'task', 'general-purpose') */
    agentType: string;
    /** Short description of the task */
    description?: string;
    /** Optional model override */
    model?: string;
    /** Short name for the agent, used to generate a human-readable ID */
    name: string;
    /** Task prompt for the agent */
    prompt: string;
}

/** Identifier assigned to the newly started background agent task. */
declare interface TasksStartAgentResult {
    /** Generated agent ID for the background task */
    agentId: string;
}

/**
 * Lifecycle status for a tracked task.
 */
declare type TaskStatus = "running" | "idle" | "completed" | "failed" | "cancelled";

/** Current lifecycle status of the task */
declare type TaskStatus_2 = "running" | "idle" | "completed" | "failed" | "cancelled";

/** Wait until all in-flight background tasks (agents + shells) and any follow-up turns scheduled by their completions have settled. Returns when the runtime is fully drained or after an internal timeout (default 10 minutes; configurable via COPILOT_TASK_WAIT_TIMEOUT_SECONDS). */
declare interface TasksWaitForPendingResult {
}

/**
 * Task type discriminator.
 */
declare type TaskType = "agent" | "shell" | "service";

/**
 * Telemetry emitted by the runtime contains properties and metrics. These are non-sensitive pieces
 * of information. There are also restricted properties that must be used to store sensitive information.
 */
declare type Telemetry = {
    /**
     * Telemetry properties can be used to store string props.
     * WARNING: Do not put sensitive data here. Use restrictedProperties for that.
     */
    properties: Record<string, string | undefined>;
    /**
     * Restricted telemetry properties must be used to store sensitive string props. These props will only be available on the restricted kusto topics.
     * Nonnullable so it is harder to overlook.
     */
    restrictedProperties: Record<string, string | undefined>;
    /**
     * The name of the telemetry event associated with the emitted runtime event.
     */
    metrics: Record<string, number | undefined>;
};

/** A normalized ExP assignment snapshot attached to one telemetry event. */
export declare interface TelemetryAssignmentContext {
    readonly [telemetryAssignmentContextBrand]: true;
    /** The primary assignment context returned by TAS. */
    readonly primary: string;
    /** The assignment context returned by the model request, when present. */
    readonly secondary?: string;
}

declare const telemetryAssignmentContextBrand: unique symbol;

declare type TelemetryEmitter = (event: TelemetryEvent) => void;

/**
 * Alternatively telemetry can be emitted by an event which just contains telemetry. This is that type.
 *
 * You can use this type with our without generics. The generics help you to enforce what properties/metrics are on your event
 * more precisely and safely.
 */
declare type TelemetryEvent<EventT = string, TelemetryT extends Telemetry = Telemetry> = {
    kind: "telemetry";
    telemetry: EventTelemetry<EventT, TelemetryT>;
};

declare interface TelemetryEvent_2 {
    /** Event type/kind (e.g., "session_shutdown", "tool_call_executed") */
    kind: string;
    /** Non-restricted properties (key-value pairs) */
    properties?: Record<string, string | undefined>;
    /** Restricted properties (may contain sensitive data like PII, file paths, ...)  */
    restrictedProperties?: Record<string, string | undefined>;
    /** Numeric metrics */
    metrics?: Record<string, number | undefined>;
    /** Reference to the model call that produced this event */
    modelCallId?: string;
    /** Forward only to opted-in hosts without a generic CLI Hydro write. */
    forwardToHostOnly?: boolean;
    /**
     * When true, sending this event is deferred until the ExP (Experimentation
     * Platform) response has been received, so the event is enriched with
     * experiment assignment context and flags.
     */
    awaitExpBeforeSend?: boolean;
}

declare type TelemetryMeasurements = {
    [key: string]: number | undefined;
};

declare type TelemetryProperties = {
    [key: string]: string | undefined;
};

declare interface TelemetrySender {
    sendTelemetry(event: TelemetryEvent_2): void;
}

/**
 * Host-boundary telemetry service delegating to the native, Rust-owned telemetry
 * router.
 *
 * All telemetry logic — envelope shaping, bag fan-out, the restricted-telemetry
 * gates, host forwarding, and the auth-driven destination lifecycle — lives in
 * Rust (`crate::github_telemetry::{router,service}`). This class is a thin shim
 * that owns the {@link routerHandle} and relays host-owned data across the N-API
 * boundary: it relays the process credential whenever it is constructed with an
 * auth manager, and auth-driven subclasses (e.g.
 * {@link AppInsightsTelemetryService}) additionally relay the destination's auth
 * notifications. A bare instance is a forward-only telemetry service that writes
 * no generic CLI tables.
 */
declare class TelemetryService {
    readonly authManager?: AuthManager | undefined;
    /**
     * The native telemetry router. Owns the App Insights / Hydro destination
     * (when configured), the host forwarding sink, and the opted-in-connection
     * count. Exposed so the SDK server can register forwarding and per-session
     * pipelines can resolve their destination by {@link routerId}.
     */
    readonly routerHandle: InstanceType<typeof nativeRuntime.TelemetryRouterHandle>;
    /** Whether a {@link relayProcessCredential} lookup has yet to report back. */
    private processCredentialRelayInFlight;
    /**
     * @param authManager - Optional auth manager, relayed by auth-driven subclasses.
     * @param appInsightsConfigJson - When present, the router builds the App
     * Insights / Hydro destination from these static host snapshot inputs.
     */
    constructor(authManager?: AuthManager | undefined, appInsightsConfigJson?: string);
    /**
     * Pull the process credential and hand it to the router, which stamps it
     * onto the lifecycle `copilot_user_info` event.
     *
     * Pre-port that event read `authManager.getCurrentAuthInfo()` at emission
     * time -- only at `session.start` / `session.resume` -- and fired for
     * forward-only services too because the SDK server's default service wrapped
     * a no-op destination but still carried the auth manager. Keeping the same
     * lazy pull (rather than subscribing to auth changes or reading eagerly at
     * construction) preserves that, and asks nothing of the auth manager the
     * pre-port service did not already use. Each pull is announced to the router
     * first and reports back under that lookup's token, so a lifecycle event
     * defers to the lookup its own emission point started rather than answering
     * from an earlier -- possibly slower -- one, matching the pre-port
     * per-emission await.
     *
     * Concurrent sessions can reach this while a lookup is still in flight; that
     * lookup is reused rather than starting a second `getCurrentAuthInfo()`, and
     * the later emission still defers to it and receives its result.
     */
    relayProcessCredential(): void;
    /** The router id per-session pipelines use to resolve this destination. */
    get routerId(): number;
    sendTelemetryEvent(eventName: string, properties?: TelemetryProperties, measurements?: TelemetryMeasurements, tags?: TelemetryTags): void;
    /** Whether restricted telemetry should be sent for eligible users who have not opted out. */
    shouldSendRestrictedTelemetry(): boolean;
    /**
     * Override the host-editor attribution (`common_extname`, `common_extversion`,
     * and `editor_version`). These land in the App Insights host snapshot's common
     * properties, so they are stamped on every classic event — not only legacy
     * `copilot_v0` usage events, but also operational ones such as
     * `error.exception` and `telemetry.pending_buffer_overflow`.
     *
     * `commonExtVersion` is optional, but it does not fall back to the CLI package
     * version once `commonExtName` names a non-CLI host: omitting it then emits
     * `common_extversion` as an empty string rather than mislabeling the event
     * with the CLI's version. Pass the host's own version to avoid that.
     *
     * Pass `undefined` to clear the override and fall back to the default CLI
     * attribution.
     */
    setUsageMetricsAttribution(attribution: UsageMetricsAttribution | undefined): void;
    /**
     * Send a TelemetryEvent as hydro bag events, routing unrestricted properties to
     * cli.telemetry and restricted properties to cli.restricted_telemetry through
     * the native router (which owns the restricted / host-only gating and the
     * host forwarding fan-out).
     *
     * @param event - The telemetry event with properties/restrictedProperties/metrics
     * @param hydroFields - Optional extra fields merged into the hydro event envelope (e.g. session_id, features)
     * @param options - Optional client name, assignment context, and restricted telemetry gate for routing
     */
    sendBagTelemetryEvent(event: TelemetryEvent_2, hydroFields?: {
        session_id?: string;
        features?: Record<string, string>;
    }, options?: HydroTelemetryOptions): void;
    /**
     * Tear down the telemetry destination, flushing buffered/in-flight events.
     * Host forwarding sinks are intentionally left registered — the SDK server
     * owns their lifetime and drops each one when its connection closes — so
     * telemetry emitted while shutdown disposes this service in parallel with
     * `SDKServer.stop()` (notably each session's final `session.shutdown`)
     * still reaches opted-in hosts.
     */
    dispose(): Promise<void> | void;
}

/** Feature override key/value pairs to attach to subsequent telemetry events from this session. */
declare interface TelemetrySetFeatureOverridesRequest {
    /** Override key/value pairs to attach to subsequent telemetry events from this session. Replaces any previously-set overrides. */
    features: Record<string, string>;
}

declare type TelemetryTags = {
    [key: string]: string;
};

declare interface TextContent_2 extends BaseContentBlock {
    type: "text";
    text: string;
}

declare interface TextResourceContents {
    uri: string;
    mimeType?: string;
    _meta?: Record<string, unknown>;
    text: string;
}

/** Tiered token pricing (API >= 2026-06-01). */
declare type TieredTokenPrices = {
    batch_size?: number;
    default: TokenPriceTier;
    long_context?: TokenPriceTier;
};

/** Session title change payload containing the new display title */
export declare interface TitleChangedData {
    /** The new display title for the session */
    title: string;
}

/** Session event "session.title_changed". Session title change payload containing the new display title */
declare interface TitleChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Session title change payload containing the new display title */
    data: TitleChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.title_changed". */
    type: "session.title_changed";
}
export { TitleChangedEvent as SessionTitleChangedEvent }
export { TitleChangedEvent }

/** Signal-only event: the agent's todos or todo_deps table was written to. No payload — clients should call session.plan.readSqlTodosWithDependencies() to fetch the current state. Events arrive in order; clients can debounce on arrival if needed. */
export declare interface TodosChangedData {
}

/** Session event "session.todos_changed". Signal-only event: the agent's todos or todo_deps table was written to. No payload — clients should call session.plan.readSqlTodosWithDependencies() to fetch the current state. Events arrive in order; clients can debounce on arrival if needed. */
declare interface TodosChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Signal-only event: the agent's todos or todo_deps table was written to. No payload — clients should call session.plan.readSqlTodosWithDependencies() to fetch the current state. Events arrive in order; clients can debounce on arrival if needed. */
    data: TodosChangedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.todos_changed". */
    type: "session.todos_changed";
}
export { TodosChangedEvent as SessionTodosChangedEvent }
export { TodosChangedEvent }

/** Represents a Token authentication information using in the SDK. */
declare type TokenAuthInfo = {
    readonly type: "token";
    readonly host: string;
    readonly token: string;
    readonly copilotUser?: CopilotUserResponse;
};

/** Authentication-info variant for SDK-configured token authentication, carrying host and the secret token value. */
declare interface TokenAuthInfo_2 {
    /** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
    copilotUser?: CopilotUserResponse;
    /** Authentication host. */
    host: string;
    /** The token value itself. Treat as a secret. */
    token: string;
    /** SDK-side token authentication; the host configured the token directly via the SDK. */
    type: "token";
}

/** A single pricing tier (API >= 2026-06-01). */
declare type TokenPriceTier = {
    input_price?: number;
    output_price?: number;
    cache_read_price?: number;
    cache_write_price?: number;
    max_prompt_tokens?: number;
};

declare type Tool<CallbackT extends ToolCallback = ToolCallback> = ToolMetadata & {
    callback: CallbackT;
    summariseIntention?: (input: unknown) => string;
    shutdown?: ToolShutdown;
};

/** Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. */
declare interface Tool_2 {
    /** Description of what the tool does */
    description: string;
    /** Optional instructions for how to use this tool effectively */
    instructions?: string;
    /** Tool identifier (e.g., "bash", "grep", "str_replace_editor") */
    name: string;
    /** Optional namespaced name for declarative filtering (e.g., "playwright/navigate" for MCP tools) */
    namespacedName?: string;
    /** JSON Schema for the tool's input parameters */
    parameters?: Record<string, unknown>;
}

declare type ToolCallback = (input: unknown, options?: ToolCallbackOptions) => Promise<ToolResult>;

/**
 * The callback boundary is intentionally TypeScript-owned: clients, abort
 * signals, and per-call host services cannot cross the native registry.
 */
declare type ToolCallbackOptions<OptionsT = Record<string, unknown>> = {
    toolCallId: string;
    truncationOptions?: {
        tokenLimit: number;
        countTokens: (input: string) => number;
    };
    settings: RuntimeSettings;
    client?: Client;
    toolOptions?: OptionsT;
    abortSignal?: AbortSignal;
    registerSteeringInterrupt?: (interrupt: () => void) => () => void;
    largeOutputOptions?: LargeOutputOptions;
    repoChangeSet?: RepoChangeSet;
    multiTurnConfig?: {
        registry: TaskRegistry;
        agentId: string;
        onTurnStart?: (message: AgentMessage) => void | Promise<void>;
        formatContinuationPrompt?: (message: AgentMessage) => string;
    };
    taskRegistryAgentId?: string;
    /** Agent ID exposed to subagent lifecycle hooks. */
    subagentHookAgentId?: string;
    factoryUsageRunId?: string;
    factoryUsageCoordinator?: FactoryUsageCoordinator;
    rawArgumentsJson?: string;
};

declare interface ToolChoice {
    mode?: "required" | "auto" | "none";
}

declare type ToolConfig = NativeToolConfig & ToolHostCallbacks & {
    permissions: PermissionsConfig;
    shellConfig?: ShellConfig;
    sandboxConfig?: SandboxConfig_2;
    /**
     * The current session's log paths, resolved from trusted session/settings
     * context: the per-session `events.jsonl` file itself (not its whole
     * `session-state/<id>` folder, to stay least-privilege) and the shared
     * `.copilot/logs` process-log dir (where `process-*.log` lives). Granted
     * read-only under the sandbox so this session's own logs can be copied for
     * Feedback Hub collection. Kept independent of shell-log enablement (see
     * issue #13274 review).
     */
    sessionLogPaths?: string[];
    /**
     * Native session id owning the session-scoped native services a tool may
     * reach (today the inbox store). Distinct from `sessionId` for subagent
     * sessions, which run under their own native session.
     */
    nativeSessionId?: string;
};

declare interface ToolDescriptor {
    name: string;
    title?: string;
    description?: string;
    inputSchema?: unknown;
    outputSchema?: unknown;
    annotations?: Record<string, unknown>;
    execution?: Record<string, unknown>;
    _meta?: Record<string, unknown>;
    [key: string]: unknown;
}

/** A content block within a tool result, which may be text, terminal output, image, audio, or a resource */
declare type ToolExecutionCompleteContent = ToolExecutionCompleteContentText | ToolExecutionCompleteContentTerminal | ToolExecutionCompleteContentShellExit | ToolExecutionCompleteContentImage | ToolExecutionCompleteContentAudio | ToolExecutionCompleteContentResourceLink | ToolExecutionCompleteContentResource;
export { ToolExecutionCompleteContent as ContentBlock }
export { ToolExecutionCompleteContent }

/** Audio content block with base64-encoded data */
declare interface ToolExecutionCompleteContentAudio {
    /** Base64-encoded audio data */
    data: string;
    /** MIME type of the audio (e.g., audio/wav, audio/mpeg) */
    mimeType: string;
    /** Content block type discriminator */
    type: "audio";
}
export { ToolExecutionCompleteContentAudio as AudioContent }
export { ToolExecutionCompleteContentAudio }

/** Image content block with base64-encoded data */
declare interface ToolExecutionCompleteContentImage {
    /** Base64-encoded image data */
    data: string;
    /** MIME type of the image (e.g., image/png, image/jpeg) */
    mimeType: string;
    /** Content block type discriminator */
    type: "image";
}
export { ToolExecutionCompleteContentImage as ImageContent }
export { ToolExecutionCompleteContentImage }

/** Embedded resource content block with inline text or binary data */
declare interface ToolExecutionCompleteContentResource {
    /** The embedded resource contents, either text or base64-encoded binary */
    resource: ToolExecutionCompleteContentResourceDetails;
    /** Content block type discriminator */
    type: "resource";
}
export { ToolExecutionCompleteContentResource as EmbeddedResource }
export { ToolExecutionCompleteContentResource }

/** The embedded resource contents, either text or base64-encoded binary */
export declare type ToolExecutionCompleteContentResourceDetails = EmbeddedTextResourceContents | EmbeddedBlobResourceContents;

/** Resource link content block referencing an external resource */
declare interface ToolExecutionCompleteContentResourceLink {
    /** Human-readable description of the resource */
    description?: string;
    /** Icons associated with this resource */
    icons?: ToolExecutionCompleteContentResourceLinkIcon[];
    /** MIME type of the resource content */
    mimeType?: string;
    /** Resource name identifier */
    name: string;
    /** Size of the resource in bytes */
    size?: number;
    /** Human-readable display title for the resource */
    title?: string;
    /** Content block type discriminator */
    type: "resource_link";
    /** URI identifying the resource */
    uri: string;
}
export { ToolExecutionCompleteContentResourceLink as ResourceLink }
export { ToolExecutionCompleteContentResourceLink }

/** Icon image for a resource */
export declare interface ToolExecutionCompleteContentResourceLinkIcon {
    /** MIME type of the icon image */
    mimeType?: string;
    /** Available icon sizes (e.g., ['16x16', '32x32']) */
    sizes?: string[];
    /** URL or path to the icon image */
    src: string;
    /** Theme variant this icon is intended for */
    theme?: ToolExecutionCompleteContentResourceLinkIconTheme;
}

/** Theme variant this icon is intended for */
export declare type ToolExecutionCompleteContentResourceLinkIconTheme = "light" | "dark";

/** Shell command exit metadata with optional output preview */
declare interface ToolExecutionCompleteContentShellExit {
    /** Working directory where the shell command was executed */
    cwd?: string;
    /** Exit code from the completed shell command */
    exitCode: number;
    /** Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. */
    outputPreview?: string;
    /** Whether outputPreview is known to be incomplete or truncated */
    outputTruncated?: boolean;
    /** Shell id, as assigned by Copilot runtime */
    shellId: string;
    /** Content block type discriminator */
    type: "shell_exit";
}
export { ToolExecutionCompleteContentShellExit as ShellExitContent }
export { ToolExecutionCompleteContentShellExit }

/**
 * Deprecated for shell command exit metadata. Use ToolExecutionCompleteContentShellExit instead.
 * @deprecated
 */
declare interface ToolExecutionCompleteContentTerminal {
    /** Working directory where the command was executed */
    cwd?: string;
    /** Process exit code, if the command has completed */
    exitCode?: number;
    /** Terminal/shell output text */
    text: string;
    /** Content block type discriminator */
    type: "terminal";
}
export { ToolExecutionCompleteContentTerminal as TerminalContent }
export { ToolExecutionCompleteContentTerminal }

/** Plain text content block */
declare interface ToolExecutionCompleteContentText {
    /** The text content */
    text: string;
    /** Content block type discriminator */
    type: "text";
}
export { ToolExecutionCompleteContentText as TextContent }
export { ToolExecutionCompleteContentText }

/** Tool execution completion results including success status, detailed output, and error information */
export declare interface ToolExecutionCompleteData {
    /** Error details when the tool execution failed */
    error?: ToolExecutionCompleteError;
    /** CAPI interaction ID for correlating this tool execution with upstream telemetry */
    interactionId?: string;
    /** Whether this tool call was explicitly requested by the user rather than the assistant */
    isUserRequested?: boolean;
    /** FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels). Persisted as `{ ifc: ... }` so the label survives session resume, including model-visible failure results. Experimental. */
    mcpMeta?: unknown;
    /** Model identifier that generated this tool call */
    model?: string;
    /**
     * Tool call ID of the parent tool invocation when this event originates from a sub-agent
     * @deprecated
     */
    parentToolCallId?: string;
    /** Tool execution result on success */
    result?: ToolExecutionCompleteResult;
    rte?: boolean;
    /** Whether this tool execution ran inside a sandbox container */
    sandboxed?: boolean;
    /** Whether the tool execution completed successfully */
    success: boolean;
    /** Unique identifier for the completed tool call */
    toolCallId: string;
    /** Tool definition metadata, present for MCP tools with MCP Apps support */
    toolDescription?: ToolExecutionCompleteToolDescription;
    /** Tool-specific telemetry data (e.g., CodeQL check counts, grep match counts) */
    toolTelemetry?: Record<string, unknown>;
    /** Identifier for the agent loop turn this tool was invoked in, matching the corresponding assistant.turn_start event */
    turnId?: string;
}

/** Error details when the tool execution failed */
export declare interface ToolExecutionCompleteError {
    /** Machine-readable error code */
    code?: string;
    /** Human-readable error message */
    message: string;
}

/** Session event "tool.execution_complete". Tool execution completion results including success status, detailed output, and error information */
export declare interface ToolExecutionCompleteEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Tool execution completion results including success status, detailed output, and error information */
    data: ToolExecutionCompleteData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "tool.execution_complete". */
    type: "tool.execution_complete";
}

/** Tool execution result on success */
export declare interface ToolExecutionCompleteResult {
    /** Model-facing binary results (base64 inline or size-omitted markers) sent to the LLM for this tool call */
    binaryResultsForLlm?: PersistedBinaryResult[];
    /** Provider-neutral source material this tool makes available to the model as citable content. Persisted so it survives session resume. Experimental. */
    citableSources?: CitableSource[];
    /** Concise tool result text sent to the LLM for chat completion, potentially truncated for token efficiency */
    content: string;
    /** Structured content blocks (text, images, audio, resources) returned by the tool in their native format */
    contents?: ToolExecutionCompleteContent[];
    /** Full detailed tool result for UI/timeline display, preserving complete content such as diffs. Falls back to content when absent. */
    detailedContent?: string;
    /** FIDES IFC label projected from tool ingress metadata (MCP `CallToolResult._meta` or synthesized built-in ingress labels) — persisted as `{ ifc: ... }` (only the `ifc` key, not the whole `_meta`). Persisted so the FIDES IFC label survives session resume: the engine rehydrates accumulated taint by replaying these on load. Populated for ingress sources when FIDES IFC is on. Experimental. */
    mcpMeta?: unknown;
    /** Structured content (arbitrary JSON) returned verbatim by the MCP tool */
    structuredContent?: unknown;
    /** MCP Apps UI resource content for rendering in a sandboxed iframe */
    uiResource?: ToolExecutionCompleteUIResource;
}

/** Tool definition metadata, present for MCP tools with MCP Apps support */
export declare interface ToolExecutionCompleteToolDescription {
    /** MCP Apps metadata for UI resource association */
    _meta?: ToolExecutionCompleteToolDescriptionMeta;
    /** Tool description */
    description?: string;
    /** Tool name */
    name: string;
}

/** MCP Apps metadata for UI resource association */
export declare interface ToolExecutionCompleteToolDescriptionMeta {
    /** MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. */
    ui?: ToolExecutionCompleteToolDescriptionMetaUI;
}

/** MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_complete`. */
export declare interface ToolExecutionCompleteToolDescriptionMetaUI {
    /** URI of the UI resource */
    resourceUri?: string;
    /** Who can access this tool */
    visibility?: ToolExecutionCompleteToolDescriptionMetaUIVisibility[];
}

/** Allowed values for the `ToolExecutionCompleteToolDescriptionMetaUIVisibility` enumeration. */
export declare type ToolExecutionCompleteToolDescriptionMetaUIVisibility = "model" | "app";

/** MCP Apps UI resource content for rendering in a sandboxed iframe */
export declare interface ToolExecutionCompleteUIResource {
    /** Resource-level UI metadata (CSP, permissions, visual preferences) */
    _meta?: ToolExecutionCompleteUIResourceMeta;
    /** Base64-encoded HTML content */
    blob?: string;
    /** MIME type of the content */
    mimeType: string;
    /** HTML content as a string */
    text?: string;
    /** The ui:// URI of the resource */
    uri: string;
}

/** Resource-level UI metadata (CSP, permissions, visual preferences) */
export declare interface ToolExecutionCompleteUIResourceMeta {
    /** MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. */
    ui?: ToolExecutionCompleteUIResourceMetaUI;
}

/** MCP Apps UI resource metadata for a completed tool result, including CSP, permissions, domain, and border preference. */
export declare interface ToolExecutionCompleteUIResourceMetaUI {
    /** CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. */
    csp?: ToolExecutionCompleteUIResourceMetaUICsp;
    domain?: string;
    /** Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. */
    permissions?: ToolExecutionCompleteUIResourceMetaUIPermissions;
    prefersBorder?: boolean;
}

/** CSP domain allowlists for an MCP Apps UI resource, including connect, resource, frame, and base URI domains. */
export declare interface ToolExecutionCompleteUIResourceMetaUICsp {
    baseUriDomains?: string[];
    connectDomains?: string[];
    frameDomains?: string[];
    resourceDomains?: string[];
}

/** Browser permission metadata for an MCP Apps UI resource, including camera, microphone, geolocation, and clipboard-write. */
export declare interface ToolExecutionCompleteUIResourceMetaUIPermissions {
    /** Marker object for camera permission on an MCP Apps UI resource. */
    camera?: ToolExecutionCompleteUIResourceMetaUIPermissionsCamera;
    /** Marker object for clipboard-write permission on an MCP Apps UI resource. */
    clipboardWrite?: ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite;
    /** Marker object for geolocation permission on an MCP Apps UI resource. */
    geolocation?: ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation;
    /** Marker object for microphone permission on an MCP Apps UI resource. */
    microphone?: ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone;
}

/** Marker object for camera permission on an MCP Apps UI resource. */
export declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsCamera {
    [key: string]: unknown;
}

/** Marker object for clipboard-write permission on an MCP Apps UI resource. */
export declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite {
    [key: string]: unknown;
}

/** Marker object for geolocation permission on an MCP Apps UI resource. */
export declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation {
    [key: string]: unknown;
}

/** Marker object for microphone permission on an MCP Apps UI resource. */
export declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone {
    [key: string]: unknown;
}

declare type ToolExecutionEvent = {
    kind: "tool_execution";
    turn: number;
    callId?: string;
    toolCallId: string;
    toolResult: ToolResultExpanded;
    durationMs: number;
    rte?: boolean;
};

/** Streaming tool execution output for incremental result display */
export declare interface ToolExecutionPartialData {
    /** Incremental output chunk from the running tool */
    partialOutput: string;
    /** Tool call ID this partial result belongs to */
    toolCallId: string;
}

/** Session event "tool.execution_partial_result". Streaming tool execution output for incremental result display */
export declare interface ToolExecutionPartialResultEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Streaming tool execution output for incremental result display */
    data: ToolExecutionPartialData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "tool.execution_partial_result". */
    type: "tool.execution_partial_result";
}

/** Tool execution progress notification with status message */
export declare interface ToolExecutionProgressData {
    /** Human-readable progress status message (e.g., from an MCP server) */
    progressMessage: string;
    /** Tool call ID this progress notification belongs to */
    toolCallId: string;
}

/** Session event "tool.execution_progress". Tool execution progress notification with status message */
export declare interface ToolExecutionProgressEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Tool execution progress notification with status message */
    data: ToolExecutionProgressData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "tool.execution_progress". */
    type: "tool.execution_progress";
}

/** Tool execution startup details including MCP server information when applicable */
export declare interface ToolExecutionStartData {
    /** Arguments passed to the tool */
    arguments?: unknown;
    /** When true, the tool output should be displayed expanded (verbatim) in the CLI timeline */
    displayVerbatim?: boolean;
    /** Name of the MCP server hosting this tool, when the tool is an MCP tool */
    mcpServerName?: string;
    /** Original tool name on the MCP server, when the tool is an MCP tool */
    mcpToolName?: string;
    /** Model identifier that generated this tool call */
    model?: string;
    /**
     * Tool call ID of the parent tool invocation when this event originates from a sub-agent
     * @deprecated
     */
    parentToolCallId?: string;
    rte?: boolean;
    /** Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. */
    shellToolInfo?: ToolExecutionStartShellToolInfo;
    /** Unique identifier for this tool call */
    toolCallId: string;
    /** Tool definition metadata, present for MCP tools with MCP Apps support */
    toolDescription?: ToolExecutionStartToolDescription;
    /** Name of the tool being executed */
    toolName: string;
    /** Identifier for the agent loop turn this tool was invoked in, matching the corresponding assistant.turn_start event */
    turnId?: string;
}

/** Session event "tool.execution_start". Tool execution startup details including MCP server information when applicable */
export declare interface ToolExecutionStartEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Tool execution startup details including MCP server information when applicable */
    data: ToolExecutionStartData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "tool.execution_start". */
    type: "tool.execution_start";
}

/** Shell-aware path hints for a shell tool's command, captured at start time so consumers can snapshot a file's pre-image before the tool runs. */
export declare interface ToolExecutionStartShellToolInfo {
    /** The command with a redundant leading `cd` into the working directory removed, present only when there was one to remove. Computed with the same routine the shell driver applies before spawning, so a surface that renders this shows the text that actually runs. Consumers that display it should keep the original tool arguments available on demand. */
    displayCommand?: string;
    /** Whether the command includes a file write redirection (e.g., > or >>). */
    hasWriteFileRedirection: boolean;
    /** File paths the command may read or write, derived from the command at start time. Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. */
    possiblePaths: string[];
}

/** Tool definition metadata, present for MCP tools with MCP Apps support */
export declare interface ToolExecutionStartToolDescription {
    /** MCP Apps metadata for UI resource association */
    _meta?: ToolExecutionStartToolDescriptionMeta;
    /** Tool description */
    description?: string;
    /** Tool name */
    name: string;
}

/** MCP Apps metadata for UI resource association */
export declare interface ToolExecutionStartToolDescriptionMeta {
    /** MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. */
    ui?: ToolExecutionStartToolDescriptionMetaUI;
}

/** MCP Apps tool `_meta.ui` resource URI and visibility captured on `tool.execution_start`. */
export declare interface ToolExecutionStartToolDescriptionMetaUI {
    /** URI of the UI resource */
    resourceUri?: string;
    /** Who can access this tool */
    visibility?: ToolExecutionStartToolDescriptionMetaUIVisibility[];
}

/** Allowed values for the `ToolExecutionStartToolDescriptionMetaUIVisibility` enumeration. */
export declare type ToolExecutionStartToolDescriptionMetaUIVisibility = "model" | "app";

/**
 * Controls how `availableTools` and `excludedTools` combine.
 */
declare type ToolFilterPrecedence = "available" | "excluded";

/**
 * Host-only configuration surface. Serializable settings are generated by
 * N-API; this compact overlay names live Node services so callers retain
 * optional-property and callback context semantics.
 */
declare type ToolHostCallbacks = {
    detachedFromSpawningParentSessionId?: string;
    callback?: IAgentCallback;
    callbackRuntime?: CallbackRuntimeSink;
    toolPartialResultCallback?: ToolPartialOutputCallback;
    toolProgressCallback?: ToolProgressCallback;
    createSubAgentCallback?: (agentId: string, options?: {
        isByokExecutor?: boolean;
    }) => IAgentCallback;
    providerConfig?: ProviderConfig;
    /**
     * CAPI request context for sub-agent telemetry header propagation.
     * Contains fields passed to sub-agent CAPI clients for correlation.
     */
    capiRequestContext?: {
        /** The parent agent's task ID (GUID), sent as X-Parent-Agent-Id. */
        parentAgentTaskId?: string;
        /** Stable identity of the immediate parent trajectory. */
        parentAgentId?: string;
        /** The current interaction ID (GUID), shared across parent and sub-agents for the same user message. */
        interactionId?: string;
    };
    availableModels?: AvailableModelInfo[];
    parentSessionModelPriceCategory?: AvailableModelInfo["priceCategory"];
    subagentOnlyModels?: AvailableModelInfo[];
    sessionModelSelectionId?: string;
    tokenBasedBilling?: boolean;
    /**
     * If the secret scanning tool should be included in security prompt snippets. Default is false.
     */
    includeSecretScanning?: boolean;
    largeOutputOptions?: LargeOutputOptions;
    canvasApi?: SessionCanvasApi;
    /** Name-based factory invocation for sessions with agent factories enabled. */
    factoryApi?: RunFactoryApi;
    /**
     * Session-scoped factory discovery, run observation, guidance, and
     * authoring. Authoring capability is carried by its optional `author`
     * member so a session that cannot author is one field, not two that can
     * disagree.
     */
    factoriesManageApi?: FactoriesManageApi;
    skillDirectories?: string[];
    embeddingRetrievalIndexTypes?: Set<InstructionSource_2>;
    disabledSkills?: Set<string>;
    disabledInstructionSources?: ReadonlySet<string>;
    installedPlugins?: InstalledPlugin[];
    cwd?: string;
    remoteSkills?: Skill_2[];
    loadedSkills?: readonly Skill_2[];
    includedBuiltinAgents?: readonly string[];
    /**
     * Returns the session-local authored prompt override for an effective agent id.
     */
    getAgentPromptOverride?: (agentId: string) => string | undefined;
    /**
     * Built-in subagents excluded by the session/integrator configuration.
     * Custom agents with the same name remain available, except for the reserved
     * `general-purpose` name.
     */
    excludedBuiltinAgents?: readonly string[];
    getBuiltinAgentPolicy?: () => {
        includedBuiltinAgents?: readonly string[];
        excludedBuiltinAgents?: readonly string[];
    };
    featureFlags?: FeatureFlags;
    cloudSessionStorageEnabled?: boolean;
    featureFlagService?: IFeatureFlagService;
    lspLanguages?: string[];
    contentExclusionService?: ContentExclusionServiceHandle;
    getContentExclusionService?: () => ContentExclusionServiceHandle | undefined;
    fileSnapshotCapture?: FileSnapshotCapture;
    hasSidekickAgents?: () => Promise<boolean>;
    sendInboxPublisher?: SendInboxPublisher;
    dynamicContext?: {
        store: SessionStore;
        repository: string;
        branch: string;
    };
    shellContextGeneration?: number;
    memoryApiCache?: MemoryApiCache;
    lspClientName?: string;
    agentContext?: AgentContext;
    subAgentDepth?: number;
    agentExecutors?: AgentExecutors;
    scheduleSessionId?: string;
    getLiveSandboxConfig?: () => SandboxConfig_2 | undefined;
    /** Returns the owning session's current shell configuration for new shell processes. */
    getLiveShellConfig?: () => ShellConfig | undefined;
    /** Returns the owning session's current initialization scripts at command launch. */
    getLiveInitScripts?: () => readonly ShellInitScript_2[] | undefined;
    getLiveWorkingDirectory?: () => string;
    /**
     * Resolves the Copilot GitHub.com token for sandbox-safe git/gh auth, read
     * lazily at shell-spawn time.
     *
     * When the OS sandbox is active with the `auth.git`/`auth.gh` options on, the
     * shell tool passes this token to the runtime, which injects it — scoped to
     * the specific command spawn — as an `http.extraheader` credential for `git`
     * commands and/or `GH_TOKEN` for `gh` commands. A *separately* spawned command
     * in the same sandboxed session never sees it (though commands chained inside
     * one compound script share that spawn's environment). An OAuth login
     * keeps its token in the CLI credential store rather than the environment, so
     * the Rust env builder cannot find it on its own — the host resolves it here.
     *
     * Only resolves a github.com-scoped token (never an enterprise token, which
     * must not be presented to github.com). Returns `undefined` when no such
     * token is available. Called only when a sandbox shell with git/gh auth is
     * spawned, so the async credential-store read stays off the common path.
     */
    getGitHubAuthToken?: () => Promise<string | undefined>;
    filterTool?: (tool: ToolMetadata) => boolean;
    onTodosChanged?: () => void;
    onMemoryChanged?: () => void;
    onFileCreated?: (path: string) => void;
    onWarning?: (message: string) => void;
    requestUserInput?: (request: {
        question: string;
        choices?: string[];
        allowFreeform?: boolean;
    }) => Promise<{
        answer: string;
        wasFreeform: boolean;
    }>;
    requestElicitation?: (request: ElicitRequestFormParams) => Promise<ElicitResult>;
    onSubagentStart?: (input: {
        sessionId: string;
        transcriptPath: string;
        agentName: string;
        agentDisplayName?: string;
        agentDescription?: string;
    }) => Promise<{
        additionalContext?: string;
    } | undefined | void>;
    /**
     * Callback for subagentStop hook. Called when a subagent is about to complete.
     * Returns a decision to block (continue) or allow the stop, and may rewrite the response.
     */
    onSubagentStop?: (input: {
        sessionId: string;
        transcriptPath: string;
        agentId: string;
        agentType: string;
        agentName: string;
        agentDisplayName?: string;
        response: string;
    }) => Promise<{
        decision?: "block" | "allow";
        reason?: string;
        modifiedResponse?: string;
    } | undefined | void>;
    /** Parent-session native hook facade forked for each legacy subagent execution. */
    nativeHookProcessor?: NativeHookProcessor;
    /**
     * Whether autopilot mode is currently active.
     * When true, the task_complete tool is included in the toolset.
     */
    autopilotActive?: boolean;
    /**
     * Evaluates a valid `task_complete` request before it is accepted, running
     * the independent autopilot completion reviewer. When omitted, the tool
     * retains its legacy unconditional completion behavior.
     */
    evaluateTaskCompletion?: (request: {
        summary: string;
        toolCallbackOptions?: ToolCallbackOptions;
    }) => Promise<TaskCompletionDecision | undefined>;
    /**
     * Whether plan mode is currently active.
     * When true (and {@link onExitPlanMode} is provided), the exit_plan_mode
     * tool is included in the toolset. Outside plan mode, the tool is hidden
     * regardless of whether a responder callback or event listener exists.
     */
    planModeActive?: boolean;
    /**
     * Callback invoked when the exit_plan_mode tool is called.
     * Shows an approval dialog with the agent's summary and returns the user's response.
     *
     * Note: presence of this callback indicates that a responder is available
     * (either a direct SDK callback or an event-listener bridge). It does not
     * by itself expose the tool — see {@link planModeActive}.
     */
    onExitPlanMode?: (request: ExitPlanModeRequest) => Promise<ExitPlanModeResponse>;
    skillInvocationEmitter?: (invocation: SkillInvocation, agentId?: string) => void;
    telemetryEmitter?: (event: TelemetryEvent) => void;
    /** Live gate for building restricted host-only engine-message telemetry. */
    shouldEmitHostEngineTelemetry?: () => boolean;
    getSubagentSettings?: () => UserSettings["subagents"];
    getParentModel?: () => string | undefined;
    /** Requested parent effort, used when a different-model subagent can accept it. */
    getParentReasoningEffort?: () => string | undefined;
    /** Validated effort actually used by the parent model. */
    getParentEffectiveReasoningEffort?: () => string | undefined;
    getParentContextTier?: () => ContextTier_3 | undefined;
    createSubagentSession?: (agentId: string, options?: SubagentSessionOptions) => LocalSession | Promise<LocalSession>;
    acquireComplementaryAutoSession?: (parentSessionModel: string) => Promise<{
        model: string;
        sessionToken: string;
    } | undefined>;
    customAgents?: SweCustomAgent[];
    mcpTools?: Tool[];
    externalTools?: Tool[];
    models?: readonly Model[];
    shellContextHolder?: ShellContextHolder<InteractiveShellToolContext>;
    sessionFs?: SessionFs;
    taskRegistry?: TaskRegistry;
    taskRegistryAgentId?: string;
    /** Factory run owning the agent that is invoking a tool, when the sender is factory-owned. */
    senderFactoryRunId?: string;
    onFileAccessed?: (path: string, tool: string) => Promise<InstructionSource[] | undefined>;
    consumePendingSystemNotifications?: (predicate: (kind: SystemNotification) => boolean) => void;
    hasPendingSystemNotification?: (filter: SystemNotification) => boolean;
};

declare type ToolInputSchema = {
    type: "object";
    [key: string]: unknown;
};

/** Built-in tools available for the requested model, with their parameters and instructions. */
declare interface ToolList {
    /** List of available built-in tools with metadata */
    tools: Tool_2[];
}

/**
 * An event that is emitted by the `Client` for each tool message it will send back to the LLM.
 */
declare type ToolMessageEvent = {
    kind: "message";
    turn?: number;
    callId?: string;
    modelCall?: ModelCallParam;
    message: ChatCompletionToolMessageParam;
};

/**
 * Metadata is generated by the native registry; these additions represent
 * schema blobs supplied by the live host.
 */
declare type ToolMetadata = NativeToolMetadata & {
    input_schema?: ToolInputSchema;
    format?: CustomToolInputFormat;
    type?: string;
    safeForTelemetry?: boolean | {
        name: boolean;
        inputsNames: boolean;
    };
    _meta?: Record<string, unknown> & {
        ui?: McpUiToolMeta;
    };
};

declare type ToolPartialOutputCallback = (callId: string, output: string) => void;

declare type ToolProgressCallback = (callId: string, progressMessage: string) => void;

declare type ToolResult = string | ToolResultExpanded;

declare interface ToolResultContent {
    type: "tool_result";
    toolUseId: string;
    content?: CallToolResultContent[];
    structuredContent?: unknown;
    isError?: boolean;
    _meta?: Record<string, unknown>;
}

/**
 * Native execution results provide the stable wire fields. The open index is
 * deliberate: post-hook fields are live host data and are not serializable
 * through N-API.
 */
declare type ToolResultExpanded<_TelemetryT extends Telemetry = Telemetry> = Omit<ToolExecutionResult, "resultKind" | "toolTelemetryJson"> & {
    resultType: ToolExecutionResult["resultKind"];
    binaryResultsForLlm?: ExternalToolTextResultForLlmBinaryResultsForLlm[];
    toolTelemetry?: {
        properties?: _TelemetryT["properties"];
        restrictedProperties?: _TelemetryT["restrictedProperties"];
        metrics?: _TelemetryT["metrics"];
    };
    skipLargeOutputProcessing?: boolean;
    newMessages?: Array<{
        content: string;
        source: string;
    }>;
    contents?: ToolExecutionCompleteContent[];
    toolReferences?: string[];
    citableSources?: CitableSource[];
    skillInvocation?: SkillInvocation;
    postToolUseFailureHooksProcessed?: boolean;
    uiResource?: McpUiResource;
    mcpMeta?: Record<string, unknown>;
    structuredContent?: unknown;
    /**
     * The semantic result of a valid `task_complete` request, produced by the
     * autopilot completion reviewer. Absent for legacy/unconditional completions.
     * @internal
     */
    taskCompletionDecision?: TaskCompletionDecision;
};

/** Persisted generic client-side tool activations restored when a session resumes. */
export declare interface ToolSearchActivatedData {
    /** Tool-search strategy that activated the definitions. */
    strategy: string;
    /** Names of tool definitions activated by this search invocation. */
    toolNames: string[];
}

/** Session event "tool_search.activated". Persisted generic client-side tool activations restored when a session resumes. */
export declare interface ToolSearchActivatedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Persisted generic client-side tool activations restored when a session resumes. */
    data: ToolSearchActivatedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "tool_search.activated". */
    type: "tool_search.activated";
}

/** Current lightweight tool metadata snapshot for the session. */
declare interface ToolsGetCurrentMetadataResult {
    /** Current tool metadata, or null when tools have not been initialized yet */
    tools: CurrentToolMetadata[] | null;
}

declare type ToolShutdown = () => Promise<TelemetryEvent | void> | TelemetryEvent | void;

/** Resolve, build, and validate the runtime tool list for this session. Subagent sessions and consumer flows that need an initialized tool set before `send` invoke this. Default base-class implementation is a no-op for sessions that don't support tool validation. */
declare interface ToolsInitializeAndValidateResult {
}

/** Optional model identifier whose tool overrides should be applied to the listing. */
declare interface ToolsListRequest {
    /** Optional model ID — when provided, the returned tool list reflects model-specific overrides */
    model?: string;
}

/** Payload of `session.tools_updated` identifying the model whose resolved tools were updated. */
export declare interface ToolsUpdatedData {
    /** Identifier of the model the resolved tools apply to. */
    model: string;
}

/** Session event "session.tools_updated". Payload of `session.tools_updated` identifying the model whose resolved tools were updated. */
declare interface ToolsUpdatedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `session.tools_updated` identifying the model whose resolved tools were updated. */
    data: ToolsUpdatedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.tools_updated". */
    type: "session.tools_updated";
}
export { ToolsUpdatedEvent as SessionToolsUpdatedEvent }
export { ToolsUpdatedEvent }

/** Empty result after applying subagent settings */
declare interface ToolsUpdateSubagentSettingsResult {
}

declare type ToolThrottleConfig = Readonly<Record<string, ToolThrottleEntry>>;

declare interface ToolThrottleEntry {
    perResponseCap: number;
    perInteractionCap: number;
    throttledMessage: string;
}

declare interface ToolUseContent {
    type: "tool_use";
    name: string;
    id: string;
    input: Record<string, unknown>;
    _meta?: Record<string, unknown>;
}

/** User-initiated tool invocation request with tool name and arguments */
export declare interface ToolUserRequestedData {
    /** Arguments for the tool invocation */
    arguments?: unknown;
    /** Unique identifier for this tool call */
    toolCallId: string;
    /** Name of the tool the user wants to invoke */
    toolName: string;
}

/** Session event "tool.user_requested". User-initiated tool invocation request with tool name and arguments */
export declare interface ToolUserRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** User-initiated tool invocation request with tool name and arguments */
    data: ToolUserRequestedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "tool.user_requested". */
    type: "tool.user_requested";
}

declare type TraceContextResolver = (toolCallId: string) => {
    traceparent?: string;
    tracestate?: string;
} | undefined;

/**
 * Transform override for a single system prompt section.
 * Calls back to the SDK client with the current rendered section content;
 * the client returns the new content. Used for regex, find-and-replace, or logging.
 */
declare interface TransformSectionOverride {
    action: "transform";
}

declare interface Transport {
    start(): Promise<void>;
    send(message: JSONRPCMessage, options?: TransportSendOptions): Promise<void>;
    close(): Promise<void>;
    onclose?: () => void;
    onerror?: (error: Error) => void;
    onmessage?: <T extends JSONRPCMessage>(message: T, extra?: MessageExtraInfo) => void;
    sessionId?: string;
    setProtocolVersion?: (version: string) => void;
}

declare interface TransportSendOptions {
    relatedRequestId?: RequestId;
    resumptionToken?: string;
    onresumptiontoken?: (token: string) => void;
}

/** Conversation truncation statistics including token counts and removed content metrics */
export declare interface TruncationData {
    /** Number of messages removed by truncation */
    messagesRemovedDuringTruncation: number;
    /** Identifier of the component that performed truncation (e.g., "BasicTruncator") */
    performedBy: string;
    /** Number of conversation messages after truncation */
    postTruncationMessagesLength: number;
    /** Total tokens in conversation messages after truncation */
    postTruncationTokensInMessages: number;
    /** Number of conversation messages before truncation */
    preTruncationMessagesLength: number;
    /** Total tokens in conversation messages before truncation */
    preTruncationTokensInMessages: number;
    /** Maximum token count for the model's context window */
    tokenLimit: number;
    /** Number of tokens removed by truncation */
    tokensRemovedDuringTruncation: number;
}

/** Session event "session.truncation". Conversation truncation statistics including token counts and removed content metrics */
declare interface TruncationEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Conversation truncation statistics including token counts and removed content metrics */
    data: TruncationData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.truncation". */
    type: "session.truncation";
}
export { TruncationEvent as SessionTruncationEvent }
export { TruncationEvent }

declare type TruncationEvent_2 = {
    kind: "history_truncated";
    turn: number;
    performedBy: string;
    truncateResult: {
        tokenLimit: number;
        preTruncationTokensInMessages: number;
        preTruncationMessagesLength: number;
        postTruncationTokensInMessages: number;
        postTruncationMessagesLength: number;
        tokensRemovedDuringTruncation: number;
        messagesRemovedDuringTruncation: number;
    };
};

declare type TurnEvent = {
    kind: "turn_started" | "turn_ended" | "turn_failed" | "turn_retry";
    model: string;
    modelInfo: object;
    turn: number;
    timestampMs: number;
    error?: string;
    /** Why this retry is happening (e.g., "streaming_error", "rate_limit"). */
    reason?: string;
};

/** A conversation turn (user→assistant pair). */
declare interface TurnRow {
    session_id: string;
    turn_index: number;
    user_message?: string;
    assistant_response?: string;
    timestamp?: unknown;
}

/** User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). */
declare type UIAutoModeSwitchResponse = "yes" | "yes_always" | "no";

/** Multi-select string field where each option pairs a value with a display label. */
declare interface UIElicitationArrayAnyOfField {
    /** Default values selected when the form is first shown. */
    default?: string[];
    /** Help text describing the field. */
    description?: string;
    /** Schema applied to each item in the array. */
    items: UIElicitationArrayAnyOfFieldItems;
    /** Maximum number of items the user may select. */
    maxItems?: number;
    /** Minimum number of items the user must select. */
    minItems?: number;
    /** Human-readable label for the field. */
    title?: string;
    /** Type discriminator. Always "array". */
    type: "array";
}

/** Schema applied to each item in the array. */
declare interface UIElicitationArrayAnyOfFieldItems {
    /** Selectable options, each with a value and a display label. */
    anyOf: UIElicitationArrayAnyOfFieldItemsAnyOf[];
}

/** Selectable option for a UI elicitation multi-select array item, with submitted value and display label. */
declare interface UIElicitationArrayAnyOfFieldItemsAnyOf {
    /** Value submitted when this option is selected. */
    const: string;
    /** Display label for this option. */
    title: string;
}

/** Multi-select string field whose allowed values are defined inline. */
declare interface UIElicitationArrayEnumField {
    /** Default values selected when the form is first shown. */
    default?: string[];
    /** Help text describing the field. */
    description?: string;
    /** Schema applied to each item in the array. */
    items: UIElicitationArrayEnumFieldItems;
    /** Maximum number of items the user may select. */
    maxItems?: number;
    /** Minimum number of items the user must select. */
    minItems?: number;
    /** Human-readable label for the field. */
    title?: string;
    /** Type discriminator. Always "array". */
    type: "array";
}

/** Schema applied to each item in the array. */
declare interface UIElicitationArrayEnumFieldItems {
    /** Allowed string values for each selected item. */
    enum: string[];
    /** Type discriminator. Always "string". */
    type: "string";
}

/** Submitted UI elicitation field value: string, number, boolean, or an array of strings. */
declare type UIElicitationFieldValue = string | number | boolean | string[];

/** Prompt message and JSON schema describing the form fields to elicit from the user. */
declare interface UIElicitationRequest {
    /** Message describing what information is needed from the user */
    message: string;
    /** JSON Schema describing the form fields to present to the user */
    requestedSchema: UIElicitationSchema;
}

/** The elicitation response (accept with form values, decline, or cancel) */
declare interface UIElicitationResponse {
    /** The user's response: accept (submitted), decline (rejected), or cancel (dismissed) */
    action: UIElicitationResponseAction;
    /** The form values submitted by the user (present when action is 'accept') */
    content?: UIElicitationResponseContent;
}

/** The user's response: accept (submitted), decline (rejected), or cancel (dismissed) */
declare type UIElicitationResponseAction = "accept" | "decline" | "cancel";

/** The form values submitted by the user (present when action is 'accept') */
declare type UIElicitationResponseContent = Record<string, UIElicitationFieldValue>;

/** Indicates whether the elicitation response was accepted; false if it was already resolved by another client. */
declare interface UIElicitationResult {
    /** Whether the response was accepted. False if the request was already resolved by another client. */
    success: boolean;
}

/** JSON Schema describing the form fields to present to the user */
declare interface UIElicitationSchema {
    /** Form field definitions, keyed by field name */
    properties: Record<string, UIElicitationSchemaProperty>;
    /** List of required field names */
    required?: string[];
    /** Schema type indicator (always 'object') */
    type: "object";
}

/** Definition for a single elicitation form field. */
declare type UIElicitationSchemaProperty = UIElicitationStringEnumField | UIElicitationStringOneOfField | UIElicitationArrayEnumField | UIElicitationArrayAnyOfField | UIElicitationSchemaPropertyBoolean | UIElicitationSchemaPropertyString | UIElicitationSchemaPropertyNumber;

/** Boolean field rendered as a yes/no toggle. */
declare interface UIElicitationSchemaPropertyBoolean {
    /** Default value selected when the form is first shown. */
    default?: boolean;
    /** Help text describing the field. */
    description?: string;
    /** Human-readable label for the field. */
    title?: string;
    /** Type discriminator. Always "boolean". */
    type: "boolean";
}

/** Numeric field accepting either a number or an integer. */
declare interface UIElicitationSchemaPropertyNumber {
    /** Default value populated in the input when the form is first shown. */
    default?: number;
    /** Help text describing the field. */
    description?: string;
    /** Maximum allowed value (inclusive). */
    maximum?: number;
    /** Minimum allowed value (inclusive). */
    minimum?: number;
    /** Human-readable label for the field. */
    title?: string;
    /** Numeric type accepted by the field. */
    type: UIElicitationSchemaPropertyNumberType;
}

/** Numeric type accepted by the field. */
declare type UIElicitationSchemaPropertyNumberType = "number" | "integer";

/** Free-text string field with optional length and format constraints. */
declare interface UIElicitationSchemaPropertyString {
    /** Default value populated in the input when the form is first shown. */
    default?: string;
    /** Help text describing the field. */
    description?: string;
    /** Optional format hint that constrains the accepted input. */
    format?: UIElicitationSchemaPropertyStringFormat;
    /** Maximum number of characters allowed. */
    maxLength?: number;
    /** Minimum number of characters required. */
    minLength?: number;
    /** Human-readable label for the field. */
    title?: string;
    /** Type discriminator. Always "string". */
    type: "string";
}

/** Optional format hint that constrains the accepted input. */
declare type UIElicitationSchemaPropertyStringFormat = "email" | "uri" | "date" | "date-time";

/** Single-select string field whose allowed values are defined inline. */
declare interface UIElicitationStringEnumField {
    /** Default value selected when the form is first shown. */
    default?: string;
    /** Help text describing the field. */
    description?: string;
    /** Allowed string values. */
    enum: string[];
    /** Optional display labels for each enum value, in the same order as `enum`. */
    enumNames?: string[];
    /** Human-readable label for the field. */
    title?: string;
    /** Type discriminator. Always "string". */
    type: "string";
}

/** Single-select string field where each option pairs a value with a display label. */
declare interface UIElicitationStringOneOfField {
    /** Default value selected when the form is first shown. */
    default?: string;
    /** Help text describing the field. */
    description?: string;
    /** Selectable options, each with a value and a display label. */
    oneOf: UIElicitationStringOneOfFieldOneOf[];
    /** Human-readable label for the field. */
    title?: string;
    /** Type discriminator. Always "string". */
    type: "string";
}

/** Selectable option for a UI elicitation single-select string field, with submitted value and display label. */
declare interface UIElicitationStringOneOfFieldOneOf {
    /** Value submitted when this option is selected. */
    const: string;
    /** Display label for this option. */
    title: string;
}

/** Transient question to answer without adding it to conversation history. */
declare interface UIEphemeralQueryRequest {
    /** In-process `AbortSignal` forwarded to the model client to cancel an in-flight request. Marked internal: excluded from the public SDK surface. Replaced by an explicit cancellation token + cancel RPC in the SDK migration. */
    abortSignal?: unknown;
    /** In-process streaming callback `(text) => void` invoked with each token as the model emits it. Marked internal: excluded from the public SDK surface. In a process-separated SDK this is replaced by a streaming RPC that yields chunks and a final answer. */
    onChunk?: unknown;
    /** Question to answer from the current conversation context. */
    question: string;
}

/** Transient answer generated from current conversation context. */
declare interface UIEphemeralQueryResult {
    /** Full assistant response text. */
    answer: string;
}

/** The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. */
declare type UIExitPlanModeAction = "exit_only" | "interactive" | "autopilot" | "autopilot_fleet";

/** User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. */
declare interface UIExitPlanModeResponse {
    /** Whether the plan was approved. */
    approved: boolean;
    /** Whether subsequent edits should be auto-approved without confirmation. */
    autoApproveEdits?: boolean;
    /** When true, the agent is instructed to end its turn without starting implementation so the client can restore the session model and auto-submit a fresh implementation turn on it. Set only when a distinct plan configuration (a different model, reasoning effort, or context tier) actually ran the planning turn. */
    deferImplementation?: boolean;
    /** Feedback from the user when they declined the plan or requested changes. */
    feedback?: string;
    /** The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. */
    selectedAction?: UIExitPlanModeAction;
}

/** Request ID of a pending `auto_mode_switch.requested` event and the user's response. */
declare interface UIHandlePendingAutoModeSwitchRequest {
    /** The unique request ID from the auto_mode_switch.requested event */
    requestId: string;
    /** User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). */
    response: UIAutoModeSwitchResponse;
}

/** Pending elicitation request ID and the user's response (accept/decline/cancel + form values). */
declare interface UIHandlePendingElicitationRequest {
    /** The unique request ID from the elicitation.requested event */
    requestId: string;
    /** The elicitation response (accept with form values, decline, or cancel) */
    result: UIElicitationResponse;
}

/** Request ID of a pending `exit_plan_mode.requested` event and the user's response. */
declare interface UIHandlePendingExitPlanModeRequest {
    /** The unique request ID from the exit_plan_mode.requested event */
    requestId: string;
    /** User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. */
    response: UIExitPlanModeResponse;
}

/** Indicates whether the pending UI request was resolved by this call. */
declare interface UIHandlePendingResult {
    /** True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. */
    success: boolean;
}

/** Request ID of a pending `sampling.requested` event and an optional sampling result payload (omit to reject). */
declare interface UIHandlePendingSamplingRequest {
    /** The unique request ID from the sampling.requested event */
    requestId: string;
    /** Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. */
    response?: UIHandlePendingSamplingResponse;
}

/** Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. */
declare interface UIHandlePendingSamplingResponse {
    [key: string]: unknown;
}

/** Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. */
declare interface UIHandlePendingSessionLimitsExhaustedRequest {
    /** The unique request ID from the session_limits_exhausted.requested event */
    requestId: string;
    /** The selected session-limit action. */
    response: UISessionLimitsExhaustedResponse;
}

/** Request ID of a pending `user_input.requested` event and the user's response. */
declare interface UIHandlePendingUserInputRequest {
    /** The unique request ID from the user_input.requested event */
    requestId: string;
    /** User response for a pending user-input request, with answer text and whether it was typed freeform. */
    response: UIUserInputResponse;
}

/** Register an in-process handler for `auto_mode_switch.requested` events. The caller still attaches the actual listener via the standard event-subscription mechanism; this registration solely tells the server bridge to skip its own dispatch (so a remote client doesn't race the in-process handler for the same requestId). */
declare interface UIRegisterDirectAutoModeSwitchHandlerResult {
    /** Opaque handle representing the registration. Pass this same handle to `unregisterDirectAutoModeSwitchHandler` when the in-process handler is no longer active. Multiple registrations are reference-counted; the server bridge will only dispatch auto-mode-switch requests when no handles are active. */
    handle: string;
}

/** The user's selected action for an exhausted session limit. */
declare interface UISessionLimitsExhaustedResponse {
    /** Action selected by the user. */
    action: UISessionLimitsExhaustedResponseAction;
    /** AI Credits to add to the current max when action is 'add'. */
    additionalAiCredits?: number;
    /** New absolute max AI Credits when action is 'set'. */
    maxAiCredits?: number;
}

/** User action selected for an exhausted session limit. */
declare type UISessionLimitsExhaustedResponseAction = "add" | "set" | "unset" | "cancel";

/** Opaque handle previously returned by `registerDirectAutoModeSwitchHandler` to release. */
declare interface UIUnregisterDirectAutoModeSwitchHandlerRequest {
    /** Handle previously returned by `registerDirectAutoModeSwitchHandler` */
    handle: string;
}

/** Indicates whether the handle was active and the registration count was decremented. */
declare interface UIUnregisterDirectAutoModeSwitchHandlerResult {
    /** True if the handle was active and decremented the counter; false if the handle was unknown. */
    unregistered: boolean;
}

/** User response for a pending user-input request, with answer text and whether it was typed freeform. */
declare interface UIUserInputResponse {
    /** The user's answer text */
    answer: string;
    /** True if the user typed a freeform response, false if they selected a presented choice. Used by telemetry to differentiate between free text input and choice selection. */
    wasFreeform: boolean;
}

export declare type UpdatableSessionOptions = Omit<SessionOptions, "sessionId" | "startTime" | "modifiedTime" | "summary" | "internalCorrelationIds" | "additionalDirectories" | "mcpTraceContextResolver" | "otelParentContextResolver" | "remoteDelegate" | "shellNotifier" | "telemetrySender" | "extensionController" | "enableFileChangeTracking" | "featureFlagService" | "includedBuiltinAgents" | "rewindManager" | "resumedFromEvents" | "hookSessionHandle" | "nativeHookProcessor" | "ownsHookSession" | "pluginActivationPolicy" | "pluginActivationSnapshot" | "autopilotContinuation" | "managedSettings"> & {
    /** Set to null to remove an existing built-in agent allow-list restriction. */
    includedBuiltinAgents?: string[] | null;
};

export declare interface UpdateOptionsBehavior {
    emitToolDefinitionsChanged?: boolean;
    emitSessionLimitsChanged?: boolean;
    /**
     * Internal updates to the model-specific effective tool list should not
     * replace the durable filter policy inherited by nested subagents.
     */
    preserveSubagentToolFilters?: boolean;
    /**
     * Marks a `workingDirectory` change as authoritative (an explicit user or
     * SDK cwd change such as `/worktree`, `/cd`, or resume). An authoritative
     * change latches ownership of the runtime cwd so that later non-authoritative,
     * stale full-options snapshots (e.g. the CLI options-sync effect) cannot
     * silently rewind it. Leave unset/false for incidental option syncs.
     */
    workingDirectoryAuthority?: boolean;
}

/** Subagent settings to apply to the current session */
declare interface UpdateSubagentSettingsRequest {
    /** Subagent settings to apply, or null to clear the live session override */
    subagents: SubagentSettings;
}

declare type UrlManager = NativeUrlManager;

/**
 * A permission request for accessing URLs.
 */
declare type UrlPermissionRequest = {
    readonly kind: "url";
    /** The intention, e.g. "Fetch web content" */
    readonly intention: string;
    /** The URL being accessed */
    readonly url: string;
    /** The immediately preceding URL when this request is for a redirect target. */
    readonly redirectedFrom?: string;
    /**
     * True when this URL fetch is requesting to bypass the sandbox network
     * policy — either because the model set `requestSandboxBypass: true`, or
     * because the tool re-issued the request as an interactive bypass after the
     * network policy denied the approved URL (host opted in via
     * `sandbox.allowBypass`). This is a request, not a grant: the fetch runs
     * only if the user approves this permission request. Hosts should highlight
     * the elevated risk in the approval UI.
     */
    readonly requestSandboxBypass?: boolean;
    /**
     * Model-provided justification for the sandbox-bypass request
     * ({@link requestSandboxBypass}). Only meaningful when
     * `requestSandboxBypass` is true.
     */
    readonly requestSandboxBypassReason?: string;
    /** Managed policy requires an explicit human response for this URL fetch. */
    readonly managedApprovalRequired?: boolean;
    readonly autoApproval?: AutoApproval;
};

/** Durable session usage checkpoint for reconstructing aggregate accounting on resume */
export declare interface UsageCheckpointData {
    /** Internal per-model prompt-cache state used to restore expiration tracking on resume */
    modelCacheState?: UsageCheckpointModelCacheState[];
    /** Session-wide accumulated nano-AI units cost at checkpoint time */
    totalNanoAiu: number;
    /** Total number of premium API requests used at checkpoint time */
    totalPremiumRequests?: number;
}

/** Session event "session.usage_checkpoint". Durable session usage checkpoint for reconstructing aggregate accounting on resume */
declare interface UsageCheckpointEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Durable session usage checkpoint for reconstructing aggregate accounting on resume */
    data: UsageCheckpointData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.usage_checkpoint". */
    type: "session.usage_checkpoint";
}
export { UsageCheckpointEvent as SessionUsageCheckpointEvent }
export { UsageCheckpointEvent }

/** Internal prompt-cache expiration state for one model */
export declare interface UsageCheckpointModelCacheState {
    /** Latest known prompt-cache expiration */
    cacheExpiresAt: string;
    /** Retained cache lifetime in seconds, used to refresh expiration after a cache read */
    cacheTtlSeconds: number;
    /** Model identifier associated with this cache state */
    modelId: string;
}

/** Accumulated session usage metrics, including premium request cost, token counts, model breakdown, and code-change totals. */
declare interface UsageGetMetricsResult {
    /** Aggregated code change metrics */
    codeChanges: UsageMetricsCodeChanges;
    /** Currently active model identifier */
    currentModel?: string;
    /** Input tokens from the most recent main-agent API call */
    lastCallInputTokens: number;
    /** Output tokens from the most recent main-agent API call */
    lastCallOutputTokens: number;
    /** Per-model token and request metrics, keyed by model identifier */
    modelMetrics: Record<string, UsageMetricsModelMetric>;
    /** ISO 8601 timestamp when the session started */
    sessionStartTime: string;
    /** Session-wide per-token-type accumulated token counts */
    tokenDetails?: Record<string, UsageMetricsTokenDetail>;
    /** Total time spent in model API calls (milliseconds) */
    totalApiDurationMs: number;
    /** Session-wide accumulated nano-AI units cost */
    totalNanoAiu?: number;
    /** Total user-initiated premium request cost across all models (may be fractional due to multipliers) */
    totalPremiumRequestCost: number;
    /** Raw count of user-initiated API requests */
    totalUserRequests: number;
}

/** Current context window usage statistics including token and message counts */
export declare interface UsageInfoData {
    /** Token count from non-system messages (user, assistant, tool) */
    conversationTokens?: number;
    /** Current number of tokens in the context window */
    currentTokens: number;
    /** Whether this is the first usage_info event emitted in this session */
    isInitial?: boolean;
    /** Current number of messages in the conversation */
    messagesLength: number;
    /** Token count from system message(s) */
    systemTokens?: number;
    /** Maximum token count for the model's context window */
    tokenLimit: number;
    /** Token count from tool definitions */
    toolDefinitionsTokens?: number;
}

/** Session event "session.usage_info". Current context window usage statistics including token and message counts */
declare interface UsageInfoEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Current context window usage statistics including token and message counts */
    data: UsageInfoData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.usage_info". */
    type: "session.usage_info";
}
export { UsageInfoEvent as SessionUsageInfoEvent }
export { UsageInfoEvent }

/**
 * Event emitted every turn to report current context window token usage.
 * Unlike TruncationEvent, this is always emitted regardless of whether truncation occurred.
 */
declare type UsageInfoEvent_2 = {
    kind: "usage_info";
    turn: number;
    tokenLimit: number;
    currentTokens: number;
    messagesLength: number;
    /** Token count from system message(s) */
    systemTokens?: number;
    /** Token count from non-system messages (user, assistant, tool) */
    conversationTokens?: number;
    /** Token count from tool definitions */
    toolDefinitionsTokens?: number;
    /** Whether this is the first usage_info event emitted in this session */
    isInitial?: boolean;
};

declare interface UsageMetricsAttribution {
    /** Value emitted as `editor_version` (e.g. `"JetBrains.PyCharm/2025.3.2.1"`). */
    editorVersion: string;
    /** Value emitted as `common_extname` (e.g. `"JetBrains.PyCharm"`). */
    commonExtName: string;
    /** Value emitted as `common_extversion` (e.g. `"2025.3.2.1"`). */
    commonExtVersion?: string;
}

/** Aggregated code change metrics */
declare interface UsageMetricsCodeChanges {
    /** Distinct file paths modified during the session */
    filesModified: string[];
    /** Number of distinct files modified */
    filesModifiedCount: number;
    /** Total lines of code added */
    linesAdded: number;
    /** Total lines of code removed */
    linesRemoved: number;
}

/** Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. */
declare interface UsageMetricsModelMetric {
    /** Latest known prompt-cache expiration for this model. A timestamp in the past indicates that the observed cache has expired. */
    cacheExpiresAt?: string;
    /** Request count and cost metrics for this model */
    requests: UsageMetricsModelMetricRequests;
    /** Token count details per type */
    tokenDetails?: Record<string, UsageMetricsModelMetricTokenDetail>;
    /** Accumulated nano-AI units cost for this model */
    totalNanoAiu?: number;
    /** Token usage metrics for this model */
    usage: UsageMetricsModelMetricUsage;
}

/** Request count and cost metrics for this model */
declare interface UsageMetricsModelMetricRequests {
    /** User-initiated premium request cost (with multiplier applied) */
    cost: number;
    /** Number of API requests made with this model */
    count: number;
}

/** Per-model token-detail entry containing the accumulated token count for one token type. */
declare interface UsageMetricsModelMetricTokenDetail {
    /** Accumulated token count for this token type */
    tokenCount: number;
}

/** Token usage metrics for this model */
declare interface UsageMetricsModelMetricUsage {
    /** Total tokens read from prompt cache */
    cacheReadTokens: number;
    /** Total tokens written to prompt cache */
    cacheWriteTokens: number;
    /** Total input tokens consumed */
    inputTokens: number;
    /** Total output tokens produced */
    outputTokens: number;
    /** Total output tokens used for reasoning */
    reasoningTokens?: number;
}

/** Session-wide token-detail entry containing the accumulated token count for one token type. */
declare interface UsageMetricsTokenDetail {
    /** Accumulated token count for this token type */
    tokenCount: number;
}

/** Represents the user-based authentication information (OAuth). */
declare type UserAuthInfo = {
    readonly type: "user";
    readonly host: string;
    readonly login: string;
    readonly copilotUser?: CopilotUserResponse;
};

/** Authentication-info variant for OAuth user auth, with host and login; the token remains in the runtime secret store. */
declare interface UserAuthInfo_2 {
    /** Snapshot of the authenticated user's Copilot subscription info, if known. Mirrors the GitHub API `/copilot_internal/v2/token` user response shape — the runtime trusts this verbatim and does not re-fetch when set. */
    copilotUser?: CopilotUserResponse;
    /** Authentication host. */
    host: string;
    /** OAuth user login. */
    login: string;
    /** OAuth user authentication. The token itself is held in the runtime's secret token store (keyed by host+login) and is NOT carried in this struct. */
    type: "user";
}

/**
 * A permission request that will be presented to the user for specific commands.
 */
declare type UserCommandsPermissionRequest = {
    readonly kind: "commands";
    readonly fullCommandText: string;
    readonly intention: string;
    readonly commandIdentifiers: ReadonlyArray<string>;
    readonly canOfferSessionApproval: boolean;
    readonly warning?: string;
    readonly requestSandboxBypass?: boolean;
    readonly requestSandboxBypassReason?: string;
    /** Managed policy requires an explicit human response for this command. */
    readonly managedApprovalRequired?: boolean;
    readonly autoApproval?: AutoApproval;
};

/**
 * A custom tool permission request that will be presented to the user.
 */
declare type UserCustomToolPermissionRequest = {
    readonly kind: "custom-tool";
    readonly toolName: string;
    readonly toolDescription: string;
    readonly args?: unknown;
    readonly autoApproval?: AutoApproval;
};

/**
 * An extension management permission request that will be presented to the user.
 */
declare type UserExtensionManagementPermissionRequest = {
    readonly kind: "extension-management";
    readonly operation: string;
    readonly extensionName?: string;
    readonly autoApproval?: AutoApproval;
};

/**
 * An extension permission access request that will be presented to the user.
 */
declare type UserExtensionPermissionAccessRequest = {
    readonly kind: "extension-permission-access";
    readonly extensionName: string;
    readonly capabilities: string[];
    readonly autoApproval?: AutoApproval;
};

/**
 * A factory permission request that will be presented to the user.
 */
declare type UserFactoryPermissionRequest = FactoryPermissionRequest & {
    readonly managedApprovalRequired?: boolean;
};

/** User input request completion with the user's response */
export declare interface UserInputCompletedData {
    /** The user's answer to the input request */
    answer?: string;
    /** Request ID of the resolved user input request; clients should dismiss any UI for this request */
    requestId: string;
    /** Whether the answer was typed as free-form text rather than selected from choices */
    wasFreeform?: boolean;
}

/** Session event "user_input.completed". User input request completion with the user's response */
export declare interface UserInputCompletedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** User input request completion with the user's response */
    data: UserInputCompletedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "user_input.completed". */
    type: "user_input.completed";
}

declare type UserInputRequest = {
    question: string;
    choices?: string[];
    allowFreeform?: boolean;
    toolCallId?: string;
};

/** User input request notification with question and optional predefined choices */
export declare interface UserInputRequestedData {
    /** Whether the user can provide a free-form text response in addition to predefined choices */
    allowFreeform?: boolean;
    /** Predefined choices for the user to select from, if applicable */
    choices?: string[];
    /** The question or prompt to present to the user */
    question: string;
    /** Unique identifier for this input request; used to respond via session.respondToUserInput() */
    requestId: string;
    /** The LLM-assigned tool call ID that triggered this request; used by remote UIs to correlate responses */
    toolCallId?: string;
}

/** Session event "user_input.requested". User input request notification with question and optional predefined choices */
export declare interface UserInputRequestedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** User input request notification with question and optional predefined choices */
    data: UserInputRequestedData;
    /** Always true for events that are transient and not persisted to the session event log on disk. */
    ephemeral: true;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "user_input.requested". */
    type: "user_input.requested";
}

declare type UserInputResponse = {
    answer: string;
    wasFreeform: boolean;
    dismissed?: boolean;
};

/**
 * A write permission request that we expect will be presented to the user in some manner.
 */
declare type UserMCPPermissionRequest = {
    readonly kind: "mcp";
    readonly serverName: string;
    readonly toolName: string;
    readonly toolTitle: string;
    readonly args: unknown;
    readonly autoApproval?: AutoApproval;
};

declare type UserMessage = {
    id: string;
    actor_id: number;
    content: string;
    timestamp: number;
};

/** The agent mode that was active when this message was sent */
declare type UserMessageAgentMode = "interactive" | "plan" | "autopilot" | "shell";
export { UserMessageAgentMode as AgentMode }
export { UserMessageAgentMode }

/** Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. */
export declare interface UserMessageData {
    /** The agent mode that was active when this message was sent */
    agentMode?: UserMessageAgentMode;
    /** Files, selections, or GitHub references attached to the message */
    attachments?: Attachment[];
    /** The user's message text as displayed in the timeline */
    content: string;
    /** How this message was delivered to the agentic loop relative to loop state (idle-start vs. steering/queued while busy). The timing axis; combine with `source` (origin) for the full picture. Used for telemetry attribution. */
    delivery?: UserMessageDelivery;
    /** CAPI interaction ID for correlating this user message with its turn */
    interactionId?: string;
    /** True when this user message was auto-injected by autopilot's continuation loop rather than typed by the user; used to distinguish autopilot-driven turns in telemetry. */
    isAutopilotContinuation?: boolean;
    /** Path-backed native document attachments that stayed on the tagged_files path flow because native upload could not read them or would exceed the request size limit */
    nativeDocumentPathFallbackPaths?: string[];
    /** Parent agent task ID for background telemetry correlated to this user turn */
    parentAgentTaskId?: string;
    /** Origin of this message, used for timeline filtering and attribution (e.g., `skill-pdf` for hidden skill injection or `agent-<agent-id>` for an inter-agent prompt) */
    source?: string;
    /** Normalized document MIME types that were sent natively instead of through tagged_files XML */
    supportedNativeDocumentMimeTypes?: string[];
    /** Transformed version of the message sent to the model, with XML wrapping, timestamps, and other augmentations for prompt caching */
    transformedContent?: string;
}

/** How this user message was delivered to the agentic loop, relative to whether the loop was already running. This is the timing axis only; the message's origin (human vs. system/command/schedule/skill/etc.) is carried separately by `source`. A system-injected message has a delivery too — e.g. a background-task notification waking an idle agent is `idle`, the same mechanism as a human starting a fresh turn. */
export declare type UserMessageDelivery = "idle" | "steering" | "queued";

/** Session event "user.message". Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. */
export declare interface UserMessageEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. */
    data: UserMessageData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "user.message". */
    type: "user.message";
}

/**
 * An event that is emitted by the `Client` for each user message it adds to the middle of the conversation.
 */
declare type UserMessageEvent_2 = {
    kind: "message";
    turn?: number;
    callId?: string;
    modelCall?: ModelCallParam;
    message: ChatCompletionUserMessageParam;
    /**
     * The component which was the source of the user message.
     * - `jit-instruction`: The message was injected by something which adds automated instructions for the agent
     * - `command-{id}`: The message was injected as a result of a command with the given id
     * - `immediate-prompt`: The message was already persisted by the immediate-prompt pre-request path; see {@link IMMEDIATE_PROMPT_SOURCE}
     * - `string`: Some other source
     */
    source?: string;
};

declare class UserMessageSentimentTelemetry implements Disposable_2 {
    private readonly session;
    private previousUserMessage;
    private unsubscribe;
    constructor(session: Session);
    dispose(): void;
    handleUserMessage(event: UserMessageEvent): Promise<void>;
    private judgeUserMessageSentiment;
}

/**
 * A response to a user path permission request.
 */
declare type UserPathPermissionRequestResponse = {
    readonly kind: "approve-once";
} | {
    readonly kind: "approve-for-session";
} | {
    readonly kind: "reject";
    readonly feedback?: string;
} | {
    readonly kind: "user-not-available";
};

/**
 * A read permission request that will be presented to the user.
 */
declare type UserReadPermissionRequest = {
    readonly kind: "read";
    readonly intention: string;
    readonly path: string;
    /**
     * True when the model requested running this search outside the sandbox and
     * the host opted in via `sandbox.allowBypass`. Surfaced so the prompt UI can
     * highlight the elevated risk of reading outside the sandbox.
     */
    readonly requestSandboxBypass?: boolean;
    /** Model-provided justification for the sandbox-bypass request. */
    readonly requestSandboxBypassReason?: string;
    /** Managed policy requires an explicit human response for this read. */
    readonly managedApprovalRequired?: boolean;
    readonly autoApproval?: AutoApproval;
};

export declare interface UserRequestedShellCommandOptions {
    abortSignal?: AbortSignal;
}

export declare type UserRequestedShellCommandResult = UserRequestedShellCommandResult_2;

/** Result of a user-requested shell command. */
declare interface UserRequestedShellCommandResult_2 {
    /** Error output when the execution failed */
    error?: string;
    /** Process exit code, when available */
    exitCode?: number | null;
    /** Captured command output */
    output: string;
    /** Whether the command completed successfully */
    success: boolean;
    /** Tool call id emitted for the shell execution */
    toolCallId: string;
}

export declare interface UserRequestedShellExecution {
    success: boolean;
    output: string;
    exitCode: number | null;
    error?: string;
}

/** A single user setting's effective value alongside its default, so consumers can render settings left at their default. */
declare interface UserSettingMetadata {
    /** The centrally-known default for this setting (null when no default is registered). */
    default: unknown;
    /** True when the user has not set an explicit value for this setting (i.e. it is left at its default). Reflects whether the user has overridden the key, not whether the effective value happens to equal the default — a key explicitly set to a value identical to the default still reports false. */
    isDefault: boolean;
    /** The effective value: the user's value if set, otherwise the default. */
    value: unknown;
}

declare interface UserSettings {
    [key: string]: unknown;
    mouse?: boolean;
    askUser?: boolean;
    autoUpdate?: boolean;
    bashEnv?: boolean;
    powershellFlags?: string[];
    autoUpdatesChannel?: "stable" | "prerelease";
    banner?: "always" | "once" | "never";
    showTipsOnStartup?: boolean;
    beep?: boolean;
    beepOnSchedule?: boolean;
    notifications?: boolean;
    keepAlive?: "on" | "off" | "busy";
    includeCoAuthoredBy?: boolean;
    compactPaste?: boolean;
    copyOnSelect?: boolean;
    /**
     * Maximum number of recent prompts retained for the Ctrl+R command-history
     * search (and up/down history navigation). Newest-first and deduplicated;
     * older entries beyond this many are dropped. Must be an integer within
     * `[1, 1000]`; out-of-range or non-integer values are rejected on write and
     * fall back to the default of 50 on load.
     */
    commandHistoryMaxSize?: number;
    /**
     * Ref used as the starting point for new clean worktrees. Defaults to the
     * current checkout (`head`); `defaultBranch` uses the remote default branch.
     * A rollout feature flag may change the default when this setting is unset.
     */
    worktreeBaseRef?: WorktreeBaseRef;
    respectGitignore?: boolean;
    proxyKerberosServicePrincipal?: string;
    builtInAgents?: {
        rubberDuck?: boolean;
        rubberDuckAutoInvoke?: boolean;
        [key: string]: unknown;
    };
    memory?: boolean;
    toolSearch?: boolean;
    model?: string;
    effortLevel?: string;
    contextTier?: "default" | "long_context";
    /**
     * Model used while the session is in plan mode. When unset, plan mode uses
     * the session {@link model} (current behavior). Set via `/model plan <id>`
     * or `/model --plan <id>`.
     */
    planModel?: string;
    /** Reasoning effort applied to {@link planModel} while in plan mode. */
    planEffortLevel?: string;
    /** Context tier applied to {@link planModel} while in plan mode. */
    planContextTier?: "default" | "long_context";
    subagents?: {
        agents?: Record<string, SubagentSelection>;
        disabledSubagents?: string[];
        /** Max concurrent subagents (usage-based billing users only). Bounds enforced in Rust. */
        maxConcurrency?: number;
        /** Max subagent nesting depth (usage-based billing users only). Bounds enforced in Rust. */
        maxDepth?: number;
        [key: string]: unknown;
    };
    continueOnAutoMode?: boolean;
    /**
     * When true, the CLI stays in autopilot mode after an autopilot task
     * completes (via `task_complete`) instead of reverting to interactive
     * mode. Defaults to true; set to false to revert to interactive after each
     * completed task.
     */
    stayInAutopilot?: boolean;
    /**
     * When true, submitting a prompt that is nothing but a lone `$` hands the
     * terminal to an interactive shell rooted at the session working directory (a
     * shell-out, restored on `exit`). The composer's hint bar advertises the gesture
     * while the lone `$` sits at the prompt, before Enter is pressed. Only ever
     * activates for a local, trusted session on a real TTY; it works even while the
     * agent is running.
     * User/managed-scoped only (not repo-overridable). Defaults to true.
     */
    shellShortcut?: boolean;
    /**
     * Managed-only cache-control directive. When true, a fresh server-managed
     * settings fetch is required on startup even when a fresh persistent cache
     * entry exists: the cached policy is never *served* (though it is still kept
     * as a fetch-failure fallback). The flag applies even when it lives in the
     * cache — a cached server response carrying it forces the next startup to
     * re-fetch. Settable via the server-managed policy or the device (MDM) layer.
     * Defaults to false.
     */
    forceRemoteSettingsRefresh?: boolean;
    renderMarkdown?: boolean;
    /**
     * Render standalone six-digit hex color codes (e.g. `#FF0000`), including
     * ones written as inline code, as inline color swatches. CLI UI only.
     * Defaults to true.
     */
    renderHexColors?: boolean;
    inlineImages?: boolean;
    /**
     * Maximum number of inline images kept live (resident) in the terminal at
     * once — the most-recent N by timeline order. Images beyond N render as a
     * text caption and have their data freed from the terminal, bounding image
     * memory in long, image-heavy sessions. `0` disables the cap. Overridden by
     * the `COPILOT_INLINE_IMAGE_LIMIT` environment variable. Defaults to 50.
     */
    inlineImageLiveWindow?: number;
    scrollbar?: boolean;
    /**
     * Pin the current section's user prompt just below the top bar while
     * scrolling the timeline, so it stays clear which request the visible
     * output belongs to. CLI UI only; no effect on prompts sent to the model.
     * Off by default: the pin costs two to three timeline rows to restate a
     * prompt the user just scrolled past. Set it to `true` to opt in.
     */
    pinnedPrompts?: boolean;
    /**
     * Sessions sidebar preferences (CLI UI only).
     */
    sidebar?: {
        /**
         * Show the Sessions sidebar and allow opening it from the composer with
         * the Left arrow. When false, the Left-arrow gesture no longer
         * opens/focuses the sidebar and its composer hint is hidden. Defaults to
         * true.
         */
        enabled?: boolean;
        /**
         * Restore the resumable sessions remembered for the launch directory when
         * the sidebar opens, so relaunching in the same directory shows the prior
         * sessions without manually resuming them. Defaults to true.
         */
        showResumableSessions?: boolean;
        /**
         * Show the header button row (`← collapse sidebar · + new session`)
         * docked at the top of the sidebar, clickable and keyboard-reachable
         * (Up past the top card). Defaults to true.
         */
        showHeaderButtons?: boolean;
        /**
         * Show a per-card close button on the sidebar session cards. When on,
         * hovering a card's right end reveals a red `close session` region, and
         * clicking it arms then confirms closing that session (mirroring the
         * `x` gesture). Defaults to false.
         */
        showCloseButton?: boolean;
        /**
         * Follow the mouse in the split view: moving the pointer ACROSS the
         * split divider focuses the pane it lands in, and the sidebar's cards
         * and header buttons preview a hover highlight under the cursor. Focus
         * tracks divider crossings, not the pointer's resting side, so a
         * keyboard or click focus change sticks until the mouse actually
         * travels to the other pane (a pointer parked on the rail cannot yank
         * focus back after a card click, and the first hover once the split
         * opens only records which side the pointer is on). When false nothing
         * reacts to hover (focus stays keyboard/click driven and nothing lights
         * up), but clicks still work. Needs a terminal with any-event mouse
         * tracking; without it hover events never arrive. Defaults to false.
         */
        hoverFocus?: boolean;
        /**
         * Color the composer's `← use sidebar` hint with the sidebar's selected
         * accent as a call-to-action while the split is open with the timeline
         * focused. When false it renders in the neutral hint color like every
         * other composer shortcut. Defaults to true. The closed-state `← open
         * sidebar` hint is always neutral.
         */
        coloredHints?: boolean;
        /**
         * Swap the sidebar card highlights: the currently active (foreground)
         * session card gets the pronounced inverted accent fill -- in both
         * focus states, so the active session stays identifiable while the
         * timeline owns the keyboard -- and the keyboard cursor gets the
         * subtle fill instead. Arming a close (`x` or the close button) still
         * recolors the cursor's card to the pronounced red confirm bar. When
         * false the cursor is accented and the active card is subtle.
         * Defaults to true.
         */
        accentActiveSession?: boolean;
    };
    remoteExport?: boolean;
    statusLine?: {
        type?: "command";
        command?: string;
        padding?: number;
        refreshInterval?: number;
        [key: string]: unknown;
    };
    screenReader?: boolean;
    /** Color theme / palette. Canonical key for the color mode (was `colorMode`). */
    theme?: ColorMode;
    /** @deprecated Legacy alias for {@link theme}; normalized to `theme` on load. */
    colorMode?: ColorMode;
    allowedUrls?: string[];
    deniedUrls?: string[];
    proxyUrl?: string;
    storeTokenPlaintext?: boolean;
    stream?: boolean;
    streamerMode?: boolean;
    footer?: {
        showModelEffort?: boolean;
        showDirectory?: boolean;
        showBranch?: boolean;
        showContextWindow?: boolean;
        showQuota?: boolean;
        showAiUsed?: boolean;
        showAgent?: boolean;
        showCodeChanges?: boolean;
        showUsername?: boolean;
        showSandbox?: boolean;
        showYolo?: boolean;
        showCiStatus?: boolean;
        showSchedules?: boolean;
        showPullRequest?: boolean;
        showCustom?: boolean;
        [key: string]: unknown;
    };
    tabs?: {
        enabled?: boolean;
        sort?: string[];
        hide?: string[];
        [key: string]: unknown;
    };
    updateTerminalTitle?: boolean;
    terminalProgress?: boolean;
    mergeStrategy?: "rebase" | "merge";
    customAgents?: {
        defaultLocalOnly?: boolean;
        [key: string]: unknown;
    };
    ide?: {
        autoConnect?: boolean;
        openDiffOnEdit?: boolean;
        [key: string]: unknown;
    };
    companyAnnouncements?: string[];
    enabledFeatureFlags?: Record<string, boolean>;
    feature_flags?: {
        enabled?: string[];
        [key: string]: unknown;
    };
    skillDirectories?: string[];
    disabledSkills?: string[];
    disabledMcpServers?: string[];
    enabledMcpServers?: string[];
    githubMcpToolsets?: string[];
    githubMcpTools?: string[];
    enableAllGithubMcpTools?: boolean;
    githubMcpInsiders?: boolean;
    dynamicRetrieval?: {
        skills?: boolean;
        mcp?: boolean;
        [key: string]: unknown;
    };
    sandbox?: {
        enabled?: boolean;
        userPolicy?: {
            filesystem?: SandboxPathPolicy;
            network?: SandboxNetworkPolicy;
            seatbelt?: SandboxSeatbeltPolicy;
            experimental?: SandboxExperimentalPolicy;
            [key: string]: unknown;
        };
        addCurrentWorkingDirectory?: boolean;
        sandboxMcpServers?: boolean;
        sandboxLspServers?: boolean;
        allowBypass?: boolean;
        auth?: {
            git?: boolean;
            gh?: boolean;
        };
        allowDevToolAccess?: boolean;
        [key: string]: unknown;
    };
    extensions?: {
        disabledExtensions?: string[];
        mode?: "disabled" | "load_only" | "load_and_augment";
        [key: string]: unknown;
    };
    enabledPlugins?: Record<string, boolean>;
    extraKnownMarketplaces?: ExtraKnownMarketplaces;
    strictKnownMarketplaces?: StrictKnownMarketplaces;
    voice?: {
        enabled?: boolean;
        selectedModel?: string;
        selectedDevice?: {
            name: string;
            occurrence?: number;
        };
        [key: string]: unknown;
    };
    permissions?: ManagedPermissionsSettings;
    /** Enterprise allowlist of MCP servers users may load (managed settings only). */
    allowedMcpServers?: ManagedMcpServerMatcher[];
    /** Enterprise denylist of MCP servers that must never load (managed settings only). */
    deniedMcpServers?: ManagedMcpServerMatcher[];
    /** Enterprise-mandated OpenTelemetry configuration (managed settings only). */
    telemetry?: ManagedTelemetrySettings;
    /** Managed-device remote-control policy (managed settings only). */
    remoteControl?: ManagedRemoteControlSettings;
    copilotUrl?: string;
    showReasoning?: boolean;
    /** Show HH:mm timestamps next to user messages in the timeline. Defaults to true. */
    showTimestamps?: boolean;
    /** Show how long each tool call took (for calls at least 5s) inline in the timeline. Defaults to true. */
    showToolDurations?: boolean;
    disableAllHooks?: boolean;
    hooks?: Record<string, unknown>;
    /** Content-hash keys of individual non-policy hooks disabled via the plugins dashboard. */
    disabledHooks?: string[];
    remoteSessions?: boolean;
    experimental?: boolean;
    logLevel?: "none" | "error" | "warning" | "info" | "debug" | "all" | "default";
}

declare const UserSettings: {
    home: typeof userSettingsConfigHome;
    path: typeof settingsFilePath;
    directoryFiles: (settings?: SettingsStorageContext) => Promise<string[]>;
    directoryFilesWithMetadata: (settings?: SettingsStorageContext) => Promise<{
        file: string;
        mtime: Date;
        birthtime: Date;
    }[]>;
    clearCache: () => void;
    load: (settings: SettingsStorageContext | undefined) => Promise<UserSettings>;
    /**
     * Like {@link UserSettings.load}, but also reports why a present
     * `settings.json` was ignored. When the file cannot be read, parsed, or
     * validated, its values are dropped (recognized `config.json` values are
     * still merged in, as before) and `warning` carries a human-readable
     * message identifying the underlying error, so callers can surface it to the
     * user (e.g. an in-session notification or a startup log) instead of
     * silently discarding their configuration.
     *
     * This deliberately does not log: the core persistence layer must stay free
     * of the logger import (it is loaded into every test's module graph via the
     * setup files, and importing the logger here breaks test logger mocks). The
     * CLI decides how to surface the warning.
     */
    loadWithWarning: (settings: SettingsStorageContext | undefined) => Promise<{
        settings: UserSettings;
        warning?: string;
    }>;
    /**
     * Load only the legacy config.json store (without the settings.json overlay),
     * so callers can detect when a write to settings.json will be shadowed by an
     * unmigrated value in config.json.
     */
    loadLegacyConfig: (settings: SettingsStorageContext | undefined) => Promise<UserSettings | undefined>;
    /**
     * Load only settings.json (without merging in the legacy config.json overlay).
     * Use when callers want the literal contents of the user settings file — for
     * example to compute a write payload that won't accidentally bake in legacy
     * sibling values, or to populate UI state that represents what's actually
     * persisted in settings.json.
     */
    loadSettingsFileOnly: (settings: SettingsStorageContext | undefined) => Promise<UserSettings | undefined>;
    /**
     * Load only settings.json, distinguishing missing-file from parse-failure.
     * Used by write paths that need to refuse the operation when the file
     * exists but is malformed — overwriting in that state would destroy the
     * user's edits. Accepts JSONC (comments + trailing commas), matching the
     * parser the rest of the persistence layer uses.
     *
     * Returns:
     * - `"ok"` — file exists (or is empty/whitespace, treated as `{}`) and
     *   parses as a JSON object. Note: this does NOT run the full
     *   whole-file user-settings validation — bad-but-typed values in unrelated
     *   fields (e.g. a typo'd `logLevel`) must not lock callers out of
     *   `/settings` set/reset for OTHER fields. Callers should validate the
     *   touched top-level subtree (see `validateUserSettingsTopKey`) before
     *   writing, not the whole file.
     * - `"missing"` — `ENOENT` / `ENOTDIR`.
     * - `"invalid"` — file exists and is non-empty but couldn't be parsed
     *   as JSONC (syntax error) or the root isn't an object.
     *
     * Other I/O errors (e.g. `EACCES`, `EISDIR`, `EBUSY`) are rethrown so
     * callers can surface an accurate read-error message rather than
     * misreporting them as "could not be parsed".
     */
    loadSettingsFileForEdit: (settings: SettingsStorageContext | undefined) => Promise<{
        status: "ok";
        settings: UserSettings;
    } | {
        status: "missing";
    } | {
        status: "invalid";
    }>;
    /**
     * Replaces the contents of settings.json with `data`, deleting any
     * top-level keys not present in `data`. Unlike `write` (which merges into
     * the existing file), this is a true-replace operation — needed so the
     * /settings dialog's "open in editor" flow can delete keys.
     *
     * Uses the same locked + atomic + private-mode write path as every
     * other settings write:
     *   - per-key mutex prevents races with concurrent `writeKey` callers,
     *   - tmp + rename ensures readers never see a torn settings.json,
     *   - directory created at `0o700`, file at `0o600`.
     */
    writeAll: (data: UserSettings, settings: SettingsStorageContext | undefined) => Promise<void>;
    /**
     * Atomically apply a batch of top-level key writes/deletes to settings.json.
     *
     * The whole read-mutate-write runs under a single file lock in the Rust
     * layer, so the batch is serialized against other settings writers (e.g.
     * `writeKey`) touching the same file. This is what makes a multi-key write
     * all-or-nothing without a TS-side read-modify-write that could interleave
     * with a concurrent native write and lose changes.
     *
     * `updates` maps each top-level key to its new value; `deleteKeys` lists
     * keys to remove. Returns `"ok"` on success, or `"invalid"` when the
     * existing settings.json could not be parsed (nothing is written), so the
     * caller can refuse to clobber it. Clears the merged-overlay cache on
     * success (handled natively).
     */
    writeSettingsKeys: (updates: Record<string, unknown>, deleteKeys: readonly string[], settings: SettingsStorageContext | undefined) => Promise<"ok" | "invalid">;
    write: (data: UserSettings, subDir?: string, settings?: SettingsStorageContext) => Promise<void>;
    writeKey: (key: keyof UserSettings, value: UserSettings[keyof UserSettings], subDir?: string, settings?: SettingsStorageContext, options?: {
        refuseOnReadFailure?: boolean;
    }) => Promise<void>;
    /**
     * Atomically merges `partial` into the value currently persisted for `key`,
     * read inside the same settings.json write lock the write holds. Unlike
     * {@link writeKey} — which replaces the key with a value the caller computed
     * earlier from a possibly-stale `load()` snapshot (the in-memory cache or a
     * merged multi-file view) — this re-reads the freshest on-disk value inside
     * the critical section so concurrent writers touching different sub-fields
     * of the same object key commute instead of clobbering each other: e.g.
     * setting `extensions.mode` cannot drop another writer's just-persisted
     * `extensions.disabledExtensions`.
     *
     * @returns The value persisted for the key after merging.
     */
    updateKey: <K extends keyof UserSettings>(key: K, partial: Partial<NonNullable<UserSettings[K]>>, subDir?: string, settings?: SettingsStorageContext) => Promise<UserSettings[K]>;
    /**
     * One-time, fire-and-forget cleanup of the legacy `builtInAgents` rubber-duck
     * keys in settings.json. Reads the raw settings file (not the migrated
     * overlay), and if it still carries the legacy keys, persists the migrated
     * shape so the keys are physically dropped. Idempotent and safe to call on
     * every startup. Errors are swallowed — the in-memory migration in `load`
     * keeps the runtime correct regardless.
     */
    migrateLegacyRubberDuckSettingsOnDisk: (settings: SettingsStorageContext | undefined) => Promise<void>;
};

declare function userSettingsConfigHome(settings?: SettingsStorageContext): string;

/** Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. */
declare interface UserSettingsGetResult {
    /** Every known user setting keyed by setting name, each with its effective value, default, and whether it is at the default. */
    settings: Record<string, UserSettingMetadata>;
}

/** Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. */
declare interface UserSettingsSetRequest {
    /** Partial user settings to write, as a free-form object keyed by setting name */
    settings: unknown;
}

/** Outcome of writing user settings. */
declare interface UserSettingsSetResult {
    /** Top-level keys whose write landed in settings.json but is shadowed by a value still present in the legacy config.json (config.json wins on read). The write does not take effect until the legacy value is removed. */
    shadowedKeys: string[];
}

/**
 * A tool permission request that we expect will be presented to the user in some manner.
 *
 * This is distinct from the PermissionRequest type that is passed into the permission service
 * because it provides more clarity based on interactions with rules and session approvals.
 */
declare type UserToolPermissionRequest = {
    toolCallId?: string;
} & (UserCommandsPermissionRequest | WritePermissionRequest | UserMCPPermissionRequest | MemoryPermissionRequest | UserCustomToolPermissionRequest | UserReadPermissionRequest | UserExtensionManagementPermissionRequest | UserFactoryPermissionRequest | UserExtensionPermissionAccessRequest);

/**
 * A response to a user tool permission request.
 *
 * Note that it is generic over the kind of request, so that we can get type narrowing and only
 * handle session approvals that make sense for the request kind we made.
 */
declare type UserToolPermissionRequestResponse<K extends UserToolPermissionRequest["kind"]> = {
    readonly kind: "approve-once";
} | {
    readonly kind: "approve-for-session";
    readonly approval: SessionApprovalFor<K>;
} | {
    readonly kind: "approve-for-location";
    readonly approval: SessionApprovalFor<K>;
    readonly locationKey: string;
} | {
    readonly kind: "reject";
    readonly feedback?: string;
} | {
    readonly kind: "user-not-available";
};

/** The approval to add as a session-scoped rule */
export declare type UserToolSessionApproval = UserToolSessionApprovalCommands | UserToolSessionApprovalRead | UserToolSessionApprovalWrite | UserToolSessionApprovalMcp | UserToolSessionApprovalMemory | UserToolSessionApprovalCustomTool | UserToolSessionApprovalExtensionManagement | UserToolSessionApprovalFactory | UserToolSessionApprovalExtensionPermissionAccess;

/** The approval to add as a session-scoped rule */
declare type UserToolSessionApproval_2 = UserToolSessionApprovalCommands_2 | UserToolSessionApprovalRead_2 | UserToolSessionApprovalWrite_2 | UserToolSessionApprovalMcp_2 | UserToolSessionApprovalMemory_2 | UserToolSessionApprovalCustomTool_2 | UserToolSessionApprovalExtensionManagement_2 | UserToolSessionApprovalFactory_2 | UserToolSessionApprovalExtensionPermissionAccess_2;

/** Session-scoped tool-approval rule for specific shell command identifiers. */
export declare interface UserToolSessionApprovalCommands {
    /** Command identifiers approved by the user */
    commandIdentifiers: string[];
    /** Command approval kind */
    kind: "commands";
}

/** Session-scoped tool-approval rule for specific shell command identifiers. */
declare interface UserToolSessionApprovalCommands_2 {
    /** Command identifiers approved by the user */
    commandIdentifiers: string[];
    /** Command approval kind */
    kind: "commands";
}

/** Session-scoped tool-approval rule for a custom tool, keyed by tool name. */
export declare interface UserToolSessionApprovalCustomTool {
    /** Custom tool approval kind */
    kind: "custom-tool";
    /** Custom tool name */
    toolName: string;
}

/** Session-scoped tool-approval rule for a custom tool, keyed by tool name. */
declare interface UserToolSessionApprovalCustomTool_2 {
    /** Custom tool approval kind */
    kind: "custom-tool";
    /** Custom tool name */
    toolName: string;
}

/** Session-scoped tool-approval rule for extension-management operations, optionally narrowed by operation. */
export declare interface UserToolSessionApprovalExtensionManagement {
    /** Extension management approval kind */
    kind: "extension-management";
    /** Optional operation identifier */
    operation?: string;
}

/** Session-scoped tool-approval rule for extension-management operations, optionally narrowed by operation. */
declare interface UserToolSessionApprovalExtensionManagement_2 {
    /** Extension management approval kind */
    kind: "extension-management";
    /** Optional operation identifier */
    operation?: string;
}

/** Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name. */
export declare interface UserToolSessionApprovalExtensionPermissionAccess {
    /** Extension name */
    extensionName: string;
    /** Extension permission access approval kind */
    kind: "extension-permission-access";
}

/** Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name. */
declare interface UserToolSessionApprovalExtensionPermissionAccess_2 {
    /** Extension name */
    extensionName: string;
    /** Extension permission access approval kind */
    kind: "extension-permission-access";
}

/** Session-scoped factory approval, optionally narrowed by approval key. */
export declare interface UserToolSessionApprovalFactory {
    /** Optional factory operation name or canonical approval key */
    approvalKey?: string;
    /** Factory approval kind */
    kind: "factory";
}

/** Session-scoped factory approval, optionally narrowed by approval key. */
declare interface UserToolSessionApprovalFactory_2 {
    /** Optional factory operation name or canonical approval key */
    approvalKey?: string;
    /** Factory approval kind */
    kind: "factory";
}

/** Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null. */
export declare interface UserToolSessionApprovalMcp {
    /** MCP tool approval kind */
    kind: "mcp";
    /** MCP server name */
    serverName: string;
    /** Optional MCP tool name, or null for all tools on the server */
    toolName: string | null;
}

/** Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null. */
declare interface UserToolSessionApprovalMcp_2 {
    /** MCP tool approval kind */
    kind: "mcp";
    /** MCP server name */
    serverName: string;
    /** Optional MCP tool name, or null for all tools on the server */
    toolName: string | null;
}

/** Session-scoped tool-approval rule for writes to long-term memory. */
export declare interface UserToolSessionApprovalMemory {
    /** Memory approval kind */
    kind: "memory";
}

/** Session-scoped tool-approval rule for writes to long-term memory. */
declare interface UserToolSessionApprovalMemory_2 {
    /** Memory approval kind */
    kind: "memory";
}

/** Session-scoped tool-approval rule for read-only filesystem operations. */
export declare interface UserToolSessionApprovalRead {
    /** Read approval kind */
    kind: "read";
}

/** Session-scoped tool-approval rule for read-only filesystem operations. */
declare interface UserToolSessionApprovalRead_2 {
    /** Read approval kind */
    kind: "read";
}

/** Session-scoped tool-approval rule for filesystem write operations. */
export declare interface UserToolSessionApprovalWrite {
    /** Write approval kind */
    kind: "write";
}

/** Session-scoped tool-approval rule for filesystem write operations. */
declare interface UserToolSessionApprovalWrite_2 {
    /** Write approval kind */
    kind: "write";
}

/**
 * A URL permission request that we expect will be presented to the user in some manner.
 */
declare type UserUrlPermissionRequest = {
    readonly url: string;
    readonly intention: string;
    readonly toolCallId?: string;
    /** Managed policy requires a human response; host auto-approval must not answer this prompt. */
    readonly managedApprovalRequired?: boolean;
    /** See {@link UrlPermissionRequest.redirectedFrom}. */
    readonly redirectedFrom?: string;
    /** See {@link UrlPermissionRequest.requestSandboxBypass}. */
    readonly requestSandboxBypass?: boolean;
    /** See {@link UrlPermissionRequest.requestSandboxBypassReason}. */
    readonly requestSandboxBypassReason?: string;
    readonly autoApproval?: AutoApproval;
};

/**
 * A response to a user URL permission request.
 */
declare type UserUrlPermissionRequestResponse = {
    readonly kind: "approve-once";
    /** True only when a host surfaced this request to a user who approved it. */
    readonly approvedInteractively?: boolean;
} | {
    readonly kind: "approve-for-session";
    readonly domain: string;
} | {
    readonly kind: "approve-permanently";
    readonly domain: string;
} | {
    readonly kind: "reject";
    readonly feedback?: string;
} | {
    readonly kind: "user-not-available";
};

/** Output verbosity level used for supported model calls (e.g. "low", "medium", "high") */
export declare type Verbosity = "low" | "medium" | "high";

/**
 * Output verbosity level for supported models.
 */
declare type Verbosity_2 = (typeof VERBOSITY_LEVELS)[number];

/** Output verbosity level for supported models */
declare type Verbosity_3 = "low" | "medium" | "high";

/**
 * Output verbosity level for supported models.
 * Controls answer detail/length independently from reasoning effort.
 */
declare const VERBOSITY_LEVELS: readonly ["low", "medium", "high"];

/** Current sharing status and shareable GitHub URL for a session. */
declare interface VisibilityGetResult {
    /** Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. */
    shareUrl?: string;
    /** Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). */
    status?: SessionVisibilityStatus;
    /** Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. */
    synced: boolean;
}

/** Desired sharing status for the session. */
declare interface VisibilitySetRequest {
    /** Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. */
    status: SessionVisibilityStatus;
}

/** Effective sharing status and shareable GitHub URL after updating session visibility. */
declare interface VisibilitySetResult {
    /** Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. */
    shareUrl?: string;
    /** Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). */
    status?: SessionVisibilityStatus;
    /** Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. */
    synced: boolean;
}

/** Warning message for timeline display with categorization */
export declare interface WarningData {
    /** Human-readable warning message for display in the timeline */
    message: string;
    /** Optional URL associated with this warning that the user can open in a browser */
    url?: string;
    /** Category of warning (e.g., "subscription", "policy", "mcp") */
    warningType: string;
}

/** Session event "session.warning". Warning message for timeline display with categorization */
declare interface WarningEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Warning message for timeline display with categorization */
    data: WarningData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.warning". */
    type: "session.warning";
}
export { WarningEvent as SessionWarningEvent }
export { WarningEvent }

declare type WildcardEventHandler = (event: SessionEvent) => void | Promise<void>;

/** Valid wire API format values for BYOK configuration. */
declare const WIRE_APIS: readonly ["completions", "responses"];

declare type WireApi = (typeof WIRE_APIS)[number];

/** Working directory and git context at session start */
export declare interface WorkingDirectoryContext {
    /** Base commit of current git branch at session start time */
    baseCommit?: string;
    /** Current git branch name */
    branch?: string;
    /** Current working directory path */
    cwd: string;
    /** Root directory of the git repository, resolved via git rev-parse */
    gitRoot?: string;
    /** Head commit of current git branch at session start time */
    headCommit?: string;
    /** Hosting platform type of the repository (github or ado) */
    hostType?: WorkingDirectoryContextHostType;
    /** Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). */
    pendingGitContext?: boolean;
    /** Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps) */
    repository?: string;
    /** Raw host string from the git remote URL (e.g. "github.com", "mycompany.ghe.com", "dev.azure.com") */
    repositoryHost?: string;
}

/** Hosting platform type of the repository (github or ado) */
export declare type WorkingDirectoryContextHostType = "github" | "ado";

/**
 * Simplified workspace schema for infinite sessions.
 *
 * Key simplifications from POC:
 * - Workspace ID = Session ID (1:1 mapping)
 * - No multiple sessions within a workspace - just a chain of compaction summaries
 * - Unified storage: ~/.copilot/session-state/{session-id}/
 * - Owner/repo stored in metadata for filtering/display
 */
/**
 * Schema for workspace metadata.
 * Stored at: ~/.copilot/session-state/{session-id}/workspace.yaml
 */
declare interface Workspace {
    id: string;
    cwd?: string;
    git_root?: string;
    repository?: string;
    host_type?: "github" | "ado";
    branch?: string;
    name?: string;
    client_name?: string;
    user_named?: boolean;
    summary_count: number;
    created_at?: string;
    updated_at?: string;
    remote_steerable?: boolean;
    mc_task_id?: string;
    mc_session_id?: string;
    mc_last_event_id?: string;
    mc_environment_id?: string;
    chronicle_sync_dismissed?: boolean;
}

declare type WorkspaceContext = WorkspaceMetadataContextUpdate;

declare interface WorkspaceContextInfo {
    name?: string;
    workspacePath: string;
    summaryCount: number;
    filesInWorkspace?: string[];
    checkpoints?: CheckpointInfo[];
}

/** A single changed file and its unified diff. */
declare interface WorkspaceDiffFileChange {
    /** Type of change represented by this file diff. */
    changeType: WorkspaceDiffFileChangeType;
    /** Unified diff content for the file. Empty when the diff was truncated. */
    diff: string;
    /** Whether the diff content was omitted because it exceeded the per-file size limit. */
    isTruncated?: boolean;
    /** Original file path for renamed files. */
    oldPath?: string;
    /** Path to the changed file, relative to the workspace root when the file lives under it. A file changed outside the workspace root keeps a `../`-relative path, or an absolute path when no relative path exists (for example a different Windows drive). */
    path: string;
}

/** Type of change represented by this file diff. */
declare type WorkspaceDiffFileChangeType = "added" | "modified" | "deleted" | "renamed";

/** Diff mode requested by the client. */
declare type WorkspaceDiffMode = "unstaged" | "branch" | "session";

/** Workspace diff result for the requested mode. */
declare interface WorkspaceDiffResult {
    /** Default branch used for a branch diff, when branch mode was requested. */
    baseBranch?: string;
    /** Changed files and their unified diffs. */
    changes: WorkspaceDiffFileChange[];
    /** Whether the requested diff fell back to unstaged changes, either because branch diff failed or session diff was unavailable. */
    isFallback: boolean;
    /** Effective mode used for the returned changes. */
    mode: WorkspaceDiffMode;
    /** Diff mode requested by the client. */
    requestedMode: WorkspaceDiffMode;
    /** Why the session diff could not be produced, when applicable. Set only when `session` mode was requested and `isFallback` is true, so a client can tell the permanent `file-change-tracking-disabled` apart from the transient `session-busy`, which the same request answers once the session settles. Never set for `unstaged` or `branch` mode, and never `unsupported-remote-session`: a remote session's captures live on its own host, so a `session`-mode diff is rejected for one rather than answered with a controller-side fallback. */
    unavailableReason?: HistoryRewindUnavailableReason;
}

/** Workspace file change details including path and operation type */
export declare interface WorkspaceFileChangedData {
    /** Whether the file was newly created or updated */
    operation: WorkspaceFileChangedOperation;
    /** Relative path within the session workspace files directory */
    path: string;
}

/** Session event "session.workspace_file_changed". Workspace file change details including path and operation type */
declare interface WorkspaceFileChangedEvent {
    /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */
    agentId?: string;
    /** Workspace file change details including path and operation type */
    data: WorkspaceFileChangedData;
    /** When true, the event is transient and not persisted to the session event log on disk */
    ephemeral?: boolean;
    /** Unique event identifier (UUID v4), generated when the event is emitted */
    id: string;
    /** ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. */
    parentId: string | null;
    /** ISO 8601 timestamp when the event was created */
    timestamp: string;
    /** Type discriminator. Always "session.workspace_file_changed". */
    type: "session.workspace_file_changed";
}
export { WorkspaceFileChangedEvent as SessionWorkspaceFileChangedEvent }
export { WorkspaceFileChangedEvent }

/** Whether the file was newly created or updated */
export declare type WorkspaceFileChangedOperation = "create" | "update";

declare interface WorkspaceMetadataContextUpdate {
    cwd?: string;
    gitRoot?: string;
    repository?: string;
    hostType?: "github" | "ado";
    branch?: string;
    clientName?: string;
}

/** Compaction summary checkpoint to persist. */
declare interface WorkspacesAddSummaryRequest {
    /** Markdown summary content to persist. */
    content: string;
    /** Summary title shown in checkpoint listings. */
    title: string;
}

/** Persisted summary metadata and refreshed workspace metadata. */
declare interface WorkspacesAddSummaryResult {
    summary?: Record<string, unknown>;
    workspace?: Record<string, unknown>;
    [key: string]: unknown;
}

/** Whether the autopilot objective file exists. */
declare interface WorkspacesAutopilotObjectiveExistsResult {
    /** True when the objective file exists. */
    exists: boolean;
}

/** Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. */
declare interface WorkspacesCheckpoints {
    /** Filename of the checkpoint within the workspace checkpoints directory */
    filename: string;
    /** Checkpoint number assigned by the workspace manager */
    number: number;
    /** Human-readable checkpoint title */
    title: string;
}

/** Relative path and UTF-8 content for the workspace file to create or overwrite. */
declare interface WorkspacesCreateFileRequest {
    /** File content to write as a UTF-8 string */
    content: string;
    /** Relative path within the workspace files directory */
    path: string;
}

/** Result of deleting the autopilot objective file. */
declare interface WorkspacesDeleteAutopilotObjectiveResult {
    /** True when a file was deleted. */
    deleted: boolean;
}

/** Parameters for computing a workspace diff. */
declare interface WorkspacesDiffRequest {
    /** When true, ignore whitespace-only changes (git `--ignore-all-space`). Defaults to false. */
    ignoreWhitespace?: boolean;
    /** Diff mode requested by the client. */
    mode: WorkspaceDiffMode;
}

/** Optional session context used when creating a local workspace. */
declare interface WorkspacesEnsureRequest {
    /** Opaque workspace context supplied by the session host. */
    context?: unknown;
}

/** Current workspace metadata for the session, including its absolute filesystem path when available. */
declare interface WorkspacesGetWorkspaceResult {
    /** Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). */
    path?: string;
    /** Current workspace metadata, or null if not available */
    workspace: {
        branch?: string;
        chronicle_sync_dismissed?: boolean;
        client_name?: string;
        created_at?: string;
        cwd?: string;
        git_root?: string;
        host_type?: WorkspacesWorkspaceDetailsHostType;
        id: string;
        mc_last_event_id?: string;
        mc_session_id?: string;
        mc_task_id?: string;
        name?: string;
        remote_steerable?: boolean;
        repository?: string;
        summary_count?: number;
        updated_at?: string;
        user_named?: boolean;
    } | null;
}

/** Workspace checkpoints in chronological order; empty when the workspace is not enabled. */
declare interface WorkspacesListCheckpointsResult {
    /** Workspace checkpoints in chronological order. Empty when workspace is not enabled. */
    checkpoints: WorkspacesCheckpoints[];
}

/** Relative paths of files stored in the session workspace files directory. */
declare interface WorkspacesListFilesResult {
    /** Relative file paths in the workspace files directory */
    files: string[];
}

/** Autopilot objective file content, or null when missing. */
declare interface WorkspacesReadAutopilotObjectiveResult {
    /** Autopilot objective file content, or null when missing. */
    content: string | null;
}

/** Checkpoint number to read. */
declare interface WorkspacesReadCheckpointRequest {
    /** Checkpoint number to read */
    number: number;
}

/** Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. */
declare interface WorkspacesReadCheckpointResult {
    /** Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing */
    content: string | null;
}

/** Relative path of the workspace file to read. */
declare interface WorkspacesReadFileRequest {
    /** Relative path within the workspace files directory */
    path: string;
}

/** Contents of the requested workspace file as a UTF-8 string. */
declare interface WorkspacesReadFileResult {
    /** File content as a UTF-8 string */
    content: string;
}

/** Pasted content to save as a UTF-8 file in the session workspace. */
declare interface WorkspacesSaveLargePasteRequest {
    /** Pasted content to save as a UTF-8 file */
    content: string;
}

/** Descriptor for the saved paste file, or null when the workspace is unavailable. */
declare interface WorkspacesSaveLargePasteResult {
    /** Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions) */
    saved: {
        filePath: string;
        filename: string;
        sizeBytes: number;
    } | null;
}

/** Rollback point for local workspace summaries. */
declare interface WorkspacesTruncateSummariesRequest {
    /** Number of newest summaries to keep. */
    keepCount: number;
}

/** Public-facing workspace metadata for this session, or null if the session has no associated workspace. Excludes runtime-internal fields (GitHub IDs, summary count, internal flags). */
declare type WorkspaceSummary = {
    branch?: string;
    created_at?: string;
    cwd?: string;
    git_root?: string;
    host_type?: WorkspaceSummaryHostType;
    id: string;
    name?: string;
    repository?: string;
    updated_at?: string;
    user_named?: boolean;
} | null;

/** Repository host type, if known */
declare type WorkspaceSummaryHostType = "github" | "ado";

/** Workspace metadata fields to update. */
declare interface WorkspacesUpdateMetadataRequest {
    /** Opaque workspace context supplied by the session host. */
    context?: unknown;
    /** Optional workspace display name override. */
    name?: string;
}

/** Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. */
declare type WorkspacesWorkspaceDetailsHostType = "github" | "ado";

/** Autopilot objective file content to persist. */
declare interface WorkspacesWriteAutopilotObjectiveRequest {
    /** Autopilot objective file content. */
    content: string;
}

/** Result of writing the autopilot objective file. */
declare interface WorkspacesWriteAutopilotObjectiveResult {
    /** Filesystem operation performed. */
    operation: string;
}

declare type WorktreeBaseRef = "head" | "defaultBranch";

/**
 * A permission request for writing to new or existing files.
 */
declare type WritePermissionRequest = {
    readonly kind: "write";
    /** The intention of the edit operation, e.g. "Edit file" or "Create file" */
    readonly intention: string;
    /** The name of the file being edited */
    readonly fileName: string;
    /** The diff of the changes being made */
    readonly diff: string;
    /** Whether the UI can offer session-wide approval for file write operations */
    readonly canOfferSessionApproval: boolean;
    /** The new file contents (for IDE diff view) */
    readonly newFileContents?: string;
    /**
     * True when a built-in file tool (`apply_patch` / `str_replace_editor`) is
     * asking to write a path the sandbox filesystem policy would block, and the
     * host opted in via `sandbox.allowBypass`. This is a request, not a grant:
     * the write happens unsandboxed only if the user approves this permission
     * request. Hosts should highlight the elevated risk in the approval UI.
     */
    readonly requestSandboxBypass?: boolean;
    /**
     * Justification for the sandbox-bypass request ({@link requestSandboxBypass}).
     * Only meaningful when `requestSandboxBypass` is true.
     */
    readonly requestSandboxBypassReason?: string;
    /** Managed policy requires an explicit human response for this write. */
    readonly managedApprovalRequired?: boolean;
    readonly autoApproval?: AutoApproval;
};

export { }
