import type { CreateMessageResultWithTools as CreateMessageResultWithTools_2 } from '@modelcontextprotocol/sdk/types.js';
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 { 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 { PermissionRequestHooksRunResult } from './sharedApi/runtime-generated';
import type { PreparedStrReplaceEditorInput } from '../core/sharedApi/runtime-generated';
import type * as RuntimeNative from '../sharedApi/runtime-generated';
import type * as RuntimeNative_2 from '../core/sharedApi/runtime-generated';
import type * as RuntimeNative_3 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 * as stream from 'stream';
import type { ToolExecutionResult } from '../core/sharedApi/runtime-generated';
import { z } from 'zod';
import * as z_2 from 'zod';

/** Turn abort information including the reason for termination */
declare interface AbortData {
    /** Finite reason code describing why the current turn was aborted */
    reason: AbortReason_3;
}

export declare type AbortEvent = WireTypes.AbortEvent;

/** Session event "abort". Turn abort information including the reason for termination */
declare interface AbortEvent_2 {
    /** 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";
}

export declare const AbortReason: {
    readonly UserInitiated: "user_initiated";
    readonly RemoteCommand: "remote_command";
    readonly UserAbort: "user_abort";
};

/** Finite reason code describing why the current turn was aborted */
declare type AbortReason_2 = "user_initiated" | "remote_command" | "user_abort";

/** Finite reason code describing why the current turn was aborted */
declare type AbortReason_3 = "user_initiated" | "remote_command" | "user_abort";

/** 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: RunnerLogger;
};

/** 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. */
declare type AdaptiveThinkingSupport = "unsupported" | "optional" | "required";

/**
 * 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_2 = "unsupported" | "optional" | "required";

declare type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise<void>;

declare type AgentAction = (typeof AgentActions)[number];

declare const AgentActions: readonly ["fix", "fix-pr-comment", "task"];

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_2 | 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";

/** 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 agent context caching, 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>;
    /** Shuts down all cached agent contexts. */
    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;
}

/** Custom 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>;
    /** Preferred model id for this agent. When omitted, inherits the outer agent's model. */
    model?: string;
    /** Unique identifier of the custom agent */
    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;
    /** 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";

/** Custom agents available to the session. */
declare interface AgentList {
    /** Available custom 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;
}

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;
    /**
     * 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;
}

export declare type AgentMode = WireTypes.AgentMode;

/**
 * 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;
}

/** 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[];
}

/**
 * A background agent task (subagent running in background mode).
 */
export declare type AgentTask = {
    type: "agent";
    id: string;
    /** Tool call ID for correlating session events with this agent. */
    toolCallId: string;
    description: string;
    status: BackgroundTaskStatus;
    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;
    /** 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;
}

/**
 * Progress for a background agent task, derived from session events.
 */
export declare type AgentTaskProgress = {
    type: "agent";
    /** Recent tool execution events converted to display lines. */
    recentActivity: ProgressLine[];
    /** The most recent intent reported by the agent. */
    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;
    /** 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;
}

/**
 * The source that triggered allow-all / yolo mode.
 */
declare type AllowAllSource = "cli_flag" | "slash_command" | "autopilot_confirmation" | "rpc";

declare const alwaysApproveRequestPermissionFn: RequestPermissionFn;

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_2;
    /** Authentication host. */
    host: string;
    /** API-key authentication for non-GitHub LLM providers (e.g. when running BYOM-style). */
    type: "api-key";
}

/** Options for experimentation staff status overrides */
declare interface AppInsightsTelemetryOptions {
    /** Whether the persisted state has `staff: true` */
    configStaff?: boolean;
    /** Whether streamer mode is active (suppresses staff for experiments) */
    streamerMode?: boolean;
}

declare class AppInsightsTelemetryService extends TelemetryService {
    readonly authManager: AuthManager;
    private readonly authCallback;
    private readonly stateHandle;
    private readonly clientName;
    private readonly clientType;
    private clientInfo;
    /**
     * Optional host-editor attribution override for legacy `copilot_v0` usage
     * events. Set when the CLI is driven by another editor over ACP (e.g. a
     * JetBrains IDE) so usage is attributed to that editor rather than the CLI.
     */
    private usageMetricsAttribution?;
    private readonly configStaff;
    private readonly streamerMode;
    private queue?;
    private restrictedQueue?;
    private copilotUser?;
    constructor(authManager: AuthManager, clientName: string, clientType: string, options?: AppInsightsTelemetryOptions);
    /**
     * Override the host-editor attribution applied to legacy `copilot_v0` usage
     * events. Pass `undefined` to restore the default CLI attribution.
     */
    setUsageMetricsAttribution(attribution: UsageMetricsAttribution | undefined): void;
    /** Check if user is staff based on the `is_staff` flag from the Copilot user response */
    private isStaff;
    /**
     * Check if user should be treated as staff for experimentation purposes.
     * Combines API org check with config flag, but suppressed in streamer mode.
     */
    private isStaffForExperimentation;
    /** Check if restricted telemetry should be sent for eligible users who have not opted out. */
    shouldSendRestrictedTelemetry(): boolean;
    private createTelemetryEventEnvelope;
    private enqueueEnvelope;
    sendTelemetryEvent(eventName: string, properties?: TelemetryProperties, measurements?: TelemetryMeasurements, tags?: TelemetryTags): void;
    sendHydroEvent(event: HydroEvent, options?: HydroTelemetryOptions): void;
    dispose(): Promise<void>;
    private updateCopilotUser;
    /** Creates new telemetry queues with the given endpoint URL and drains pending events. */
    private updateQueues;
    private emitPendingBufferOverflowDiagnostic;
    private getTags;
    private createHostSnapshot;
}

declare type AskUserRequest = {
    question: string;
    choices?: string[];
    allowFreeform?: boolean;
    toolCallId?: string;
};

declare type AskUserResponse = {
    answer: string;
    wasFreeform: boolean;
    dismissed?: boolean;
};

declare const AskUserToolName = "ask_user";

declare type AssessedCommand = {
    readonly identifier: string;
    readOnly: boolean;
};

/** 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 */
declare interface AssistantIdleData {
    /** True when the preceding agentic loop was cancelled via abort signal */
    aborted?: boolean;
}

export declare type AssistantIdleEvent = WireTypes.AssistantIdleEvent;

/** 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 */
declare interface AssistantIdleEvent_2 {
    /** 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 */
declare interface AssistantIntentData {
    /** Short description of what the agent is currently doing or planning to do */
    intent: string;
}

export declare type AssistantIntentEvent = WireTypes.AssistantIntentEvent;

/** Session event "assistant.intent". Agent intent description for current activity or plan */
declare interface AssistantIntentEvent_2 {
    /** 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 */
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;
    /** 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;
    /** 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 */
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;
}

export declare type AssistantMessageDeltaEvent = WireTypes.AssistantMessageDeltaEvent;

/** Session event "assistant.message_delta". Streaming assistant message delta for incremental response updates */
declare interface AssistantMessageDeltaEvent_2 {
    /** 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";
}

export declare type AssistantMessageEvent = WireTypes.AssistantMessageEvent;

/** Session event "assistant.message". Assistant response containing text content, optional tool requests, and interaction metadata */
declare interface AssistantMessageEvent_2 {
    /** 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_3 = {
    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 */
declare interface AssistantMessageServerTools {
    advisorModel?: string;
    functionCallNamespaces?: Record<string, string>;
    items?: unknown[];
    provider: string;
    rawContentBlocks?: unknown[];
}

/** Streaming assistant message start metadata */
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;
}

export declare type AssistantMessageStartEvent = WireTypes.AssistantMessageStartEvent;

/** Session event "assistant.message_start". Streaming assistant message start metadata */
declare interface AssistantMessageStartEvent_2 {
    /** 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 */
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. */
declare type AssistantMessageToolRequestType = "function" | "custom";

/** Assistant reasoning content for timeline display with complete thinking text */
declare interface AssistantReasoningData {
    /** The complete extended thinking text from the model */
    content: string;
    /** Unique identifier for this reasoning block */
    reasoningId: string;
}

/** Streaming reasoning delta for incremental extended thinking updates */
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;
}

export declare type AssistantReasoningDeltaEvent = WireTypes.AssistantReasoningDeltaEvent;

/** Session event "assistant.reasoning_delta". Streaming reasoning delta for incremental extended thinking updates */
declare interface AssistantReasoningDeltaEvent_2 {
    /** 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";
}

export declare type AssistantReasoningEvent = WireTypes.AssistantReasoningEvent;

/** Session event "assistant.reasoning". Assistant reasoning content for timeline display with complete thinking text */
declare interface AssistantReasoningEvent_2 {
    /** 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 */
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;
}

export declare type AssistantServerToolProgressEvent = WireTypes.AssistantServerToolProgressEvent;

/** 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 */
declare interface AssistantServerToolProgressEvent_2 {
    /** 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 */
declare interface AssistantStreamingDeltaData {
    /** Cumulative total bytes received from the streaming response so far */
    totalResponseSizeBytes: number;
}

export declare type AssistantStreamingDeltaEvent = WireTypes.AssistantStreamingDeltaEvent;

/** Session event "assistant.streaming_delta". Streaming response progress with cumulative byte count */
declare interface AssistantStreamingDeltaEvent_2 {
    /** 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 */
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;
}

export declare type AssistantToolCallDeltaEvent = WireTypes.AssistantToolCallDeltaEvent;

/** Session event "assistant.tool_call_delta". Streaming tool-call input delta for incremental tool-call updates */
declare interface AssistantToolCallDeltaEvent_2 {
    /** 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 */
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;
}

export declare type AssistantTurnEndEvent = WireTypes.AssistantTurnEndEvent;

/** Session event "assistant.turn_end". Turn completion metadata including the turn identifier */
declare interface AssistantTurnEndEvent_2 {
    /** 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 */
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 */
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 */
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;
}

export declare type AssistantTurnStartEvent = WireTypes.AssistantTurnStartEvent;

/** Session event "assistant.turn_start". Turn initialization metadata including identifier and interaction tracking */
declare interface AssistantTurnStartEvent_2 {
    /** 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 */
declare type AssistantUsageApiEndpoint = "/chat/completions" | "/v1/messages" | "/responses" | "ws:/responses";

/** Per-request cost and usage data from the CAPI copilot_usage response field */
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 */
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 */
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;
    /** 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;
    /** Model identifier used for this API call */
    model: string;
    /** 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;
    /** 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;
}

export declare type AssistantUsageEvent = WireTypes.AssistantUsageEvent;

/** Session event "assistant.usage". LLM API call usage metrics including tokens, costs, quotas, and billing information */
declare interface AssistantUsageEvent_2 {
    /** 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. */
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;
}

export declare type Attachment = WireTypes.Attachment;

/** A user message attachment — a file, directory, code selection, blob, GitHub reference, GitHub-anchored pointer, or extension-supplied context payload */
declare type Attachment_2 = 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_3 = 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";
}

/** 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";
}

/** 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";
}

/** 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";
}

/** 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 */
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;
}

/** 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;
}

/** 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;
}

/** 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;
}

/** 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) */
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;
}

/** 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 */
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;
}

/** 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;
}

/** 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;
}

/** 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;
}

/** 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) */
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;
}

/** 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";
}

/** 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 */
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 */
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 */
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;
}

export declare type AudioContent = WireTypes.AudioContent;

declare interface AudioContent_2 extends BaseContentBlock {
    type: "audio";
    data: string;
    mimeType: string;
}

declare type AuthCallback = (authInfo: AuthInfo | null, token?: string) => void | Promise<void>;

/**
 * Minimal interface for subscribing to authentication state changes.
 * Satisfied by AuthManager — avoids coupling consumers to the full class.
 */
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 featureFlags;
    private authInfoWithTokenPromise;
    private userSwitchAuthCachePromise;
    private authCallbacks;
    private config;
    private _lastAuthErrors;
    /** Identifier of the backing Rust AuthManager instance that owns all auth state. */
    private readonly rustInstanceId;
    constructor(featureFlags?: FeatureFlags, config?: AuthManagerConfig);
    /**
     * Release the native AuthManager instance owned by this shim. Idempotent;
     * the {@link FinalizationRegistry} runs the same release on GC if this is
     * never called.
     */
    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;
    /** Builds the defined subset of process.env as the env map passed to Rust. */
    private buildEnv;
    /**
     * Reads the `storeTokenPlaintext` flag the Rust orchestration consults when
     * deciding whether to prefer the plaintext state-file token over a stale
     * keychain entry. The OLD TypeScript orchestration reached this flag through
     * `TokenStore.getToken(host, login)` / `getAnyToken()` calls that passed no
     * settings, so it always resolved against the DEFAULT config directory
     * (`UserSettings.load(undefined)`) regardless of any custom settings this manager
     * was constructed with. We preserve that exact behavior here — reading fresh
     * per call, against the default directory — and default to `false` on any
     * failure, matching `UserSettings.load`'s own swallow-and-default semantics.
     */
    private getStoreTokenPlaintext;
    /**
     * Mirrors the Rust instance's last auth errors into the TS-side cache so the
     * synchronous {@link lastAuthErrors}/{@link lastAuthErrorDetails} getters can
     * surface them. The Rust runtime returns each error as a JSON-encoded
     * {@link AuthValidationError} (`{ message, githubMessage? }`), so we parse the
     * entries back into structured objects; a non-JSON entry is treated as a bare
     * message for resilience.
     */
    private syncLastAuthErrors;
    /**
     * 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.
     *
     * @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 an authentication change callback
     * @param callback The callback to remove
     */
    removeAuthCallback(callback: AuthCallback): void;
    /**
     * Notify all registered callbacks of auth state change.
     * Callbacks are invoked fire-and-forget.
     * @param authInfo Current auth info (null for logged out)
     * @param token Optional token
     */
    private notifyAuthChange;
    /**
     * Resolves auth info via the Rust runtime, updating the Rust-owned cache,
     * the TS mirror, and the registered callbacks.
     */
    private loadAuthInfo;
    /**
     * Returns the current auth info, waiting for the initial load if needed.
     * @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 reused until the user-switch auth cache is invalidated.
     * @returns List of available auth options for the user switcher, along with the token if available.
     */
    getAllAuthAvailableForUserSwitch(): Promise<AuthInfoWithToken[]>;
    private invalidateUserSwitchAuthCache;
    /**
     * Re-fetches the Copilot user info for the current auth and notifies callbacks.
     * Useful after actions that change the user's subscription status.
     * @returns Updated auth info, or null if no auth is available.
     */
    refreshCopilotUser(): Promise<AuthInfo | null>;
    /**
     * Logs in the user with the provided credentials, persisting them via the
     * Rust runtime, then notifies callbacks with the resolved auth info.
     * @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.
     * @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, then re-reads the current
     * auth state and fans out to registered TS callbacks. Used by the user
     * switcher / {@link accountApi}, 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>;
    /**
     * Re-reads the current auth state from the Rust instance and fans out to
     * registered TS callbacks. Used after {@link logoutUser} mutates auth state
     * directly through the Rust instance, so TS subscribers registered via
     * {@link onAuthChange} stay coherent with the dual call path.
     */
    private syncFromRustAndNotify;
}

/**
 * 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 interface AuthorFactoryApi {
    author(input: unknown): Promise<ToolResultExpanded>;
}

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;
};

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). */
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;
};

/** 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 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;
};

export declare type AutoModeResolvedData = WireTypes.AutoModeResolvedData;

/** 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. */
declare interface AutoModeResolvedData_2 {
    /** 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;
    /** Classifier confidence for the predicted label, when available */
    confidence?: number;
    /** 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;
}

export declare type AutoModeResolvedEvent = WireTypes.AutoModeResolvedEvent;

/** 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. */
declare interface AutoModeResolvedEvent_2 {
    /** 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_2;
    /** 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 */
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.
 */
export 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 {@link REFRESH_LEAD_TIME_MS}
 * 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 stateJson;
    private currentAuthInfo?;
    private inflight?;
    /**
     * Per-session cached Auto Intent resolution, keyed by `sessionId`, so each session
     * classifies its own first prompt instead of inheriting the first session's decision.
     * Later prompts in the same session reuse it. Cleared on token change and on disposal.
     */
    private intentCache;
    /** In-flight `/predict` per `sessionId`, so concurrent callers in one session share it. */
    private intentInflight;
    /**
     * Per-session `IntentSessionState` blob (JSON), keyed by `sessionId`: the one-shot latch
     * plus the multi-turn drift schedule for one session's conversation. Threaded through the
     * native intent calls rather than the process-global `stateJson`. Absent = first prompt.
     */
    private intentSessionState;
    /**
     * Per-session dispatch marker for the current in-flight `/predict`. Dropped on disposal /
     * token change so a later completion fails {@link isCurrentIntentDispatch} and bails.
     */
    private intentDispatch;
    /**
     * Bumped on token change/clear. A `/predict` captures it at dispatch and only writes its
     * result if unchanged, so a post-refresh completion can't repopulate a stale-token result.
     */
    private intentGeneration;
    private listeners;
    /** Pending proactive-refresh timer, if scheduled. Cleared on refresh, clear, and dispose. */
    private refreshTimer?;
    /** Args from the most recent {@link resolve} call, reused to drive proactive refreshes. */
    private lastResolveArgs?;
    /**
     * 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 synchronously 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;
    /**
     * The model a specific SDK session should use: its own token-matched Auto Intent
     * decision when cached, else the pristine standard pick. Never returns another
     * session's shared last-writer refinement, so a session that hasn't classified
     * (e.g. a standalone compaction turn) doesn't inherit it.
     */
    private sessionModelOrStandard;
    /**
     * Choose the model for a `cached` resolve plan. See {@link sessionModelOrStandard};
     * the pristine standard falls back to the plan's effective `modelId` only for legacy
     * plans that predate `standardModelId`.
     */
    private cachedPlanModel;
    /**
     * 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>;
    /**
     * 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 this session's own {@link intentSessionState} blob (advanced
     * natively in `resolveIntentStart`): 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: RunnerLogger;
        prompt: string;
        hasImage: boolean;
        multiTurnRoutingEnabled?: boolean;
    }): Promise<AutoIntentResolveResult | undefined>;
    /**
     * Whether the prediction that captured `generation` + `dispatch` for `key` is still
     * active: the shared token hasn't changed and the session hasn't been forgotten since.
     */
    private isCurrentIntentDispatch;
    /**
     * Gate for multi-turn drift routing. Flag off: strip `multiTurnJson` so the
     * drift machine never engages (legacy once-per-token latch). Flag on but the
     * server sent no policy: inject a default so the runtime applies its client
     * defaults. A policy the server does send (including `enabled: false`) is
     * passed through untouched.
     */
    private gateMultiTurn;
    private doResolveIntent;
    private doResolve;
    /**
     * Drop all per-session Auto Intent state. Called on token change (acquire/refresh) or
     * clear, so every session re-classifies its first prompt against the fresh token.
     */
    private clearIntentCache;
    /**
     * Drop a single SDK session's cached Auto Intent state + any in-flight prediction. Call on
     * {@link Session} disposal. Dropping the dispatch marker also cancels an in-flight prediction:
     * if it completes later it fails {@link isCurrentIntentDispatch} and bails.
     */
    forgetIntentSession(sessionId: string): void;
    /** Drop the cached session and clear the token from {@link settings}. */
    clear(settings?: RuntimeSettings): 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): 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 blob 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 {@link REFRESH_LEAD_TIME_MS} 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;
    /** Cancel the pending proactive-refresh timer, if any. */
    private cancelProactiveRefresh;
}

declare type AutoModeSessionResult = {
    sessionToken: string;
    selectedModel: string;
    availableModels: string[];
    expiresAt?: number;
    discountPercent?: number;
};

/** Auto mode switch completion notification */
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;
}

export declare type AutoModeSwitchCompletedEvent = WireTypes.AutoModeSwitchCompletedEvent;

/** Session event "auto_mode_switch.completed". Auto mode switch completion notification */
declare interface AutoModeSwitchCompletedEvent_2 {
    /** 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 */
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;
}

export declare type AutoModeSwitchRequestedEvent = WireTypes.AutoModeSwitchRequestedEvent;

/** Session event "auto_mode_switch.requested". Auto mode switch request notification requiring user approval */
declare interface AutoModeSwitchRequestedEvent_2 {
    /** 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 */
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);
}

declare const AUTOPILOT_ASK_USER_RESPONSE = "The user is not available to respond and will review your work later. Work autonomously and make good decisions. If the request is genuinely ambiguous or unresolvable, stop and call task_complete summarizing the ambiguity rather than proceeding on an unfounded assumption.";

/**
 * Message sent to the agent when session goes idle without task completion.
 * Used by both interactive mode (app.tsx) and prompt mode (promptMode.ts).
 */
declare const AUTOPILOT_CONTINUATION_MESSAGE: string;

/** Autopilot objective state file operation details indicating what changed */
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";
}

/** The type of operation performed on the autopilot objective state file */
declare type AutopilotObjectiveChangedOperation = "create" | "update" | "delete";

/** Current autopilot objective status, if one exists */
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;
}

declare interface AutopilotObjectiveMutationResult {
    readonly state: AutopilotObjectiveState;
    readonly previous?: AutopilotObjectiveState;
}

declare type AutopilotObjectiveOrigin = "objective" | "user" | null;

declare class AutopilotObjectiveRegistry implements AutopilotObjectiveContinuationProvider {
    private readonly session;
    private state;
    private nextId;
    private disposed;
    private readyResolved;
    private writeQueue;
    private readonly initialization;
    private readonly unsubscribeShutdown;
    private readonly unsubscribeTaskComplete;
    private readonly unsubscribeModeChanged;
    private readonly unsubscribeTurnStart;
    private readonly unsubscribeUsage;
    private completionEligibleObjectiveId;
    constructor(session: AutopilotObjectiveRegistrySession);
    ready(): Promise<void>;
    flushPendingWrites(): Promise<void>;
    isReady(): boolean;
    getState(): AutopilotObjectiveState | undefined;
    set(objectiveInput: string): Promise<AutopilotObjectiveMutationResult | {
        error: string;
    }>;
    pause(reason?: string): Promise<AutopilotObjectiveMutationResult | {
        error: string;
    }>;
    resume(): 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 recordAssistantTurnStarted;
    private recordUsage;
    private handleModeChanged;
    private restoreInteractiveModeIfObjectiveOwned;
    private getStorageUnavailableError;
    private hasStorage;
    private persistSnapshotSafely;
    private emitOutcomeTelemetry;
    private persistSnapshot;
    private assertActive;
}

declare type AutopilotObjectiveRegistrySession = Pick<Session, "currentMode" | "emit" | "getAutopilotObjectivePath" | "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;
    readonly createdAt: string;
    readonly updatedAt: string;
    readonly completionSummary?: string;
    readonly pauseReason?: string;
}

declare type AutopilotObjectiveStatus = "active" | "paused" | "completed";

/**
 * 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[];
    defaultReasoningEffort?: 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;
};

/**
 * Unified type for tracked tasks, discriminated by `type` field.
 */
export declare type BackgroundTask = ShellTask | AgentTask;

/**
 * Discriminated union of progress information for background tasks.
 */
export declare type BackgroundTaskProgress = AgentTaskProgress | ShellTaskProgress;

/** Empty payload for `session.background_tasks_changed`, indicating background task state changed. */
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";
}

/**
 * Status of a background task (agent or shell).
 */
export declare type BackgroundTaskStatus = "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>;
}

export declare abstract class BaseLogger implements RunnerLogger {
    protected logLevel?: LogLevel;
    protected debugEnvironmentVariables?: string[];
    private secretFilter;
    constructor(logLevel?: LogLevel, debugEnvironmentVariables?: string[]);
    filterSecrets(messageOrError: string | Error): string | Error;
    /**
     * Returns true if the log level is not set, or the log level is set and the level is enabled.
     */
    shouldLog(level: LogLevel): boolean;
    isDebug(): boolean;
    abstract log(message: string): void;
    abstract info(message: string): void;
    abstract debug(message: string): void;
    abstract notice(message: string | Error): void;
    abstract warning(message: string | Error): void;
    abstract error(message: string | Error): void;
    abstract startGroup(name: string, level?: LogLevel): void;
    abstract endGroup(level?: LogLevel): void;
}

/**
 * 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 */
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 declare type BinaryAssetReference = WireTypes.BinaryAssetReference;

/** A reference to binary data persisted once on a session.binary_asset event and shared by id */
declare interface BinaryAssetReference_2 {
    /** 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. */
declare type BinaryAssetReferenceType = "image" | "resource";

/**
 * Per-session store of binary-asset bytes, keyed by content-addressed id. Used
 * to de-duplicate large base64 payloads (images/resources) that would otherwise
 * be persisted inline on multiple events (e.g. a tool image that also appears in
 * a preToolUse hook's input). Bytes are interned once, emitted on a single
 * `session.binary_asset` event, and referenced by id elsewhere.
 *
 * The map is append-only for the session lifetime (no GC): a compacted-away
 * asset can legitimately reappear (re-read / re-reference), and content-hash ids
 * mean a re-encounter re-points at the surviving entry rather than re-inlining.
 */
declare class BinaryAssetRegistry {
    private readonly assets;
    /** True if bytes for this asset id are already tracked. */
    has(assetId: string): boolean;
    /**
     * Registers an asset's canonical bytes/metadata. Idempotent and
     * conflict-safe: a second registration for the same id keeps the existing
     * entry (assets are content-addressed, so a matching id implies matching
     * bytes; a divergent payload is treated as a no-op rather than overwriting
     * good data).
     */
    register(asset: SessionBinaryAssetEvent["data"]): void;
    /** Returns the base64 data for an asset id, or undefined if not tracked. */
    getData(assetId: string): string | undefined;
}

/** Binary asset type discriminator. Use "image" for images and "resource" otherwise. */
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;
};

export declare type BinaryResult = WireTypes.BinaryResult;

export declare type BlobAttachment = WireTypes.BlobAttachment;

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;
}

/**
 * Builds the `providerAndModel` string for BYOM (custom provider) sessions,
 * encoding reasoning options when set so the native model setting parser can
 * surface them as client options.
 */
export declare function buildByomProviderAndModel(model: string, reasoningEffort: string | undefined, reasoningSummary: ReasoningSummary_3 | undefined): string;

declare const buildLargeOutputOptions: (sessionFs?: SessionFs, settings?: {
    enabled?: boolean;
    maxSizeBytes?: number;
    outputDir?: string;
}, grepToolName?: string) => LargeOutputOptions;

declare function buildToolCallbackOptions(client: Client, settings: RuntimeSettings_2, tools: readonly Pick<ToolMetadata, "name" | "description">[], abortSignal?: AbortSignal, sessionFs?: SessionFs): Promise<Omit<ToolCallbackOptions, "toolCallId">>;

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. */
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";
}

/** 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. */
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";
}

/** 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. */
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. */
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. */
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. */
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. */
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";
}

/** Durable record that a canvas instance was closed, superseding a prior instance_recorded during resume replay. */
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. */
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. */
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. */
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 */
declare interface CapabilitiesChangedData {
    /** UI capability changes */
    ui?: CapabilitiesChangedUI;
}

export declare type CapabilitiesChangedEvent = WireTypes.CapabilitiesChangedEvent;

/** Session event "capabilities.changed". Session capability change notification */
declare interface CapabilitiesChangedEvent_2 {
    /** 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 */
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. 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.
 */
export declare interface CapiSessionOptions {
    /**
     * 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;
}

/** Options scoped to the built-in CAPI (Copilot API) provider. */
declare interface CapiSessionOptions_2 {
    /** 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;
}

/** Client name identifying the Copilot Cloud Agent across all entrypoint versions. */
export declare const CCA_CLIENT_NAME = "github/copilot-cloud-agent";

/**
 * Feature flag name for routing the code_review tool through the TypeScript
 * Autofind engine (`run-ccr` mode) instead of the Go binary.
 *
 * Off by default. See issues github/agents#1023 and github/agents#1039.
 */
declare const CCA_USE_TS_AUTOFIND_FF_NAME = "copilot_swe_agent_cca_use_ts_autofind";

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;
}

/**
 * Information about a checkpoint for display in the prompt.
 */
declare interface CheckpointInfo {
    /** Checkpoint number (1-indexed) */
    number: number;
    /** Title of the checkpoint */
    title: string;
    /** Filename of the checkpoint (e.g., "001-plan-design.md") */
    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. */
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. */
declare type CitationLocation = CitationLocationChar | CitationLocationPage | CitationLocationBlock;

/** A content-block range within a structured source document. */
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. */
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. */
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. */
declare type CitationProvider = "anthropic" | "openai" | "client";

/** A single citation occurrence linking a span of generated text to a supporting source. */
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. */
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. */
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. */
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 const claudeModelSupportsToolSearch: (model: string) => boolean;

declare const cleanupTempFiles: () => Promise<void>;

/** Clears stale `deferLoading` on every tool in place when tool search is disabled. */
declare function clearAllDeferral(tools: Tool[]): void;

/**
 * Clears `deferLoading` on tools that a custom agent listed in its `tools`
 * array. When a custom agent specifies tools by name (not wildcard `"*"`),
 * those tools are made fully visible to the model by default — deferring
 * them behind tool search is counterproductive because the model doesn't
 * know to search for tools the agent already said it needs.
 *
 * Supports exact names, namespaced names (`ado/wit_get_work_item`), and
 * wildcard namespace patterns (`ado/*`).
 *
 * Agents can opt back into deferral by setting `deferredToolLoading: true`
 * (YAML) / `deferred-tool-loading: true` (Markdown frontmatter), in which
 * case this function is a no-op and `markToolsAsDeferred`'s decisions stand.
 *
 * @param tools - The mutable array of tools (modified in place)
 * @param customAgent - The custom agent whose tool list and opt-in flag are checked
 */
declare function clearDeferralForAgentTools(tools: Tool[], customAgent: {
    tools?: string[] | null;
    deferredToolLoading?: boolean;
} | undefined): void;

export declare const CLI_CLIENT_NAME = "github/cli";

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>;
}

/**
 * Client information for telemetry events, matching Hydro's ClientInfo entity.
 */
declare interface ClientInfo {
    cli_version: string;
    os_platform: string;
    os_version: string;
    os_arch: string;
    node_version: string;
    copilot_plan?: string;
    /** Type of client (e.g., "cli-interactive", "cli-prompt", "sdk") */
    client_type?: string;
    /** Name of the client application (e.g., "copilot-cli", "autopilot", "sdk") */
    client_name?: string;
    /** Whether the user is a GitHub/Msft staff member */
    is_staff?: boolean;
    /** Whether TE is enabled for the user */
    te?: boolean;
    /**
     * Raw contents of the most recent `X-Copilot-API-Request-TE` response header
     * relayed from Copilot API responses (an opaque per-request treatment signal).
     */
    rte?: string;
    /** Stable machine identifier from @vscode/deviceid */
    dev_device_id?: string;
}

declare type ClientInfo_2 = {
    clientName: string;
    displayName?: string;
    mcpClient?: NativeMcpSession;
    listTools?: (options?: {
        timeoutMs?: number;
    }) => Promise<readonly LenientToolInfo[]>;
    safeForTelemetry?: Tool["safeForTelemetry"];
    tools: string[];
    filterMapping?: Record<string, ContentFilterMode_2> | ContentFilterMode_2;
    timeout?: number;
    pendingConnection?: Promise<void>;
    isDefaultServer?: boolean;
    disableSecretMasking?: boolean;
    serverSupportsTaskTools?: boolean;
    excludeTools?: string[];
    deferTools?: "auto" | "never";
};

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;
    /**
     * If for the current model, a higher level of thinking is possible, use it.
     * @default false
     */
    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.
     */
    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;
    /**
     * 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_3;
    /**
     * 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;
    /**
     * 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_2;
    /** OpenAI Responses API prompt cache key. */
    promptCacheKey?: 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;
    /**
     * 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;
    /**
     * Resolver for OpenAI client-executed tool search routed to an SDK consumer.
     *
     * Only clients that service tool search themselves (today, the OpenAI
     * Responses client) read this. When a `SessionOptions.toolSearch` override
     * is configured, the session sets it so the client routes a
     * `tool_search_call` to the SDK consumer over `external_tool.requested`,
     * resolving to the matched deferred-tool names. Clients that ignore it fall
     * back to their built-in search. Only applicable to OpenAI models.
     */
    clientToolSearchResolver?: (args: unknown, toolCallId: string) => Promise<string[]>;
    /**
     * 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;
};

/**
 * 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>;
        stat(params: SessionFsStatRequest): SessionFsStatResult | Promise<SessionFsStatResult>;
        writeFile(params: SessionFsWriteFileRequest): SessionFsError | Promise<SessionFsError>;
    };
}

declare type CloudSessionStoreSqlInput = {
    description: string;
    query: string;
    org?: string;
    repo?: string;
    source?: "cloud" | "local";
};

declare type CloudSessionStoreSqlSettings = SettingsStorageContext;

/** CAPI integration ID used by the Code Coverage Agent. */
export declare const COCOA_INTEGRATION_ID = "code-coverage-ai";

/** Feature flag name for explicitly disabling the code review tool */
declare const CODE_REVIEW_DISABLE_FF_NAME = "copilot_swe_agent_code_review_disabled";

/** Feature flag name for enabling the code review tool */
declare const CODE_REVIEW_FF_NAME = "copilot_swe_agent_code_review";

/** Tool name constant for the code review tool */
declare const CODE_REVIEW_TOOL_NAME = "code_review";

/**
 * Code change metrics tracked during a session
 */
export declare interface CodeChangeMetrics {
    linesAdded: number;
    linesRemoved: number;
    filesModified: Set<string>;
    /**
     * Absolute count of changed files when individual file paths are not
     * available (e.g. relay sessions, where the host reports only an aggregate
     * `SessionSummary.changes.files` count rather than per-edit paths). When
     * set, consumers prefer this over `filesModified.size`. Local sessions leave
     * it undefined and rely on the `filesModified` path set.
     */
    filesModifiedCount?: number;
}

/**
 * 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 */
declare interface CommandCompletedData {
    /** Request ID of the resolved command request; clients should dismiss any UI for this request */
    requestId: string;
}

export declare type CommandCompletedEvent = WireTypes.CommandCompletedEvent;

/** Session event "command.completed". Queued command completion notification signaling UI dismissal */
declare interface CommandCompletedEvent_2 {
    /** 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 */
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;
}

export declare type CommandExecuteEvent = WireTypes.CommandExecuteEvent;

/** Session event "command.execute". Registered command dispatch request routed to the owning client */
declare interface CommandExecuteEvent_2 {
    /** 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 */
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;
}

export declare type CommandQueuedEvent = WireTypes.CommandQueuedEvent;

/** Session event "command.queued". Queued slash command dispatch request for client execution */
declare interface CommandQueuedEvent_2 {
    /** 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. */
declare interface CommandsChangedCommand {
    /** Optional human-readable command description. */
    description?: string;
    /** Slash command name without the leading slash. */
    name: string;
}

/** SDK command registration change notification */
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";
}

/** 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) */
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 */
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 */
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;
    /** Number of tokens removed during compaction */
    tokensRemoved?: number;
    /** Token count from tool definitions after compaction */
    toolDefinitionsTokens?: number;
}

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";
}

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 */
declare interface CompactionStartData {
    /** Token count from non-system messages (user, assistant, tool) at compaction start */
    conversationTokens?: number;
    /** Model identifier used for compaction, when known */
    model?: string;
    /** Token count from system message(s) at compaction start */
    systemTokens?: number;
    /** Token count from tool definitions at compaction start */
    toolDefinitionsTokens?: number;
}

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";
}

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";
}>;

export declare function completeOrphanedToolCalls(messages: ChatCompletionMessageParam[], options?: {
    syntheticToolResultContent?: (toolCall: CopilotChatCompletionMessageToolCall) => string | undefined;
}): ChatCompletionMessageParam[];

/** 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;
            };
        };
    };
};

export declare class CompoundLogger implements RunnerLogger {
    readonly loggers: RunnerLogger[];
    constructor(loggers: RunnerLogger[]);
    isDebug(): boolean;
    shouldLog(level: LogLevel): boolean;
    debug(message: string): void;
    log(message: string): void;
    info(message: string): void;
    notice(message: string | Error): void;
    warning(message: string | Error): void;
    error(message: string | Error): void;
    startGroup(name: string, level?: LogLevel): void;
    endGroup(level?: LogLevel): void;
}

/**
 * Coarse, repo-granular confidentiality lattice. Instead of enumerating reader
 * sets (collaborator logins), we track the set of source repositories whose
 * private data is mixed into a value. The authorised audience of a `private`
 * label is the intersection of the collaborator sets of its compartments; this
 * representation lets us decide same-repo vs different-repo flows without
 * enumerating collaborators.
 *
 *   - `public()` is the bottom (universe of readers).
 *   - `private(repos)` is private to the compartments in `repos`.
 *   - A ⊑ B iff B ⊆ A in audience terms, which for our compartments is:
 *       public ⊑ anything, and private(R₁) ⊑ private(R₂) iff R₁ ⊆ R₂
 *       (more compartments = smaller audience = higher in the lattice).
 *   - join (LUB) = union of compartments (mixing data shrinks the audience).
 *   - meet (GLB) = intersection of compartments.
 *
 * Because join is union, mixing data from two different repos yields a
 * two-compartment label that is ⊑ neither single repo — so a write to either
 * repo alone is correctly disallowed (only a same-single-repo write passes).
 */
declare class ConfidentialityLabel implements Lattice<ConfidentialityLabel> {
    readonly level: "public" | "private";
    /** Source-repo compartments; empty iff public, otherwise non-empty. */
    readonly repos: ReadonlySet<string>;
    static public(): ConfidentialityLabel;
    /**
     * Private to the given repository compartments (`owner/repo`). Defaults to
     * the opaque {@link LOCAL_COMPARTMENT} when no repos are supplied (private
     * data with no repo binding, e.g. local shell output).
     */
    static private(repos?: Iterable<string>): ConfidentialityLabel;
    private constructor();
    get isPrivate(): boolean;
    get isPublic(): boolean;
    /** public ⊑ anything; private(R₁) ⊑ private(R₂) iff R₁ ⊆ R₂. */
    leq(other: ConfidentialityLabel): boolean;
    join(other: ConfidentialityLabel): ConfidentialityLabel;
    meet(other: ConfidentialityLabel): ConfidentialityLabel;
    equals(other: ConfidentialityLabel): boolean;
    toString(): string;
    /**
     * Like {@link toString} but redacts repo identities (count only). Use this
     * in logs to avoid leaking private repo names into debug output.
     */
    toLogString(): string;
    /**
     * Lossless serialization:
     *   - public() → `["public"]`
     *   - private(repos) → the sorted compartment list
     *
     * This array form is NOT the coarse wire format ({@link parseIfcLabel}
     * accepts the string markers `"public"` / `"private"`). It IS round-tripped
     * in-process via {@link fromJSON} — e.g. the subagent seam carries the
     * child's full compartment set to the parent without collapsing to `<local>`.
     */
    toJSON(): string[];
    /**
     * Inverse of {@link toJSON}. `["public"]` → public(); any other non-empty
     * array → private(compartments). Returns undefined for malformed input
     * (empty array, non-string entries) so callers fail closed. A `"public"`
     * entry mixed with repos is treated as private (the safe, more-restrictive
     * reading) rather than silently downgrading to public.
     */
    static fromJSON(value: unknown): ConfidentialityLabel | undefined;
}

/** 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, in addition to the runtime's normal GitHub/CTS emission (dual-write). 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. */
    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;
}

export declare class ConsoleLogger extends BaseLogger implements RunnerLogger {
    constructor(logLevel?: LogLevel, debugEnvironmentVariables?: string[]);
    log(message: string): void;
    debug(message: string): void;
    info(message: string): void;
    notice(message: string | Error): void;
    warning(message: string | Error): void;
    error(message: string | Error): void;
    startGroup(name: string, level?: LogLevel): void;
    endGroup(level?: LogLevel): void;
}

/**
 * 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;
}

export declare type ContentBlock = WireTypes.ContentBlock;

/**
 * Response from the content exclusion API for a single repository.
 */
declare type ContentExclusionApiResponse = z.infer<typeof contentExclusionApiResponseSchema>;

/**
 * Zod schema for a single entry in the content exclusion API response array.
 */
declare const contentExclusionApiResponseSchema: z.ZodObject<{
    rules: z.ZodArray<z.ZodObject<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, z.ZodTypeAny, "passthrough">>, "many">;
    last_updated_at: z.ZodUnion<[z.ZodString, z.ZodNumber]>;
    scope: z.ZodEnum<["repo", "all"]>;
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
    rules: z.ZodArray<z.ZodObject<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, z.ZodTypeAny, "passthrough">>, "many">;
    last_updated_at: z.ZodUnion<[z.ZodString, z.ZodNumber]>;
    scope: z.ZodEnum<["repo", "all"]>;
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
    rules: z.ZodArray<z.ZodObject<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
        paths: z.ZodArray<z.ZodString, "many">;
        ifAnyMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        ifNoneMatch: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        source: z.ZodObject<{
            name: z.ZodString;
            type: z.ZodString;
        }, "strip", z.ZodTypeAny, {
            name: string;
            type: string;
        }, {
            name: string;
            type: string;
        }>;
    }, z.ZodTypeAny, "passthrough">>, "many">;
    last_updated_at: z.ZodUnion<[z.ZodString, z.ZodNumber]>;
    scope: z.ZodEnum<["repo", "all"]>;
}, z.ZodTypeAny, "passthrough">>;

/**
 * Service for checking content exclusion rules.
 *
 * This service fetches exclusion rules from the GitHub API and caches them.
 * It provides methods to check if files should be excluded based on:
 * - Path patterns (glob matching)
 * - Content patterns (regex matching via ifAnyMatch/ifNoneMatch)
 *
 * Usage:
 * 1. Create an instance with auth info
 * 2. Call startFetching() at session start (non-blocking)
 * 3. Call isExcluded() when checking files (blocks until fetch complete if needed)
 *
 * The fetch orchestration, rule cache, and path/content evaluation run in the
 * native runtime; this class owns the JS-side lifecycle (handle refcount and
 * finalizer), forwards telemetry, and replays the logs the runtime returns.
 */
declare class ContentExclusionService {
    private readonly featureEnabled;
    private disposed;
    private retainCount;
    private readonly finalizerToken;
    /** Handle to the native content exclusion service instance. */
    private readonly runtimeHandle;
    /** Optional callback for emitting telemetry events */
    private readonly onTelemetry?;
    constructor(host: string, token: string | undefined, featureEnabled: boolean, onTelemetry?: (event: TelemetryEvent) => void, additionalPolicies?: ContentExclusionApiResponse[]);
    retain(): void;
    dispose(): void;
    isUnavailable(): boolean;
    private getUnavailableResult;
    /**
     * Starts fetching exclusion rules for repositories in the given directories.
     * This method is non-blocking - it kicks off the fetch but doesn't wait.
     *
     * @param directories Directories to scan for git repositories
     */
    startFetching(directories: string[]): void;
    /**
     * Runs the native fetch, replays the returned logs, and forwards telemetry.
     */
    private runFetch;
    /**
     * Returns whether any content exclusion rules are active.
     * Awaits the initial fetch if still in progress.
     */
    hasRules(): Promise<boolean>;
    /**
     * Checks if a file is excluded by content exclusion rules.
     *
     * This method will block on the initial fetch if it hasn't completed yet.
     *
     * @param absolutePath Absolute path to the file
     * @returns Exclusion check result with excluded status and reason
     */
    isExcluded(absolutePath: string): Promise<ExclusionCheckResult>;
    /**
     * Checks if any files in a list are excluded.
     * Useful for shell command checking via possiblePaths.
     *
     * @param absolutePaths Array of absolute file paths
     * @param options.onlyExisting When true, paths that do not exist on disk are
     *   ignored before checking exclusion. Shell `possiblePaths` is an
     *   over-approximation that can include phantom paths (command names,
     *   subcommands, and other bare words resolved under the cwd) that never
     *   exist on disk. A path that does not exist cannot reference protected
     *   content, so callers checking shell commands set this to avoid
     *   false-positive blocks on those phantom paths. Explicit read/write
     *   targets (view/edit/create) must leave this unset so that not-yet-created
     *   files remain protected.
     * @param options.cwd The working directory the paths were resolved against.
     *   Used only to recover the original (pre-resolution) token for the
     *   glob-metacharacter heuristic in {@link filterExistingPaths}; see that
     *   method for why the token, not the absolute path, must be inspected.
     * @returns First excluded path and its result, or null if none excluded
     */
    findFirstExcluded(absolutePaths: string[], options?: {
        onlyExisting?: boolean;
        cwd?: string;
    }): Promise<{
        path: string;
        result: ExclusionCheckResult;
    } | null>;
    /**
     * Filters a list of paths down to those that could reference real content on
     * disk, i.e. paths that currently exist.
     *
     * Paths containing shell glob/wildcard metacharacters (`*`, `?`, `[`, `]`,
     * `{`, `}`) are kept regardless of existence: the shell expands them at
     * runtime, so they never `stat()` as a literal file, but they can still
     * resolve to excluded content (e.g. `cat *.secret` reading `passwords.secret`).
     * Dropping them would let a glob bypass an exclusion rule it matches, so we
     * conservatively keep them and let pattern matching decide. Command-name
     * phantoms (`git`, `Get-Location`) never contain these characters, so this
     * does not reintroduce the over-blocking this filter is meant to prevent.
     *
     * The metacharacter test runs against the original (pre-resolution) token,
     * recovered via `cwd`, rather than the resolved absolute path. A working
     * directory that itself contains `[`, `]`, `{`, or `}` (e.g. `/repo/cache[1]`)
     * would otherwise make every relative phantom candidate resolved under it look
     * like a glob, short-circuit the existence check, and re-introduce the
     * over-blocking this filter prevents.
     */
    private filterExistingPaths;
    /**
     * Gets the formatted error message for an excluded file.
     */
    getExclusionMessage(filePath: string): string;
    /**
     * Returns the native service handle so a streaming line filter can drive
     * exclusion checks directly, or `undefined` once the service is disposed so
     * the filter observes the service as unavailable.
     */
    getRuntimeHandleForFilter(): number | undefined;
    /**
     * Returns whether content exclusion is enabled for this service. Readable
     * even after disposal (the flag is fixed at construction), so the streaming
     * line filter can pair it with `getRuntimeHandleForFilter()` to fail closed
     * for a disposed-but-present, feature-enabled service — matching
     * `getUnavailableResult()`.
     */
    isFeatureEnabledForFilter(): boolean;
    /**
     * Forwards a native rule-fetch telemetry record as a
     * `content_exclusion_rules_fetched` event. Used both by this shim's fetch
     * and by the streaming line filter, which drives the native orchestrator
     * directly and may trigger a cache refresh.
     */
    emitRuntimeFetchTelemetry(telemetry: {
        ruleCount: number;
        repoCount: number;
        submoduleCount: number;
        fetchDurationMs: number;
    }): void;
    /** Replays effects accumulated by a native tool that checked this service directly. */
    replayRuntimeSideEffects(logs: {
        level: string;
        message: string;
    }[], telemetry: {
        ruleCount: number;
        repoCount: number;
        submoduleCount: number;
        fetchDurationMs: number;
    }[]): void;
    /** Replays native leveled log lines through the JS logger. */
    private replayLogs;
}

/** 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 = "none" | "markdown" | "hidden_characters";

declare enum ContentFilterMode_2 {
    None = "none",
    Markdown = "markdown",
    HiddenCharacters = "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";
}

/** 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. */
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_2;
    /** 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;
    ImpressionId?: string;
    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;
}

/**
 * The canonical Copilot user-response shape is the generated SDK wire type.
 * Rust owns runtime validation/normalization; parse results assign cleanly to
 * this type while consumers see exactly the wire contract.
 */
declare type CopilotUserResponse = CopilotUserResponse_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. */
declare interface CopilotUserResponse_2 {
    /** 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;
    "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;
}

declare type CoreServicesInput = {
    telemetryService: TelemetryService;
    createFeatureFlagService: CreateFeatureFlagService;
    autoModeManager: AutoModeSessionManager;
};

declare const CREATE_PULL_REQUEST_TOOL_NAME = "create_pull_request";

declare function createAskUserTool(requestUserInput: RequestUserInputFn): Tool;

declare function createCanvasTools(canvas: SessionCanvasApi, permissions: PermissionsConfig): Tool[];

declare const createCloudSessionStoreSqlTool: (_config: ToolConfig, options: {
    settings: CloudSessionStoreSqlSettings;
    /** Whether the local session store is also available for supplementary queries */
    localEnabled?: boolean;
}) => Tool;

export declare function createCoreServices({ telemetryService, createFeatureFlagService, autoModeManager, }: CoreServicesInput): CoreServices;

export declare function createDeferredFeatureFlagService(options: FeatureFlagInitOptions): FeatureFlagService;

/**
 * Create an empty metrics object.
 */
export declare function createEmptyMetrics(sessionStartTime?: number): UsageMetrics;

export declare type CreateFeatureFlagService = (options: {
    readonly sessionId: string;
    expAssignments?: CopilotExpAssignmentResponse;
    deferExpResponse?: boolean;
}) => SessionFeatureFlagService;

/**
 * Creates a provider-neutral search tool that loads matching definitions into
 * the next request through the session's normal mid-turn tool refresh.
 */
declare function createGenericClientToolSearchTool(options: GenericClientToolSearchOptions): Tool;

export declare function createLocalFeatureFlagService(options?: Partial<FeatureFlagInitOptions>): LocalFeatureFlagService;

export declare function createLocalFeatureFlagServiceCreator(options?: Partial<FeatureFlagInitOptions>): CreateFeatureFlagService;

declare function createLSPRefactorTools(config: ToolConfig, logger: RunnerLogger): Tool[];

declare function createLSPTool(config: ToolConfig, logger: RunnerLogger): Tool;

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>;
}

declare function createPullRequestTool(settings: Settings, logger: RunnerLogger, agentAction?: AgentAction): Tool | undefined;

declare function createRunFactoryTool(api: RunFactoryApi): Tool;

declare const createSqlTool: (workspacePath: string, config: ToolConfig, options?: Options) => Tool | undefined;

/**
 * Creates the task_complete tool.
 * The session emits the `session.task_complete` event when this tool is executed.
 */
declare function createTaskCompleteTool(): Tool;

declare function createToolSearchTool(options: ToolSearchToolOptions): Tool;

/**
 * Callback values cannot cross N-API, so this intentionally remains a small
 * host wrapper around the runtime-owned tool-set name registry.
 */
declare const createToolSet: (tools: Tool[]) => Record<string, Tool>;

/** 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;
}

declare const CUSTOM_TOOL_NAMES: readonly ["apply_patch"];

/**
 * 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. */
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. */
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";
}

declare type CustomModelMetadata = {
    key_name: string;
    owner_name: string;
    owner_type: "organization" | "enterprise";
    provider: string;
};

export declare type CustomNotificationData = WireTypes.CustomNotificationData;

/** Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. */
declare interface CustomNotificationData_2 {
    /** 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;
}

export declare type CustomNotificationEvent = WireTypes.CustomNotificationEvent;

/** Session event "session.custom_notification". Opaque custom notification data. Consumers may branch on source and name, but payload semantics are source-defined. */
declare interface CustomNotificationEvent_2 {
    /** 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_2;
    /** 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 */
declare type CustomNotificationPayload = unknown;

/** Optional source-defined string identifiers describing the payload subject */
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 DEFAULT_INTEGRATION_ID = "copilot-developer-cli";

declare const DEFAULT_LARGE_OUTPUT_THRESHOLD: number;

/**
 * Default maximum decoded byte size for a single model-facing binary tool
 * result (e.g. an image) that will be persisted inline in session events and
 * re-presented to the model on subsequent turns / resume. Results larger than
 * the effective limit are persisted as a metadata-only marker (an
 * omitted-binary result) and replaced with a short text note on read-back.
 * Override per session via `SessionOptions.maxInlineBinaryBytes`.
 */
export declare const DEFAULT_MAX_INLINE_BINARY_BYTES: number;

export declare const defaultFeatureFlags: Readonly<Readonly<Record<string, boolean> & KnownFeatureFlagProperties>>;

/** Tool count above which MCP/external tools defer (`deferLoading`) behind tool search. */
declare const DEFERRED_TOOLS_THRESHOLD = 30;

declare enum DefinedExpFlags {
    COPILOT_CI = "copilot_ci",
    COPILOT_CLI = "copilot_cli",
    GPT_DEFAULT_MODEL = "copilot_cli_gpt_default_model",
    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",
    /** Enables provider-neutral client-side tool search for ordinary function-calling models. */
    TOOL_SEARCH_CLIENT_GENERIC = "copilot_cli_tool_search_client_generic",
    /** When true, uses fingerprint-based enterprise allowlist evaluation instead of per-server registry lookups */
    MCP_ENTERPRISE_ALLOWLIST = "copilot_cli_mcp_enterprise_allowlist",
    /** 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, enables tgrep indexed search for large repositories */
    TGREP = "copilot_cli_tgrep",
    /** 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",
    /**
     * 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, enables improved subagent parallelism prompts to encourage direct action and real parallel work */
    SUBAGENT_PARALLELISM_PROMPTS = "copilot_cli_subagent_parallelism_prompts",
    /** When true, enables the CLI search subagent tool (server-side ExP rollout, independent of the static feature flag) */
    SEARCH_SUBAGENT = "copilot_cli_search_subagent",
    /** 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, reduces planning/progress overhead in CLI prompt guidance */
    NO_PLANNING = "copilot_cli_no_planning",
    /** 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, enables automatic compaction of successful bash output */
    BASH_OUTPUT_COMPACTION = "copilot_cli_bash_output_compaction",
    /** When true, enables automatic compaction of successful grep/glob/rg output */
    SEARCH_TOOL_OUTPUT_COMPACTION = "copilot_cli_search_tool_output_compaction",
    /** 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",
    /**
     * 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, injects the per-turn LSP language-server status reminder into the user message. */
    LSP_SERVICES_PROMPT = "copilot_cli_lsp_services_prompt",
    /**
     * When true, the skills list is moved out of the skill tool definition and
     * rendered into the dynamic part of the system prompt (the `<tools>` section)
     * for improved prompt cache hit rates. A/B via ExP.
     */
    SKILLS_LIST_IN_SYSTEM_PROMPT = "copilot_cli_skills_list_in_system_prompt",
    /** 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, enables session-scoped `/model` overrides (--session/-s). */
    SESSION_MODEL_OVERRIDE = "copilot_cli_session_model_override",
    /** When true, shows the GitHub Copilot desktop-app install nudge at startup. Rollout gated via ExP. */
    APP_INSTALL_NUDGE = "copilot_cli_app_install_nudge"
}

declare class DelegatingShellNotificationSender implements ShellNotificationSender {
    private delegate?;
    constructor(delegate?: ShellNotificationSender);
    configure(delegate: ShellNotificationSender | undefined): void;
    sendOutput(notification: ShellOutputNotification): void;
    sendExit(notification: ShellExitNotification): void;
}

declare type DeniedToolResult = ToolResultExpanded & {
    resultType: "denied";
};

declare type DeniedToolResult_2 = ToolResultExpanded & {
    resultType: "denied";
};

export declare function describeDiscoveredInstructionSource(source: InstructionSource_2): string;

/**
 * Generate a human-readable title for a system notification kind.
 * Used as the `title` field in notification hook payloads.
 */
export declare function describeSystemNotificationKind(kind: SystemNotificationKind): string;

export declare type DirectoryAttachment = WireTypes.DirectoryAttachment;

/** 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;
}

/** 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 {
    dispose(): void;
    setExtraFeatures(features: Record<string, string>): void;
    setInternalCorrelationIds?(internalCorrelationIds: SessionCorrelationIds | undefined): void;
    /**
     * Optional accessor for the current engagement id. Implemented by
     * `SessionTelemetry`; forwarded by the parent CLI when spawning a
     * detached child so engagement-scoped analytics roll up correctly.
     */
    getEngagementId?(): string;
}

declare const doesStrReplaceEditorArgsWriteContentInclude: (args: StrReplaceEditorArgs, content: string) => 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];

/** Tracks instruction sources discovered at runtime by on-demand file access */
declare interface DynamicInstructionState {
    /** Instruction sources discovered at runtime, keyed by resolved absolute file path */
    sources: Map<string, InstructionSource_2>;
    /** Directories already scanned (to avoid re-scanning) */
    discoveredDirs: Set<string>;
    /** Source IDs already delivered to the agent (to avoid re-injecting) */
    deliveredSourceIds: Set<string>;
    /** Promise chain that serializes concurrent discovery walks to protect dedupe invariants */
    pendingDiscovery: Promise<void>;
}

declare const editingTools: (config: ToolConfig, logger: RunnerLogger, _settings?: object) => Tool[];

/** The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed) */
declare type ElicitationCompletedAction = "accept" | "decline" | "cancel";

/** Opaque JSON value submitted for one field in accepted `elicitation.completed` form content. */
declare type ElicitationCompletedContent = unknown;

/** Elicitation request completion with the user's response */
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;
}

export declare type ElicitationCompletedEvent = WireTypes.ElicitationCompletedEvent;

/** Session event "elicitation.completed". Elicitation request completion with the user's response */
declare interface ElicitationCompletedEvent_2 {
    /** 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) */
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;
}

export declare type ElicitationRequestedEvent = WireTypes.ElicitationRequestedEvent;

/** Session event "elicitation.requested". Elicitation request; may be form-based (structured input) or URL-based (browser redirect) */
declare interface ElicitationRequestedEvent_2 {
    /** 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. */
declare type ElicitationRequestedMode = "form" | "url";

/** JSON Schema describing the form fields to present to the user (form mode only) */
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. */
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;
}

export declare type EmbeddedResource = WireTypes.EmbeddedResource;

/** Embedded text resource contents identified by a URI, with an optional MIME type and a text payload. */
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?: RunnerLogger): 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_2;
    /** 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 */
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";
}

declare type Event_2 = MessageEvent_2 | ResponseEvent | ModelCallFailureEvent_2 | ModelCallStartedEvent | TurnEvent | TruncationEvent_2 | UsageInfoEvent_2 | ResponseLimitsStatusEvent | CompactionEvent | ImageProcessingEvent | BinaryAttachmentRemovalEvent | ModelCallSuccessEvent | ToolExecutionEvent | TelemetryEvent_2 | 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 {
    /** 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;
    /** 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). */
    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 started from the beginning of the remaining history. */
declare type EventsCursorStatus = "ok" | "expired";

/** 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. */
    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 started from the beginning of the remaining history. */
    cursorStatus: EventsCursorStatus;
    /** Events are delivered in two batches per read: persisted events first (in append order), then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral events do not interleave within a single read. */
    events: SessionEvent_2[];
    /** True when the read returned `max` events and more events are available immediately. When false, the next read with a non-zero `waitMs` will block until a new event arrives or the wait expires. */
    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"];
};

declare type EventType = SessionEvent["type"];

/**
 * Models that are explicitly excluded from the model picker regardless of
 * API enablement or policy status. These models will never be shown to users.
 */
export declare const EXCLUDED_MODELS: ReadonlySet<string>;

/**
 * Result of checking if a file is excluded.
 */
declare interface ExclusionCheckResult {
    /** Whether the file is excluded */
    excluded: boolean;
    /** If excluded, the reason/source */
    reason?: string;
    /** If excluded, the source that set the rule */
    source?: {
        name: string;
        type: 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;
}

/** Exit plan mode action */
declare type ExitPlanModeAction = "exit_only" | "interactive" | "autopilot" | "autopilot_fleet";

declare type ExitPlanModeAction_2 = (typeof ExitPlanModeActionValues)[number];

declare const ExitPlanModeActionValues: readonly ["exit_only", "interactive", "autopilot", "autopilot_fleet"];

/** Plan mode exit completion with the user's approval decision and optional feedback */
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;
}

export declare type ExitPlanModeCompletedEvent = WireTypes.ExitPlanModeCompletedEvent;

/** Session event "exit_plan_mode.completed". Plan mode exit completion with the user's approval decision and optional feedback */
declare interface ExitPlanModeCompletedEvent_2 {
    /** 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";
}

declare type ExitPlanModeRequest = {
    summary: string;
    actions: ExitPlanModeAction_2[];
    recommendedAction: ExitPlanModeAction_2;
    toolCallId?: string;
};

/** Plan approval request with plan content and available user actions */
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;
}

export declare type ExitPlanModeRequestedEvent = WireTypes.ExitPlanModeRequestedEvent;

/** Session event "exit_plan_mode.requested". Plan approval request with plan content and available user actions */
declare interface ExitPlanModeRequestedEvent_2 {
    /** 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_2;
    autoApproveEdits?: boolean;
    feedback?: string;
};

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;
}

export declare type ExtensionContextAttachment = WireTypes.ExtensionContextAttachment;

/** 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 {
    /** 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>;
    /** Author and reload a session-scoped factory through the extension host. */
    authorFactory?(args: unknown, requestPermission: (request: PermissionRequest_2) => Promise<PermissionRequestResult_2>): 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. */
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_2[];
}

/** 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";
}

/** 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. */
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";
}

/** A single extension discovered by `session.extensions_loaded`, including qualified ID, source, and current status. */
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 */
declare type ExtensionsLoadedExtensionSource = "project" | "user" | "plugin" | "session";

/** Current status: running, disabled, failed, or starting */
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 */
declare interface ExternalToolCompletedData {
    /** Request ID of the resolved external tool request; clients should dismiss any UI for this request */
    requestId: string;
}

export declare type ExternalToolCompletedEvent = WireTypes.ExternalToolCompletedEvent;

/** Session event "external_tool.completed". External tool completion notification signaling UI dismissal */
declare interface ExternalToolCompletedEvent_2 {
    /** 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";
}

export declare type ExternalToolCompletion = WireTypes.ExternalToolCompletion;

declare type ExternalToolCompletion_2 = {
    status: "success";
    result: ExternalToolResult_2;
} | {
    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";
    /**
     * 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 */
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;
}

export declare type ExternalToolRequestedEvent = WireTypes.ExternalToolRequestedEvent;

/** Session event "external_tool.requested". External tool invocation request for client-side tool execution */
declare interface ExternalToolRequestedEvent_2 {
    /** 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";
}

export declare type ExternalToolResult = WireTypes.ExternalToolResult;

/** Tool call result (string or expanded result object) */
declare type ExternalToolResult_2 = 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;

declare type ExtraKnownMarketplaces = Record<string, {
    source: ExtraKnownMarketplaceSource;
    [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;
};

/** 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 label distinguishing otherwise identical memoized agent calls. */
    label?: string;
    /** Optional model identifier for the subagent. */
    model?: string;
    /** Optional JSON Schema for structured agent output. */
    schema?: unknown;
}

/** Parameters for one factory-scoped subagent call. */
declare interface FactoryAgentRequest {
    /** 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;
}

/** Parameters for cancelling a factory run. */
declare interface FactoryCancelRequest {
    /** Factory run identifier. */
    runId: string;
}

/** Parameters sent to the owning extension to execute a factory closure. */
declare interface FactoryExecuteRequest {
    /** Factory input value. */
    args: unknown;
    /** 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 retrieving a factory run. */
declare interface FactoryGetRunRequest {
    /** Factory run identifier. */
    runId: string;
}

/** Parameters for reading a factory journal entry. */
declare interface FactoryJournalGetRequest {
    /** 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 {
    /** 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;
    /** Wall-clock timeout for the factory run, in milliseconds. Must be positive when present. */
    timeout?: number;
}

/** 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 {
    /** Ordered progress lines to append. */
    lines: FactoryLogLine[];
    /** Factory run identifier. */
    runId: string;
}

/** 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";
};

/** Cumulative resource ceiling that stopped a factory run. */
declare type FactoryRunFailureKind = "maxTotalSubagents" | "timeout";

/** Wire-only per-invocation factory resource ceiling overrides. */
declare interface FactoryRunLimits {
    /** Maximum number of factory subagents that may run concurrently. */
    maxConcurrentSubagents?: number;
    /** Maximum total number of factory subagents that may be admitted. */
    maxTotalSubagents?: number;
    /** Factory active-run timeout in milliseconds. */
    timeout?: 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";

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;
    private latestRequestTe;
    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;
    getLatestRequestTeIfPresent(): string | undefined;
    captureRequestTe(requestTe: 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>;
    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>>;

/**
 * Tool that fetches documentation about the GitHub Copilot CLI agent.
 * First checks embedded README and /help output, only fetches online docs if needed.
 */
declare const fetch_copilot_cli_documentation: (logger: RunnerLogger) => Tool | undefined;

declare const FETCH_DOCUMENTATION_TOOL_NAME = "fetch_copilot_cli_documentation";

export declare type FileAttachment = WireTypes.FileAttachment;

/**
 * The direct host closures the native file-effect driver invokes, one per
 * capability. Each is a thin pass-through to a live host callback; the native
 * driver owns which capability to call, the request/response envelopes, the
 * dispatch protocol, and the defaults. The types are derived from the generated
 * N-API signature so the closures stay in lockstep with the Rust contract.
 */
declare type FileDriverCallbacks = {
    checkExclusion: Parameters<typeof nativeRuntime.toolFileDriverRegisterCallbacks>[0];
    requestPermission: Parameters<typeof nativeRuntime.toolFileDriverRegisterCallbacks>[1];
    readImage: Parameters<typeof nativeRuntime.toolFileDriverRegisterCallbacks>[2];
    countTokens: Parameters<typeof nativeRuntime.toolFileDriverRegisterCallbacks>[3];
    sessionFs: Parameters<typeof nativeRuntime.toolFileDriverRegisterCallbacks>[4];
    fileCreated: Parameters<typeof nativeRuntime.toolFileDriverRegisterCallbacks>[5];
    fileAccessed: Parameters<typeof nativeRuntime.toolFileDriverRegisterCallbacks>[6];
};

declare const fileDriverEffects: (config: ToolConfig, logger: RunnerLogger, options: Options_2 | undefined, exclusion?: ContentExclusionService | undefined) => FileDriverCallbacks;

export declare class FileLogger extends BaseLogger implements RunnerLogger, LogWriter {
    private readonly handle;
    constructor(filePath: string, logLevel?: LogLevel, debugEnvironmentVariables?: string[]);
    /** Dispose the underlying Rust file logger. Call when done to release
     * the handle and flush remaining writes. */
    dispose(): Promise<void>;
    /** Promise that resolves when all pending writes are persisted. Used to
     * serialize writes and for testing. */
    get writeQueue(): Promise<void>;
    outputPath(): string;
    shouldLog(level: LogLevel): boolean;
    isDebug(): boolean;
    log(message: string): void;
    debug(message: string): void;
    info(message: string): void;
    notice(message: string | Error): void;
    warning(message: string | Error): void;
    error(message: string | Error): void;
    startGroup(name: string, level?: LogLevel): void;
    endGroup(level?: LogLevel): void;
    /** @internal Exported for testing only. */
    get stats(): FileLoggerStats;
    /** Format and enqueue one log entry. Secret filtering must already be
     * applied before calling this method. */
    write(category: string, message: string): void;
    writeLog(level: LogLevel_2, message: string): Promise<void>;
    private logNative;
}

declare interface FileLoggerStats {
    writeCount: number;
    pendingLength: number;
    drainScheduled: boolean;
}

/**
 * A range of lines in a file.
 */
declare interface FileRange {
    /** The path of the file, relative to the repository root. */
    path: string;
    /** The start line of the range (1-based, inclusive). */
    startLine: number;
    /** The end line of the range (1-based, inclusive). */
    endLine: number;
}

/**
 * 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 file-snapshot 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 CLI snapshot 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.
 */
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> | ContentFilterMode;

/**
 * Find orphaned tool call IDs from the end of the chat messages.
 * Returns an array of {toolCallId, toolName, args} for each orphaned tool call.
 */
export declare function findOrphanedToolCalls(messages: ChatCompletionMessageParam[]): {
    toolCallId: string;
    toolName: string;
    args: unknown;
}[];

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;
}

declare interface ForkSessionOptions {
    /** Optional event ID boundary (exclusive). */
    toEventId?: string;
    /** Optional friendly name for the fork. */
    name?: string;
}

declare interface ForkSessionResult {
    /** New forked session ID. */
    sessionId: string;
    /** Friendly name assigned to the fork, when one was persisted. */
    name?: string;
}

declare const formatBytes: (bytes: number) => string;

/**
 * Type for a function tool call delta (streaming).
 */
declare type FunctionToolCallDelta = {
    index: number;
    id?: string;
    type?: "function";
    function?: {
        name?: string;
        arguments?: string;
    };
};

declare const generateLargeOutputMessage: (filePath: string, bytes: number, preview: string, grep?: string, kind?: string) => string;

/** @deprecated Use {@link ShellContextHolder}. */
declare type GenerationalHolder<T> = ShellContextHolder<T>;

declare interface GenericClientToolSearchOptions {
    getAllTools: () => ReadonlyArray<ToolMetadata>;
    onDiscover: (toolNames: readonly string[]) => void;
    isDiscovered?: (toolName: string) => boolean;
    onInvoked?: (input: {
        query?: string;
        limit?: number;
        catalogCount: number;
        resultCount: number;
        newlyActivatedCount?: number;
        outcome: "success" | "no_match" | "invalid" | "custom" | "failure";
    }) => void;
    callback?: ToolCallback;
    definition?: ToolSearchToolOptions["definition"];
}

/**
 * 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;
    /** Current per-run resolver for client-executed tool search. */
    clientToolSearchResolver?: (args: unknown, toolCallId: string) => Promise<string[]>;
    /**
     * 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 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;
    /**
     * 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_3;
    /**
     * 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.
     */
    onSessionTokenExpired?: () => Promise<{
        sessionToken: string;
        model: string;
    } | undefined>;
};

declare const getCreatedTempFiles: () => ReadonlyArray<{
    filePath: string;
}>;

/** Gets the list of available custom agents. */
export declare function getCustomAgents(authInfo: AuthInfo, workingDir: string, integrationId?: string, logger?: RunnerLogger, settings?: SettingsStorageContext, additionalPlugins?: InstalledPlugin[]): Promise<SweCustomAgent[]>;

export declare function getExpFlagEnvKey(flag: ExpFlagKey): string;

declare function getGrepToolNameFromTools(tools: readonly Pick<ToolMetadata, "name" | "description">[]): string | undefined;

/**
 * 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).
 *
 * Fail-closed: a server fetch that is attempted but fails leaves policy
 * undetermined and forces the restriction on (`resolved.failClosed === true`).
 * 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;
    /** Test seam: override the server-fetch implementation. */
    fetchImpl?: IngestManagedSettingsInput["fetchImpl"];
    /** Test seam: override the device-MDM loader. */
    loadDeviceImpl?: IngestManagedSettingsInput["loadDeviceImpl"];
    /** Test seam: override token resolution for {@link authInfo}. */
    getToken?: IngestManagedSettingsInput["getToken"];
}

declare function getOrCreateCurrent<T>(holder: ShellContextHolder<T>, create: () => Promise<T>, dispose?: (value: T) => void): Promise<T>;

declare const getStrReplaceEditorArgsOrNull: (call: CopilotChatCompletionMessageToolCall) => StrReplaceEditorArgs | null;

declare function getToolDeniedWithoutUserRequest(isAutopilotMode?: boolean): Readonly<DeniedToolResult_2>;

/** 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_2;
    /** 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";
}

declare interface GitHandler {
    /**
     * Clone a repository.
     * @param settings The runtime settings.
     * @param repo The repository to clone.
     * @param repoLocation The location to clone the repository to.
     * @param branchName The name of the branch to clone.
     * @param commitCount The number of commits to fetch during cloning. Used for PR comment fix scenarios only. Defaults to 2.
     * @param baseCommit The base commit to use for the clone. Used for PR comment fix scenarios only.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     */
    cloneRepo: (settings: GitRuntimeSettings, repo: string, repoLocation: string, branchName: string, commitCount?: number, baseCommit?: string, execOptions?: RunnerExecOptions) => Promise<void>;
    /**
     * Commit changes to the repository without pushing.
     * @param settings The runtime settings.
     * @param branchName The name of the branch to commit to.
     * @param repoLocation The location of the repository.
     * @param commitMessage The commit message.
     * @param allowEmptyCommit Whether to allow empty commits.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise indicating the success of the operation.
     */
    commitChanges: (settings: GitRuntimeSettings, branchName: string, repoLocation: string, commitMessage: string, allowEmptyCommit?: boolean, noVerify?: boolean, execOptions?: RunnerExecOptions) => Promise<string>;
    /**
     * Commit and push changes to the repository.
     * @param settings The runtime settings.
     * @param branchName The name of the branch to commit to.
     * @param repoLocation The location of the repository.
     * @param commitMessage The commit message.
     * @param allowEmptyCommit Whether to allow empty commits.
     * @param noVerify Whether to skip pre-commit/push hooks.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise indicating the success of the operation.
     */
    commitAndPushChanges: (settings: GitRuntimeSettings, branchName: string, repoLocation: string, commitMessage: string, allowEmptyCommit?: boolean, noVerify?: boolean, execOptions?: RunnerExecOptions) => Promise<string>;
    /**
     * Stages all changes in the repository (including new files).
     *
     * @param repoLocation The location of the repository.
     */
    stageChanges(repoLocation: string, execOptions?: RunnerExecOptions): Promise<string>;
    /**
     * Get the diff of a branch.
     * @param repoLocation The location of the repository.
     * @param stagedChanges If true, compare against staged changes. If false compare against all changes.
     * @param baseCommit The base commit to compare against. If this parameter is not provided, the diff will be calculated against the current working tree.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise containing the diff.
     */
    diff: (repoLocation: string, stagedChanges?: boolean, baseCommit?: string, execOptions?: RunnerExecOptions) => Promise<string>;
    /**
     * Get the parsed diff of a branch, as a list of diff file ranges.
     * @param repoLocation The location of the repository.
     * @param baseCommit The base commit to compare against. If this parameter is not provided, the diff will be calculated against the current working tree.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise containing the list of diff file ranges.
     */
    getDiffRanges: (repoLocation: string, baseCommit?: string, execOptions?: RunnerExecOptions) => Promise<FileRange[]>;
    /**
     * Get the most recent commits in a repository.
     * @param repoLocation The location of the repository.
     * @param count The number of commits to retrieve.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise containing the list of commit hashes.
     */
    getMostRecentCommits: (repoLocation: string, count: number, execOptions?: RunnerExecOptions) => Promise<string[]>;
    /**
     * Get the paths of files that have been changed between two commits, or between a commit and the working tree.
     * @param repoLocation The location of the repository.
     * @param moreRecentCommit The more recent commit hash.
     * @param baseCommit The base commit hash to compare against. If this parameter is not provided, the diff will be calculated against the current working tree.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise containing the list of changed file paths.
     */
    getChangedPaths: (repoLocation: string, moreRecentCommit: string, baseCommit?: string, execOptions?: RunnerExecOptions) => Promise<string[]>;
    /**
     * Get the current commit hash of a repository.
     * @param repoLocation The location of the repository.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise containing the current commit hash.
     */
    getCurrentCommitHash: (repoLocation: string, execOptions?: RunnerExecOptions) => Promise<string>;
    /**
     * Show the contents of a file at a specific commit.
     * @param repoLocation The location of the repository.
     * @param filePath The path of the file, relative to the repository root.
     * @param commitHash The commit hash to show the file at.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     * @returns A promise containing the file contents.
     */
    showFileAtCommit(repoLocation: string, filePath: string, commitHash: string, execOptions?: RunnerExecOptions): Promise<string>;
    /**
     * Resolve baseCommit to a SHA. If it's already a SHA or exists locally, return it.
     * If it's a branch name that doesn't exist locally, fetch it from remote and resolve to SHA.
     *
     * @param location The repository location.
     * @param baseCommit The base commit to resolve.
     * @param execOptions The execution options. Optional, set to empty if not specified.
     *
     * @returns The resolved SHA of the base commit.
     */
    resolveBaseCommitToSha(location: string, baseCommit: string, execOptions?: RunnerExecOptions): Promise<string>;
    /**
     * Returns the Git OIDs of all tracked files (in the index and in the working
     * tree) that are under the given base path, including files in active
     * submodules. Untracked files and files not under the given base path are
     * ignored.
     *
     * @param basePath A path into the Git repository.
     * @returns a map from file paths (relative to `basePath`) to Git OIDs.
     * @throws {Error} if "git ls-files" produces unexpected output.
     */
    getFileOidsUnderPath(basePath: string): Promise<{
        [key: string]: string;
    }>;
    execGit(gitArgs: string[], execOptions: RunnerExecOptions, filteredCmdArgs?: string[]): Promise<RunnerExecOutput>;
    execReadOnlyGit(gitArgs: string[], execOptions: RunnerExecOptions, filteredCmdArgs?: string[]): Promise<RunnerExecOutput>;
    /**
     * Determine whether there are uncommitted changes that should be committed.
     * @param allowEmptyCommit Whether to allow empty commits.
     * @param repoLocation The location of the repository.
     * @returns Whether there are changes to commit.
     */
    shouldCommit(allowEmptyCommit: boolean, repoLocation: string): Promise<boolean>;
    /**
     * Configure GPG commit signing for the repository.
     * @param settings The runtime settings.
     * @param execOptions The execution options.
     */
    configureGpgSigning(settings: GitRuntimeSettings, execOptions: RunnerExecOptions): Promise<void>;
}

export declare type GitHubActionsJobAttachment = WireTypes.GitHubActionsJobAttachment;

/**
 * GitHub-anchored attachment variants. Each is a flat top-level discriminator
 * in the `Attachment` union (the SDK codegen pipeline does not support nested
 * `oneOf`-in-`oneOf`). `GitHubReferenceAttachmentSchema` is the original entry
 * and is preserved byte-for-byte; the remaining variants are typed pointers
 * with no inlined contents — the agent fetches content via tools as needed.
 */
export declare const githubAttachmentSchemas: readonly [z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_reference">;
    number: z_2.ZodNumber;
    title: z_2.ZodString;
    referenceType: z_2.ZodEnum<["issue", "pr", "discussion"]>;
    state: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    number: number;
    type: "github_reference";
    url: string;
    title: string;
    referenceType: "issue" | "pr" | "discussion";
    state: string;
}, {
    number: number;
    type: "github_reference";
    url: string;
    title: string;
    referenceType: "issue" | "pr" | "discussion";
    state: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_commit">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    oid: z_2.ZodString;
    message: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    type: "github_commit";
    message: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    oid: string;
}, {
    type: "github_commit";
    message: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    oid: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_release">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    tagName: z_2.ZodString;
    name: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    name: string;
    type: "github_release";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    tagName: string;
}, {
    name: string;
    type: "github_release";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    tagName: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_actions_job">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    jobId: z_2.ZodNumber;
    jobName: z_2.ZodString;
    workflowName: z_2.ZodString;
    url: z_2.ZodString;
    conclusion: z_2.ZodOptional<z_2.ZodString>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_actions_job";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    jobId: number;
    jobName: string;
    workflowName: string;
    conclusion?: string | undefined;
}, {
    type: "github_actions_job";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    jobId: number;
    jobName: string;
    workflowName: string;
    conclusion?: string | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_repository">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    url: z_2.ZodString;
    description: z_2.ZodOptional<z_2.ZodString>;
    ref: z_2.ZodOptional<z_2.ZodString>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_repository";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    description?: string | undefined;
    ref?: string | undefined;
}, {
    type: "github_repository";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    description?: string | undefined;
    ref?: string | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_file_diff">;
    url: z_2.ZodString;
    head: z_2.ZodOptional<z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        ref: z_2.ZodString;
        path: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }>>;
    base: z_2.ZodOptional<z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        ref: z_2.ZodString;
        path: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }>>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_file_diff";
    url: string;
    head?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
    base?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
}, {
    type: "github_file_diff";
    url: string;
    head?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
    base?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_tree_comparison">;
    url: z_2.ZodString;
    base: z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        revision: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }>;
    head: z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        revision: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_tree_comparison";
    url: string;
    head: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
    base: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
}, {
    type: "github_tree_comparison";
    url: string;
    head: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
    base: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_url">;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    type: "github_url";
    url: string;
}, {
    type: "github_url";
    url: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_file">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    ref: z_2.ZodString;
    path: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    type: "github_file";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    ref: string;
}, {
    type: "github_file";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    ref: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_snippet">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    ref: z_2.ZodString;
    path: z_2.ZodString;
    url: z_2.ZodString;
    lineRange: z_2.ZodObject<{
        start: z_2.ZodNumber;
        end: z_2.ZodNumber;
    }, "strip", z_2.ZodTypeAny, {
        end: number;
        start: number;
    }, {
        end: number;
        start: number;
    }>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_snippet";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    lineRange: {
        end: number;
        start: number;
    };
    ref: string;
}, {
    type: "github_snippet";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    lineRange: {
        end: number;
        start: number;
    };
    ref: string;
}>];

export declare type GitHubCommitAttachment = WireTypes.GitHubCommitAttachment;

export declare type GitHubFileAttachment = WireTypes.GitHubFileAttachment;

export declare type GitHubFileDiffAttachment = WireTypes.GitHubFileDiffAttachment;

/** 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, 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;
}

export declare type GitHubReferenceAttachment = WireTypes.GitHubReferenceAttachment;

export declare type GitHubReleaseAttachment = WireTypes.GitHubReleaseAttachment;

/** Pointer to a GitHub repository. */
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;
}

export declare type GitHubRepositoryAttachment = WireTypes.GitHubRepositoryAttachment;

export declare type GitHubSnippetAttachment = WireTypes.GitHubSnippetAttachment;

export declare type GitHubTreeComparisonAttachment = WireTypes.GitHubTreeComparisonAttachment;

export declare type GitHubUrlAttachment = WireTypes.GitHubUrlAttachment;

declare type GitRootResult = RuntimeNative.GitRootResult;

declare type GitRuntimeSettings = {
    api?: {
        copilot?: {
            sessionId?: string;
        };
    };
    featureFlags?: Record<string, unknown>;
    github?: {
        host?: string;
        hostProtocol?: string;
        serverUrl?: string;
        token?: string;
        user?: {
            name?: string;
            email?: string;
            actorId?: number;
            actorLogin?: string;
        };
        repo?: {
            name?: string;
            branch?: string;
            commit?: string;
            signCommits?: boolean;
        };
    };
    swebench_base_commit?: string;
    [key: string]: unknown;
};

declare const gptModelSupportsToolSearch: (model: string) => boolean;

/** 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_2;
}

/** Indicates whether the external tool call result was handled successfully. */
declare interface HandlePendingToolCallResult {
    /** Whether the tool call result was handled successfully */
    success: boolean;
}

/**
 * Handles a permission request result and returns an appropriate tool result.
 * Returns null if permission was approved, otherwise returns a denial/rejection result.
 */
declare function handlePermissionResult(result: PermissionRequestResult_2, options?: HandlePermissionResultOptions): ToolResultExpanded | null;

/**
 * Options for handling permission results.
 */
declare type HandlePermissionResultOptions = {
    /** Custom messages for denial cases */
    messages?: PermissionResultMessages;
    /** Whether autopilot mode is enabled (adds extra guidance to denial messages) */
    isAutopilotMode?: boolean;
};

/**
 * Yielded by {@link LocalSessionManager.handoffSession} when a non-fatal blocker
 * is encountered that the caller can choose to override (e.g. the current
 * working directory's repository does not match the remote session's
 * repository). The consumer resumes the generator with a
 * {@link HandoffConfirmationResponse} to indicate whether to proceed.
 */
declare interface HandoffConfirmationRequest {
    kind: "confirmation";
    /** The kind of blocker awaiting confirmation. */
    confirmation: "repository-mismatch";
    /** The repository detected in the current working directory. */
    localRepo: string;
    /** The repository the remote session belongs to. */
    remoteRepo: string;
}

/** Response passed back into {@link LocalSessionManager.handoffSession} for a {@link HandoffConfirmationRequest}. */
declare interface HandoffConfirmationResponse {
    /** Whether to proceed with the handoff despite the blocker. */
    confirmed: boolean;
}

/** Session handoff metadata including source, context, and repository information */
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";
}

/**
 * Git operations needed for remote→local session handoff.
 * Injected by CLI so that LocalSessionManager has no direct dependency on CLI git helpers.
 */
export declare interface HandoffGitOperations {
    getRepositoryInfo(cwd: string): Promise<{
        repository: string;
    }>;
    getUncommittedChangesCount(cwd: string): Promise<{
        staged: number;
        unstaged: number;
        untracked: number;
        hasChanges: boolean;
    }>;
    switchToBranch(branch: string, cwd: string): Promise<void>;
}

declare interface HandoffProgress {
    step: HandoffStep;
    status: "in-progress" | "complete";
    message?: string;
}

/** Repository context for the handed-off session */
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 */
declare type HandoffSourceType = "remote" | "local";

declare type HandoffStep = "load-session" | "validate-repo" | "check-changes" | "checkout-branch" | "create-session" | "save-session";

/** Single HTTP header entry as a name/value pair. */
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;
}

/** Models visible in help text and CLI --model choices (excludes {@link HIDDEN_MODELS} and {@link SUBAGENT_ONLY_MODELS}) */
export declare const HELP_VISIBLE_MODELS: readonly SupportedModel[];

/**
 * **Visibility & Access Control:**
 * - Hidden models are excluded from help text and CLI `--model` choices (see {@link HELP_VISIBLE_MODELS})
 * - When CAPI returns a hidden model as available (policy enabled), it is **always shown** in the
 *   `/model` picker regardless of staff status — CAPI is the source of truth for authorization
 * - When CAPI does not return a hidden model (or returns it as blocked/unconfigured), it is
 *   excluded from the blocked/disabled/upgrade lists for non-staff users to keep the picker clean
 * - Staff users always see hidden models in all categories (available, blocked, upgrade-needed)
 *
 * Note: models reserved exclusively for a trusted built-in subagent belong in
 * {@link SUBAGENT_ONLY_MODELS}, not here — hidden models can still surface in the picker when CAPI
 * enables them, whereas subagent-only models never can.
 *
 * Keep in sync with `HIDDEN_MODELS_LIST` in `src/runtime/src/model/catalog.rs`.
 */
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;
}

/** 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;
};

/** 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;
}

/** 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 {
    /** 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_2;
    /** 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";
}

declare class HolderGenerationChangedError extends Error {
    constructor();
}

declare class HolderTerminatedError extends Error {
    constructor();
}

/** Hook invocation completion details including output, success status, and error information */
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 */
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;
}

export declare type HookEndEvent = WireTypes.HookEndEvent;

/** Session event "hook.end". Hook invocation completion details including output, success status, and error information */
declare interface HookEndEvent_2 {
    /** 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 `createPermissionService`.
 */
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 */
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;
}

export declare type HookProgressEvent = WireTypes.HookProgressEvent;

/** Session event "hook.progress". Ephemeral progress update from a running hook process */
declare interface HookProgressEvent_2 {
    /** 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 */
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;
}

export declare type HookStartEvent = WireTypes.HookStartEvent;

/** Session event "hook.start". Hook invocation start details including type and input data */
declare interface HookStartEvent_2 {
    /** 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";
}

/**
 * Host context exposed to the guest UI on initialization, and via
 * `ui/notifications/host-context-changed` for partial updates (SEP-1865).
 */
declare interface HostContext {
    /** Metadata of the tool call that instantiated the View. */
    toolInfo?: {
        /** JSON-RPC id of the originating `tools/call` request. */
        id?: number | string;
        /** The tool that was called (name, inputSchema, etc.). */
        tool?: Record<string, unknown>;
    };
    /** Current color theme preference. */
    theme?: "light" | "dark";
    /** Style configuration for theming. */
    styles?: {
        /** CSS custom properties the view can reference. */
        variables?: Record<string, string | undefined>;
        /** CSS blocks the view can inject (e.g., `@font-face` rules). */
        css?: {
            fonts?: string;
        };
    };
    /** Current display mode. */
    displayMode?: McpUiDisplayMode;
    /** Display modes the host supports. Views should check before requesting changes. */
    availableDisplayModes?: McpUiDisplayMode[];
    /**
     * Container dimensions. `width`/`height` are fixed; `maxWidth`/`maxHeight`
     * are flexible upper bounds; absence means unbounded.
     */
    containerDimensions?: {
        width?: number;
        height?: number;
        maxWidth?: number;
        maxHeight?: number;
    };
    /** BCP-47 locale (e.g., `"en-US"`). */
    locale?: string;
    /** IANA timezone (e.g., `"America/New_York"`). */
    timeZone?: string;
    /** Host application identifier (free-form). */
    userAgent?: string;
    /** Platform type for responsive design. */
    platform?: "web" | "desktop" | "mobile";
    /** Device capabilities. */
    deviceCapabilities?: {
        touch?: boolean;
        hover?: boolean;
    };
    /** Safe-area insets in pixels (e.g. notches, home indicators). */
    safeAreaInsets?: {
        top: number;
        right: number;
        bottom: number;
        left: number;
    };
    /** Forward-compat catchall for fields added in later spec revisions. */
    [key: string]: unknown;
}

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"];
}

/**
 * Union type for all Hydro events that can be sent.
 * Standard events have `restricted?: false`. Restricted events (`cli.restricted_telemetry`)
 * require `restricted: true` to ensure they are routed to the restricted telemetry client.
 */
declare type HydroEvent = ({
    name: "cli.telemetry";
    event: HydroTelemetry;
} & {
    restricted?: false;
}) | ({
    name: "cli.restricted_telemetry";
    event: HydroRestrictedTelemetry;
} & {
    restricted: true;
});

/**
 * Restricted bag-shaped telemetry event.
 * Maps to: copilot_cli.v0.RestrictedTelemetry (restricted_telemetry.proto)
 */
declare interface HydroRestrictedTelemetry {
    /** Event type/kind */
    kind: string;
    /** Timestamp when the event was created (ISO 8601 format) */
    created_at?: string;
    /** Reference to the model call that produced this event */
    model_call_id?: string;
    /** Joined properties including restricted props */
    properties: Record<string, string | undefined>;
    /** Numeric metrics */
    metrics: Record<string, number | undefined>;
    /** Experiment assignment context */
    exp_assignment_context?: string;
    /** Feature flags enabled for this session */
    features?: Record<string, string>;
    /** Session identifier (auto-filled by SessionTelemetry) */
    session_id?: string;
    /** Copilot tracking ID for user-level attribution */
    copilot_tracking_id?: string;
    /** Client environment metadata */
    client?: ClientInfo;
}

/**
 * Generic bag-shaped telemetry event.
 * Maps to: copilot_cli.v0.Telemetry (telemetry.proto)
 */
declare interface HydroTelemetry {
    /** Event type/kind (e.g., "get_completion_with_tools_turn", "tool_call_executed") */
    kind: string;
    /** Timestamp when the event was created (ISO 8601 format) */
    created_at?: string;
    /** Reference to the model call that produced this event */
    model_call_id?: string;
    /** Non-restricted properties (key-value pairs) */
    properties: Record<string, string | undefined>;
    /** Numeric metrics */
    metrics: Record<string, number | undefined>;
    /** Experiment assignment context */
    exp_assignment_context?: string;
    /** Feature flags enabled for this session */
    features?: Record<string, string>;
    /** Session identifier (auto-filled by SessionTelemetry) */
    session_id?: string;
    /** Copilot tracking ID for user-level attribution */
    copilot_tracking_id?: string;
    /** Client environment metadata */
    client?: ClientInfo;
}

declare interface HydroTelemetryOptions {
    clientName?: string;
    featureFlagService?: IFeatureFlagService;
    sendRestrictedTelemetry?: boolean;
}

/**
 * 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 */
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";
}

declare type IfcAgentMode = "interactive" | "plan" | "autopilot" | "shell";

declare class IFCEngine implements IPreToolsExecutionProcessor, IPostToolExecutionProcessor, IFCStateProjector {
    private readonly logger;
    private readonly telemetry?;
    private contextLabel;
    private agentMode;
    private searchRepositoriesTool;
    private settings;
    private readonly getWorkingDir;
    private readonly repoVisibilityCache;
    private readonly resolvers;
    constructor(logger: RunnerLogger, initialLabel?: SecurityLabel, telemetry?: TelemetrySender | undefined, getWorkingDir?: () => string);
    /**
     * Sets the MCP tool used to check repository visibility.
     * Called after tools are loaded (they are not available at construction time).
     */
    setSearchRepositoriesTool(tool: Tool | undefined, settings?: RuntimeSettings_3): void;
    getContextLabel(): SecurityLabel;
    setContextLabel(label: SecurityLabel): void;
    setAgentMode(agentMode: IfcAgentMode): void;
    /** Visible for testing. */
    getRepoVisibilityCache(): ReadonlyMap<string, RepoVisibility>;
    toJSON(): string;
    getRepoVisibility(owner: string, repo: string): Promise<RepoVisibility | undefined>;
    private emitVisibilityLookup;
    /**
     * Queries the `search_repositories` MCP tool to determine whether a
     * repository is public or private, reporting a typed outcome so the caller
     * can distinguish a clean miss (`unknown`) from a thrown error (`error`)
     * for telemetry. Returns `visibility: undefined` when the tool is
     * unavailable or the response cannot be parsed.
     */
    private fetchRepoVisibilityWithOutcome;
    private parseRepoVisibility;
    createPreToolUseHook(agentMode?: IfcAgentMode): (input: IFCPreToolUseInput) => Promise<void>;
    /**
     * Records which path a GitHub egress took (gated MCP sink vs `gh`-via-bash).
     * Observe-only; wrapped so a telemetry fault never breaks the tool call.
     */
    private emitEgressRoute;
    preToolsExecution(context: PreToolsExecutionContext): Promise<PreToolsExecutionResult>;
    /**
     * Emit the per-evaluation policy telemetry. Integrity/confidentiality are
     * reported as levels + repo COUNT only (never names — see PII rule in
     * `fidesIfcTelemetry.ts`). The audience level is omitted when unresolved so
     * the `audience_resolved` flag is the single source of truth.
     */
    private emitPolicyEvaluated;
    postToolExecution(context: PostToolExecutionContext): Promise<void>;
    applyToolIngress(payload: IFCIngressPayload): Promise<void>;
    /**
     * Emits the per-ingress coverage/taint-acquisition event. `previous` and
     * `next` are the context labels before and after the join, used to derive
     * whether taint rose and which axis transitioned first. Wrapped in try/catch
     * so a telemetry failure can never break enforcement.
     */
    private emitLabelObserved;
    private synthesizeBuiltinToolLabel;
    private isIngressCoverageEligible;
}

declare interface IFCIngressPayload {
    toolName: string;
    toolArgs: unknown;
    mcpMeta?: Record<string, unknown>;
    resultType?: "success" | "failure" | "timeout" | "denied" | "rejected";
}

declare interface IFCPreToolUseInput {
    toolName: string;
    toolArgs: unknown;
}

declare interface IFCStateProjector {
    applyToolIngress(payload: IFCIngressPayload): Promise<void>;
    getContextLabel(): SecurityLabel;
    setContextLabel(label: SecurityLabel): void;
}

export declare type IFeatureFlagService = Omit<FeatureFlagService, "destroy" | "dispose" | "resetExpResponse" | "resetInstance">;

export declare type ImageContent = WireTypes.ImageContent;

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;
}

declare class Inbox {
    private entries;
    private dbProvider?;
    private loaded;
    private loadPromise?;
    configurePersistence(dbProvider: () => SessionDatabase | undefined): void;
    send(input: SendInboxEntryInput): Promise<InboxEntry>;
    read(options?: ReadInboxEntryOptions): Promise<InboxEntry | undefined>;
    getUnreadUnnotifiedEntries(): Promise<InboxEntry[]>;
    markNotified(entryId: string): Promise<InboxEntry | undefined>;
    getById(entryId: string): Promise<InboxEntry | undefined>;
    /** Returns entries sent by a specific sender for a specific interaction. */
    getEntriesBySenderAndInteraction(senderId: string, interactionId: string): Promise<InboxEntry[]>;
    private ensureLoaded;
    private doLoad;
    private runMigrations;
    private applySend;
    private persistEntry;
    private persistReadState;
    private persistNotificationState;
    private prunePersistedEntries;
}

declare type InboxEntry = {
    id: string;
    recipientSessionId: string;
    senderId: string;
    senderName: string;
    senderType: string;
    interactionId: string;
    sequence: number;
    summary: string;
    content: string;
    sentAt: number;
    unread: boolean;
    readAt?: number;
    notifiedAt?: number;
};

/**
 * 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 */
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";
}

/** Inputs for {@link ingestManagedSettings}. */
declare interface IngestManagedSettingsInput {
    /**
     * When `true`, self-fetch server-managed settings and load device MDM policy.
     * Requires `authInfo` for the server fetch. Left unset when there is no auth
     * context to fetch with.
     */
    selfFetch?: boolean;
    /** Auth used to self-fetch server-managed settings. */
    authInfo?: AuthInfo;
    /** Abort signal forwarded to the server fetch. */
    signal?: AbortSignal;
    /**
     * Test seam: override the server-fetch implementation. Defaults to
     * {@link fetchManagedSettings}.
     */
    fetchImpl?: (host: string, token: string, signal?: AbortSignal) => Promise<ManagedSettingsResponse | undefined>;
    /**
     * Test seam: override the device-MDM loader. Defaults to
     * {@link loadMdmManagedSettings}.
     */
    loadDeviceImpl?: () => ManagedSettingsResponse | undefined;
    /** Resolves the bearer token for `authInfo`. */
    getToken?: (authInfo: AuthInfo) => Promise<string | undefined>;
}

declare class InProcMCPTransport extends MCPTransport<ClientInfo_2> {
    constructor(settings: RuntimeSettings, logger: RunnerLogger, cacheProviderTools?: boolean);
    protected loadDescriptors(clientInfo: ClientInfo_2): Promise<RustMcpToolDescriptor[]>;
    refreshProvider(clientInfo: ClientInfo_2): Promise<void>;
    invokeTool(toolId: string, toolParams: Record<string, unknown>, filterMode?: ContentFilterMode_2, toolCallId?: string): Promise<ToolResultExpanded>;
    protected invokeDescriptorTool(toolId: string, toolParams: Record<string, unknown>, filterMode: ContentFilterMode_2, 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;
    /** 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, and optional subpath. */
declare interface InstalledPluginSourceGitHub {
    path?: string;
    ref?: string;
    repo: 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, and optional subpath. */
declare interface InstalledPluginSourceUrl {
    path?: string;
    ref?: string;
    /** Constant value. Always "url". */
    source: "url";
    url: string;
}

declare const INSTRUCTION_DISCOVERY_MESSAGE_SOURCE = "instruction-discovery";

/** 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 sources, where it disambiguates same-named files (e.g. .github/copilot-instructions.md) 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;
}

declare type InstructionSource_2 = {
    /** Unique identifier for this source (used for toggling) */
    id: string;
    /** Human-readable label */
    label: string;
    /** File path relative to repo or absolute for home */
    sourcePath: string;
    /** Raw content of the instruction file */
    content: string;
    /** Category of instruction source — used for merge logic */
    type: InstructionSourceType_2;
    /** Where this source lives — used for UI grouping */
    location: InstructionSourceLocation_2;
    /** Glob pattern(s) from frontmatter — when set, this instruction applies only to matching files */
    applyTo?: string[];
    /** Short description from frontmatter for use in instruction tables */
    description?: string;
    /** When true, this source starts disabled and must be toggled on by the user */
    defaultDisabled?: boolean;
};

/** Source of an indexed instruction entry. */
declare type InstructionSource_3 = "mcp-server" | "skill";

/** Where this source lives — used for UI grouping */
declare type InstructionSourceLocation = "user" | "repository" | "working-directory" | "plugin";

/** Where an instruction source lives — used for UI grouping */
declare enum InstructionSourceLocation_2 {
    User = "user",
    Repository = "repository",
    WorkingDirectory = "working-directory",
    Plugin = "plugin"
}

/** Category of instruction source — used for merge logic */
declare type InstructionSourceType = "home" | "repo" | "model" | "vscode" | "nested-agents" | "child-instructions" | "plugin";

/** Represents an individual instruction source before merging */
/** Category of instruction source — used for merge logic */
declare enum InstructionSourceType_2 {
    Home = "home",
    Repo = "repo",
    Model = "model",
    VSCode = "vscode",
    NestedAgents = "nested-agents",
    ChildInstructions = "child-instructions",
    Plugin = "plugin"
}

export declare const INTEGRATION_ID: string;

/**
 * Two-level integrity lattice following the FIDES paper (arXiv 2505.23643v2, §4.1):
 *   T ⊑ U  (trusted flows to untrusted)
 *   join(T, U) = U  (taint propagation: LUB is the less-trusted value)
 *   meet(T, U) = T  (GLB is the more-trusted value)
 *
 * Numeric encoding: trusted = 0, untrusted = 1.
 */
declare class IntegrityLabel implements Lattice<IntegrityLabel> {
    readonly level: "trusted" | "untrusted";
    private constructor();
    static trusted(): IntegrityLabel;
    static untrusted(): IntegrityLabel;
    static fromString(s: string): IntegrityLabel;
    private get numericLevel();
    leq(other: IntegrityLabel): boolean;
    /** Least upper bound: returns the less-trusted (higher) value. */
    join(other: IntegrityLabel): IntegrityLabel;
    /** Greatest lower bound: returns the more-trusted (lower) value. */
    meet(other: IntegrityLabel): IntegrityLabel;
    equals(other: IntegrityLabel): boolean;
    toString(): string;
    toJSON(): string;
}

/** 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;
    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_2>;
    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 assessSafety;
    private checkExclusion;
    private requestPermission;
    private consumeNotification;
    private completeCommand;
    private publishPartialOutput;
    private emitSandboxTelemetry;
    private stopDescription;
}

export declare namespace internal {
    export {
        AppInsightsTelemetryService,
        NoopTelemetryService,
        SessionTelemetry,
        missingRemoteBranchWarning,
        loadPersistedSessionCwd,
        HandoffStep,
        HandoffProgress,
        HandoffConfirmationRequest,
        HandoffConfirmationResponse,
        PruneResult,
        ForkSessionOptions,
        ForkSessionResult,
        LocalSessionManagerOptions,
        PersistedSessionCwdInfo,
        ResumeBehavior,
        LocalSessionManager
    }
}

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>;
}

export declare function isAgentsTabEnabled(featureFlags: FeatureFlags | 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): boolean;

declare function isAutopilotContinuationMessage(prompt: string): boolean;

declare function isCcaUseTsAutofindEnabled(settings: unknown): boolean;

declare function isCodeReviewFeatureEnabled(settings: unknown): boolean;

/**
 * Returns true if the DEBUG or COPILOT_AGENT_DEBUG environment variable is set to 1 or true (case-insensitive).
 * If additionalVariables are provided, they are also checked.
 * @param additionalVariables Additional environment variables to check for debug logging.
 */
export declare function isDebugEnvironment(...additionalVariables: string[]): boolean;

export declare const isFeatureFlag: (flag: string) => flag is FeatureFlag;

declare const isLargeOutputEnabled: (options?: Pick<LargeOutputOptions, "enabled">) => boolean;

declare const isStrReplaceEditorCall: (call: CopilotChatCompletionMessageToolCall) => call is ChatCompletionMessageFunctionToolCall & {
    function: {
        name: string;
    };
};

declare function isToolResultExpanded(result: ToolResult): result is ToolResultExpanded;

/**
 * Type guard that checks if an external tool's parameters schema is valid for use as a ToolInputSchema.
 * Tool input schemas must be objects (type: "object") since function calling requires named parameters.
 * Returns true if the schema is undefined (will use default empty object) or has type "object".
 */
export declare function isValidToolParametersSchema(schema: ExternalToolDefinition["parameters"]): schema is ToolInputSchema;

declare const isWriteToFileStrReplaceEditorCommand: (c: string) => 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_OBJECTIVES?: boolean;
    FORGE_AGENT_ENABLED?: boolean;
}

declare const LARGE_OUTPUT_DISABLED_THRESHOLD_BYTES: number;

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;
}

declare const LARK_AUTOPILOT_CONTINUATION_MESSAGE: string;

/**
 * A lattice provides a partial order with join (least upper bound) and meet (greatest lower bound).
 * Used for information flow control label algebra.
 */
declare interface Lattice<T> {
    leq(other: T): boolean;
    join(other: T): T;
    meet(other: T): T;
}

/** 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;
}

declare function liveSandboxFromConfig(config: ToolConfig): SandboxConfig_2;

declare const llmToolRejectionMessage = "The tool call required approval from the user, but the user rejected it or an earlier tool call.";

export declare function loadFeatureFlagsFromConfig(config: UserSettings, featureFlags: FeatureFlags): FeatureFlags;

export declare function loadFeatureFlagsFromEnv(featureFlags: FeatureFlags): FeatureFlags;

/**
 * Loads a session's persisted cwd from `workspace.yaml`.
 *
 * Returns `{ cwd: undefined, persistedFieldPresent: false }` for missing files,
 * missing/empty cwd fields, I/O failures, and parse failures. Invalid persisted
 * directories return `{ cwd: undefined, persistedFieldPresent: true }`.
 */
declare function loadPersistedSessionCwd(sessionId: string, settings: SettingsStorageContext | undefined): Promise<PersistedSessionCwdInfo>;

/**
 * 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;
}

/**
 * Raw JSON result of a local session store query.
 */
declare interface LocalQueryResultRaw {
    rowsJson: string;
    truncated: boolean;
}

/**
 * Session class with event sourcing
 */
declare class LocalSession extends Session<LocalSessionMetadata> {
    readonly isRemote: false;
    private nativeCallbackRuntime?;
    private readonly callbackRuntimeDelegate;
    private callback;
    private isProcessing;
    /**
     * Display prompts of steering messages that have been injected into the
     * active turn (delivery `"steering"`, i.e. folded into an in-flight
     * request) but whose reply has not yet been committed. `getQueue()` on
     * the immediate processor no longer contains these once injected, so
     * without this list `getPendingSteeringMessagesDisplayPrompt()` would stop
     * reporting a steering interjection as pending the instant it is folded
     * into a request -- often within the same tick it was submitted, well
     * before its reply streams back -- even though the interjection is still
     * awaiting a reply and the UI should keep showing it as pending (including
     * across a session switch away and back). Cleared once the whole busy
     * cycle (including any redirected/folded turns) finishes, see the
     * `isProcessing = false` assignment below.
     */
    private inFlightSteeringMessages;
    private itemQueue;
    /**
     * Monotonic counter shared between `itemQueue` and the immediate steering
     * queue so we can identify the most recently added pending item across
     * both queues regardless of which one received it last.
     */
    private nextPendingOrder;
    /**
     * Tracks insertion order for pending items keyed by item identity. Used
     * by `removeMostRecentPendingItem()` to honor LIFO removal across both
     * the immediate steering queue and the queued-items queue.
     */
    private pendingItemOrder;
    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 cachedSettings?;
    private lastDeferredToolHintMessage;
    protected getCurrentSettingsForHandle(): RuntimeSettings;
    protected clearCachedAutoModeSessionTokenFromSettings(): void;
    protected getToolConfig(): ToolConfig | undefined;
    protected invalidateAgentToolConfig(): void;
    private getMcpServerDisplayNames;
    private queueDeferredToolHintIfNeeded;
    private _retainedClient;
    private _activeClient;
    private modelClientLifecycleDisposed;
    private readonly disposedModelClients;
    private readonly clientsPendingDisposal;
    private immediatePromptProcessor;
    private responseLimitsPreRequestProcessor;
    private initializedSessionLimitsTelemetry;
    private hasEmittedSessionLimitsTerminalError;
    private hasEmittedSessionLimitsTerminalWarning;
    private compactionProcessor;
    readonly sidekickAgentManager: SidekickAgentManager;
    protected onUsageMetricsUpdated(event: SessionEvent): void;
    protected getResponseLimitsPreRequestProcessorForSubagent(): ResponseLimitsPreRequestProcessor | undefined;
    setInheritedResponseLimitsPreRequestProcessor(processor: ResponseLimitsPreRequestProcessor): void;
    private emitAbortCancellation;
    private removeAbortedAssistantText;
    private appendMissingAbortToolCallMessage;
    private hasAssistantToolCall;
    private getCurrentTurnStartedToolRequestsForAbort;
    private getAbortSyntheticToolResultContent;
    /**
     * Get background tasks from the sidekick agent registry.
     * Returns only agent tasks (sidekick agents don't have shell entries).
     */
    getSidekickBackgroundTasks(): BackgroundTask[];
    get hasActiveWork(): 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;
    /** Embedding-based instruction retrieval processor handle (Rust napi). */
    private embeddingRetrievalHandle?;
    /** Provider label the handle was built for; reset on provider change. */
    private embeddingRetrievalProviderLabel?;
    /** Dirty flag: when true the embedding instruction index needs to be (re)built. */
    private instructionIndexDirty;
    /** Promise for the in-progress index rebuild so concurrent callers can await it. */
    private instructionIndexRebuildPromise?;
    /** Tracks the skills cache generation at last index build to detect skill changes. */
    private lastSkillsCacheGeneration;
    private pendingAbortReason?;
    /** True while the queue is sleeping during a rate-limit pause. */
    private isPausedForRateLimit;
    private disposeClient;
    private disposeRetainedClient;
    private invalidateModelBoundRuntimeCaches;
    private activeSubAgents;
    mcpHostCache: McpHostCache;
    /** Per-session telemetry sender, supplied at construction. */
    protected sessionTelemetry?: DisposableTelemetrySender;
    /**
     * Registration handle for this session's runtime log sink, when active.
     * Set by {@link attachRuntimeLogSink} once the session goes live and torn
     * down in {@link dispose}. `undefined` until attached (and after disposal).
     */
    private runtimeLogRegistration?;
    /**
     * Routes session-correlated Rust runtime logs (delivered via the process-
     * global runtime log bridge) onto this session's event stream as
     * `session.{info,warning,error}` events.
     *
     * Called once the session becomes a live, top-level session (from the
     * session manager, right after it enters `activeSessions`). Idempotent.
     *
     * Only top-level sessions register: subagent sessions share their parent's
     * `sessionId` (see {@link createSubagentSession}), so a per-`sessionId`
     * registry would collide if both registered. A subagent-initiated runtime
     * log still surfaces correctly — it carries the shared parent `sessionId`
     * and so resolves to the parent's sink, and the record's `agentId` flows
     * through to the emitted event for correct sub-agent attribution.
     */
    attachRuntimeLogSink(): void;
    /** Tear down per-session resources and clear the telemetry sender. */
    dispose(): Promise<void>;
    shutdown(params?: ShutdownParams): Promise<void>;
    private hasEmittedModelResolutionInfo;
    private autoModeTelemetryToken?;
    private warnedUnknownTools;
    private sessionWorkspace;
    private workspaceEnabled;
    private _workspaceManager;
    private lastTodoContent;
    private lastPlanUpdateTurn;
    private static readonly PLAN_REMINDER_TURN_THRESHOLD;
    private readonly memoryApiCache;
    /** Store + repo + branch for the dynamic context board tool (set even when the board is empty). */
    private _dynamicContextConfig;
    /**
     * Tools that should be hidden from the default (top-level) agent but still
     * available to custom subagents (sidekicks, task-tool subagents) that
     * allowlist them. Mutated internally — kept separate from the user-facing
     * `defaultAgentExcludedTools` SDK option so that values added here do not
     * leak into telemetry or SDK consumers reading that field back.
     */
    private readonly internalDefaultAgentExcludedTools;
    /** 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 compactionCancelled;
    private manualCompactionAbortController;
    private idleDeferredByBackgroundWork;
    private idleDeferredAborted;
    /**
     * When true, the next abort triggered by {@link interruptMainTurn} unwinds
     * only the main agentic loop and leaves running background work (subagents,
     * sidekicks, promoted attached shells) alive. Consumed by both
     * {@link cancelProcessing} (the synchronous teardown) and the post-loop
     * re-cancel block in {@link processQueuedItems} (the late-agent sweep), then
     * reset once the aborted loop has fully unwound. This powers the CLI's
     * "interrupt the coordinator but keep the workers" (double-Esc) behavior so
     * background agents are only stopped by a separate, explicit escalation.
     */
    private preserveBackgroundWorkOnPendingAbort;
    /**
     * When true, an {@link interruptMainTurn} abort preserved the user's queued
     * messages (only hidden system items were dropped) and wants them delivered
     * as the next turn once the aborted loop unwinds. If no notifying background
     * work is in flight the queue is drained immediately; otherwise the
     * preserved items ride the normal deferred-idle drain and start once that
     * work settles. Consumed and reset in {@link processQueuedItems}.
     */
    private flushQueuedAfterAbort;
    /**
     * 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);
    /**
     * Normalize infiniteSessions config from boolean or object to a full config object.
     */
    private normalizeInfiniteSessionsConfig;
    /**
     * 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(): void;
    /**
     * Cached set of injection marker keys present in prior user messages.
     * Lazily populated; updated incrementally as new markers are injected;
     * cleared by `onCompactionApplied` since compaction rewrites `_chatMessages`.
     */
    private cachedPriorInjectedMarkers;
    /**
     * Marker keys (`mcp:<name>` / `skill:<name>`) already injected in prior
     * user messages, used by embedding retrieval to dedup across `--resume`
     * boundaries where the in-process emitted-id set was lost. Caller must
     * incrementally add any new markers it injects.
     */
    private getPriorInjectedMarkers;
    getMetadata(): LocalSessionMetadata;
    /**
     * Get the per-session WorkspaceManager, if available.
     */
    getWorkspaceManager(): WorkspaceManager | null;
    /** Internal throwing accessor for methods that require workspace to be enabled. */
    private requireWorkspaceManager;
    /**
     * 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;
    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>;
    getAutopilotObjectivePath(): string | null;
    readAutopilotObjective(): Promise<string | null>;
    writeAutopilotObjective(content: string): Promise<"create" | "update">;
    deleteAutopilotObjective(): Promise<boolean>;
    autopilotObjectiveExists(): Promise<boolean>;
    /**
     * 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>;
    /**
     * Update the last todo content (called when update_todo tool is used).
     * This content will be included in post-compaction messages.
     */
    setLastTodoContent(content: string | null): void;
    /**
     * Get the last todo content.
     */
    getLastTodoContent(): string | null;
    /**
     * Check if a plan update reminder should be shown.
     * Returns true if:
     * - Workspace is enabled
     * - Plan.md hasn't been updated in the last N turns
     * - A plan.md file exists (we only remind to update, not create)
     */
    shouldShowPlanReminder(): Promise<boolean>;
    /**
     * Get the plan reminder message to inject into user prompts.
     * Returns null if no reminder should be shown.
     */
    getPlanReminderMessage(): Promise<string | null>;
    /**
     * Build a per-turn reminder describing the LSP language servers currently
     * tracked for this session (their `read_agent` agent ids and status), and how
     * to use `read_agent` to inspect them. Returns null when no servers are
     * tracked, so the reminder only appears once at least one LSP server has
     * started (e.g. via warmup or first `lsp` tool use).
     *
     * This is injected each turn (rather than baked into the static system
     * prompt) because the set of servers and their readiness changes over the
     * session, and a stale snapshot would mislead the agent about which ids are
     * live.
     */
    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;
    /**
     * Emit telemetry when agent writes to a workspace file (plan.md or files/).
     */
    private emitWorkspaceFileTelemetry;
    /**
     * Emit telemetry when agent reads a workspace file (plan.md, checkpoints, or files/).
     */
    private emitWorkspaceFileReadTelemetry;
    /**
     * 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<InstructionSource_2[]>;
    /**
     * 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 the resulting chat message
     * is handed to the ImmediatePromptProcessor so the current model call
     * includes it — no branching needed inside the processor. 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: SystemNotificationKind | 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: SystemNotificationKind, delivery?: SendOptions["notificationDelivery"]): number;
    private emitBackgroundNotificationSyntheticRead;
    private consumePendingSystemNotifications;
    private queuePostToolUseFailureContext;
    private runPostToolUseFailureHooks;
    private processToolExecutionResult;
    /**
     * Fire notification hooks for a given notification event.
     * Non-blocking — native failures are logged by the hook facade.
     * If any hook returns additionalContext, it's injected as a prepended user message.
     */
    private fireNotificationHook;
    /** 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.
     *
     * For `kind: "message"` items, the wrapper inherits any insertion-order
     * stamp already attached to `item.options` — this preserves true LIFO
     * ordering for `removeMostRecentPendingItem()` when an item moves between
     * queues (e.g. an immediate steering message popped into the main queue
     * via `processQueuedItems()`). Fresh sends have no stamp on `options`
     * and get a new one allocated.
     *
     * @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;
    /**
     * Record a steering message's display prompt as in-flight: injected into
     * the active turn but awaiting its reply. See
     * {@link LocalSession.inFlightSteeringMessages}.
     */
    recordInFlightSteeringMessage(displayPrompt: string): void;
    private setPendingMessageDelivery;
    private shouldUseStableHmacNoUserInteractionId;
    private getStableHmacNoUserInteractionId;
    private getModelRequestInteractionId;
    /**
     * Add a message to the immediate steering queue and stamp it with an
     * insertion order so `removeMostRecentPendingItem()` can compare it
     * against entries in `itemQueue`.
     */
    private addImmediateMessage;
    /**
     * Enqueue any item (command or message) to be processed after the current agentic work completes.
     * Items are processed in FIFO order.
     *
     * If the session is not currently processing, this will also kick off queue processing.
     * This ensures that items transferred from another session (e.g., after /clear)
     * actually get executed even if there are no messages to trigger processing.
     *
     * @param item - The queued item (either a command or message)
     */
    enqueueItem(item: QueuedItem): void;
    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): void;
    /**
     * Enqueue a user message item to be processed later.
     * This is a utility for creating properly typed message queue items.
     * Uses addItemToQueue internally for consistent mode normalization.
     *
     * @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;
    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;
    /**
     * 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;
    /**
     * 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;
    /**
     * Check if the session is currently processing queued items.
     * Returns true when processQueuedItems() is actively running (e.g., during
     * an autopilot continuation that was started as fire-and-forget).
     */
    isProcessingMessages(): boolean;
    /**
     * 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_2, reasoningSummary?: ReasoningSummary_3, contextTier?: ContextTier_3, verbosity?: Verbosity_3): Promise<void>;
    /**
     * 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 `processQueuedItems`. 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;
    /**
     * 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 sessionShellHasCommandsAwaitingNotification;
    private hasNotifyingBackgroundWork;
    private trackBackgroundNotificationTask;
    private isBackgroundTaskNotificationPayloadsEnabled;
    private emitSessionIdle;
    private emitDeferredSessionIdleIfReady;
    /**
     * 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`.
     */
    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).
     *
     * Includes both messages still waiting to be sent (`immediatePromptProcessor`'s
     * queue) AND ones already folded into the active turn but whose reply hasn't
     * committed yet ({@link inFlightSteeringMessages}) -- the latter is what keeps
     * a steering interjection showing as pending across a session switch instead
     * of disappearing the instant it is injected into a request.
     */
    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>;
    /**
     * @deprecated Use getPendingQueuedItems() instead for proper display of mixed queue items.
     */
    getPendingQueuedMessages(): ReadonlyArray<string>;
    /**
     * 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;
    /**
     * Drop only the hidden `source: "system"` items (hook context, system
     * notifications) from both the steering and main queues, preserving every
     * user-facing pending message/command.
     *
     * This is the "flush" counterpart to {@link clearPendingItems}: when the
     * user interrupts the main turn but wants their queued prompts delivered
     * next, we must still evict system items. Otherwise the post-abort drain
     * would re-run them and, because they can recursively enqueue more system
     * work, strand the UI in a "cancelling" state (the same hazard that made
     * the abort path clear the whole queue). Keeping user items lets the normal
     * queue drain deliver them once the aborted loop unwinds.
     *
     * @returns true if any user-facing pending item remains after the sweep.
     */
    private clearSystemPendingItems;
    /**
     * Interrupt the current main agentic turn while leaving running background
     * work (subagents, sidekicks, promoted attached shells) alive.
     *
     * This is the runtime half of the CLI's double-Esc "interrupt" rule: a
     * running coordinator is stopped, but the workers it spawned keep going so
     * the user can either let them finish or escalate. The follow-up escalation
     * ({@link cancelAllBackgroundAgents}) stops the preserved subagents and
     * sidekicks; promoted attached shells are not agents, so they keep running
     * until they finish naturally or the user cancels them via `/tasks`. It
     * differs from {@link abort} (which tears down all background work) purely in
     * what it spares — see {@link cancelProcessing}'s `preserveBackgroundWork`
     * gate.
     *
     * With `flushQueued`, the user's queued prompts are preserved (only hidden
     * system items are dropped) so they are delivered as the next turn once the
     * aborted loop unwinds. Without it, the queue is cleared like a plain abort.
     *
     * No-op when the main loop is not processing (there is no turn to interrupt);
     * in that state the CLI uses {@link cancelAllBackgroundAgents} instead.
     *
     * @returns whether a main turn was interrupted.
     */
    interruptMainTurn(opts?: {
        flushQueued?: boolean;
    }): Promise<{
        interrupted: boolean;
    }>;
    /**
     * Cancel every running background agent (main task-registry subagents plus
     * sidekick agents) without touching the main agentic loop. Backs the CLI's
     * "stop background agents" escalation available once the coordinator is idle
     * but workers are still running ("Waiting for background agents").
     *
     * Promoted attached shells are deliberately not affected -- they are not
     * agents and are cancelled via `/tasks`, not this escalation.
     *
     * Cancelling drains any deferred `session.idle` via the task-registry change
     * pulse, so the UI leaves the waiting state once the last worker stops.
     *
     * @returns the number of main task-registry agents that were cancelled.
     */
    cancelAllBackgroundAgents(): number;
    /**
     * 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.
     *
     * Insertion order is tracked via {@link pendingItemOrder} so items are
     * removed strictly in LIFO order regardless of which queue they ended up
     * in (e.g. Enter goes to the immediate queue, Ctrl+Enter to itemQueue).
     *
     * 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.
     */
    removeMostRecentPendingItem(): boolean;
    /**
     * @deprecated Use clearPendingItems() instead.
     */
    clearPendingMessages(): void;
    /**
     * 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
     * @returns Promise that resolves with compaction results
     * @throws Error if compaction fails or prerequisites aren't met
     */
    compactHistory(customInstructions?: string): Promise<CompactionResult>;
    /**
     * After an active turn exits (a normal message turn or a resume-pending
     * continuation), pop the first non-passive message still buffered in the
     * immediate processor onto the main queue so it starts its own turn.
     *
     * A scheduled tick (or any steering message) delivered mid-turn lands in
     * the immediate processor. If the turn returns without a further preRequest
     * that drains it, that message would otherwise strand there with no active
     * turn to consume it, leaving its delivery promise unresolved until an
     * unrelated future turn. Passive `wait-for-next-turn` messages stay buffered
     * for the next user-driven turn; passive `drop` messages are discarded.
     */
    private salvageBufferedSteeringMessage;
    /**
     * Clears any steering messages folded into the turn that just ended
     * ({@link inFlightSteeringMessages}). Called once the owning
     * `runAgenticLoop()` call for the current queue item returns — including
     * any redirects handled internally by that same call — so a steering
     * message stays reported as pending only for the turn it was folded into,
     * not for every later, unrelated queued item drained afterward by
     * {@link processQueuedItems}.
     */
    private clearInFlightSteeringMessages;
    /**
     * Process queued items (messages and commands) through the agentic loop.
     * Used by send() and after manual compaction completes.
     * No-op if already processing or queue is empty.
     */
    private processQueuedItems;
    /**
     * 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 strategy is:
     *   1. Try a GC — may be enough on its own.
     *   2. If still under pressure and no compaction is already running,
     *      trigger an emergency compaction to free message history.
     */
    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;
    /**
     * Sends a notification to the agent when a background agent completes.
     *
     * Note: unlike the idle path, this does not thread a turn count. Terminal
     * (completed/failed) states are final, so `isRedundantAgentNotification`
     * treats a completion notification as redundant purely on whether a
     * terminal read state was recorded — it never compares turn counts.
     */
    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;
    /**
     * Sends a notification to the agent when a detached shell completes.
     */
    private isDetachedShellCompletionNotificationCurrent;
    private consumeDetachedShellCompletionNotification;
    private sendDetachedShellCompletionNotification;
    /**
     * Core MCP host initialization used by both ensureMcpLoaded() and initializeMcpHost().
     * Creates the McpHost, wires callbacks, and starts servers. Extracted so that
     * ensureMcpLoaded() (defined early in the class) can delegate here without
     * referencing private fields that tsgo cannot resolve across large class spans.
     */
    private _doInitializeMcp;
    /**
     * Initialize MCP host if configured
     */
    private initializeMcpHost;
    /**
     * 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;
    /**
     * Get connected IDE info if available.
     * Returns undefined if no IDE is connected.
     */
    private getConnectedIdeInfo;
    /**
     * 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;
    private getEffectiveLegacyProviderConfig;
    /**
     * Merge the session-level largeOutput config (from {@link SessionOptions.largeOutput})
     * into freshly-built legacy settings. Both the agent loop
     * ({@link buildSettingsAndTools}) and standalone LLM calls ({@link getClient}) call
     * this so that `enabled`/`outputDir`/`maxSizeBytes` reach the tool layer in either
     * path. A no-op when no session-level config was provided.
     */
    private applySessionLargeOutputConfig;
    /**
     * 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), AND the `copilot_cli_native_web_search` ExP
     * flag must be enabled. 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 so the async flag lookup is only reached
     * for capable Responses models.
     */
    private isNativeWebSearchActive;
    /**
     * Shared method to build settings and initialize tools.
     * Used by both initializeAndValidateTools() and runAgenticLoop().
     *
     * @param problemStatement - Optional problem statement for settings (used by runAgenticLoop)
     * @returns Settings and tools, or undefined if initialization failed
     */
    private buildSettingsAndTools;
    /**
     * Apply the three-arm dynamic retrieval experiment
     * (`copilot_cli_dynamic_instructions_retrieval_arm`) by setting the two
     * standalone feature flags for this build:
     *   "control"        → neither flag set (retrieval off)
     *   "text-embedding" → DYNAMIC_INSTRUCTIONS_RETRIEVAL set (text-embedding model)
     *   "blackbird"      → DYNAMIC_INSTRUCTIONS_RETRIEVAL + _BLACKBIRD both set
     *
     * The arm is the single rollout experiment: one assignment drives both the
     * on/off gate and the model selector, so traffic splits into clean thirds.
     * When an arm is assigned the experiment is authoritative and overrides any
     * tier/config/env value for these two flags. When ExP has no arm assignment
     * (local dev, not in the experiment, or the experiment stopped/unassigned
     * mid-session) the flags fall back to their captured base values.
     *
     * Both flags are written unconditionally on every build (rather than
     * early-returning when no arm is assigned) so the result is idempotent
     * across per-turn rebuilds: a prior arm's mutation can never stay stuck on
     * after the assignment goes away. Re-evaluated on every build (never cached)
     * so a mid-session ExP change — the experiment being stopped, unassigned, or
     * re-bucketed — takes effect immediately and fails safe to the base values.
     */
    private applyDynamicRetrievalArm;
    private resolveIsDynamicRetrievalEnabled;
    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
     * {@link applyDynamicRetrievalArm} 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)
     * - entries: Map from each enabled index type to its pre-loaded 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;
    /** Internal helper that performs the actual embedding index build. */
    private doEmbeddingIndexBuild;
    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;
    /**
     * 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;
    /** Emit model_resolution_info telemetry once per session. */
    private emitModelResolutionInfo;
    private retrieveModelLists;
    /**
     * 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;
    private getModelList;
    protected getAvailableModelsForAgentValidation(): Promise<Model[] | undefined>;
    /**
     * 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;
    /**
     * 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;
    private getAutoApprovalToolResultStatusByCallId;
    /**
     * 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" | "sidekick";
        taskRegistry: TaskRegistry;
        interactionId?: string;
        isByokExecutor?: boolean;
    } | {
        agentId: string;
        agentType: "sampling";
        isByokExecutor?: boolean;
    }): IAgentCallback;
}

/**
 * SessionManager subclass that persists sessions to JSONL files.
 * Uses SessionEventState for all file system operations.
 */
declare class LocalSessionManager implements SessionManager<LocalSessionMetadata, LocalSession>, Disposable_2 {
    private sessionWriters;
    private activeSessions;
    private inUseLocks;
    private copilotVersion;
    private flushDebounceMs;
    private settings?;
    /** Additional plugins from --plugin-dir, merged with config plugins for hook loading */
    additionalPlugins: InstalledPlugin[];
    private sessionStoreTracking;
    private _startupPrompts;
    private pendingRepoHooks;
    private _lastLoadedHookCount;
    private detachedSessionCache;
    private closingSessions;
    /**
     * Prompt messages from hook configs to auto-submit at session start.
     * Only populated for new sessions, not resumed ones — resuming continues
     * an existing conversation where startup prompts have already run.
     */
    get startupPrompts(): readonly string[];
    /**
     * Method form of {@link startupPrompts} used by the schema {@link SessionsApiManager}
     * interface. Returns the same readonly view; the schema getter wraps it in
     * `{prompts}` for the wire shape.
     */
    getStartupPrompts(): readonly string[];
    /**
     * Setter form of {@link additionalPlugins} used by the schema {@link SessionsApiManager}
     * interface. Replaces the manager-wide additional-plugin list with the
     * provided array. Subsequent createSession calls (and reloadPluginHooks
     * invocations) will see the new set; already-running sessions keep their
     * existing hook installation until the next reload.
     */
    setAdditionalPlugins(plugins: InstalledPlugin[]): void;
    /**
     * Returns a snapshot of the in-memory active sessions. Used by server-level
     * APIs (e.g. {@link pluginsApi}'s `onBeforePluginMutation` hook) to iterate
     * sessions for cross-cutting work like stopping plugin-owned MCP servers
     * before plugin files are removed. The returned array is a copy; callers
     * must not assume entries remain alive (sessions can be disposed concurrently).
     */
    getActiveSessions(): LocalSession[];
    /**
     * The hook count from the last successful loadDeferredRepoHooks call.
     * Reset to 0 at the start of each loadDeferredRepoHooks invocation.
     */
    get lastLoadedHookCount(): number;
    private readonly coreServices;
    private readonly telemetryService;
    private readonly handoffGitOperations?;
    private readonly sessionLifecycleMode?;
    private readonly authManager?;
    private readonly sessionsApi;
    /**
     * The OTel lifecycle is always retained (even when env vars don't enable
     * OTel) so enterprise managed settings fetched after construction can
     * enable and configure it via {@link applyManagedTelemetry}. The public
     * {@link otel} getter exposes it only while it's effectively enabled, so
     * existing `this.otel?.` call sites keep their disabled-means-undefined
     * semantics.
     */
    private readonly otelLifecycle;
    /**
     * Per-session OTel tracking options, retained for every active session so
     * that managed telemetry arriving *after* a session is created (the SDK
     * inits lazily, and the interactive session is created before the CLI
     * fetches managed settings) can retroactively attach a tracker with the
     * same options the session was created with. Cleared on session close.
     */
    private readonly otelTrackingOptions;
    /**
     * Last managed-settings layers resolved by the host (CLI) for the enterprise
     * MCP allow/deny policy, retained so a session created AFTER managed settings
     * resolved still receives the policy at creation. See {@link applyManagedMcpPolicy}.
     */
    private lastManagedMcpLayers?;
    /**
     * True once the host (CLI) has declared via {@link expectManagedMcpPolicy}
     * that it will resolve the enterprise-managed MCP policy out-of-band, but no
     * policy has been applied yet. While set, sessions created in the meantime
     * arm their MCP-load gate so a denied server cannot be exposed before the
     * policy lands. Cleared once {@link applyManagedMcpPolicy} runs.
     */
    private expectingManagedMcpPolicy;
    private readonly shellNotifier;
    private readonly extensionControllers;
    private readonly telemetrySenders;
    /**
     * State machine for the runtime-managed remote-control singleton.
     * Mutated only by `startRemoteControl*` / `transferRemoteControl*` /
     * `stopRemoteControl*` / `setRemoteControlSteering*`.
     * The CLI reads it via `getRemoteControlStatus` and the corresponding
     * `sessionsApi` schema methods.
     */
    private remoteControlState;
    /** Factory for creating per-session virtual filesystems. */
    sessionFsFactory: (sessionId: string, settings?: SettingsStorageContext) => SessionFs;
    constructor(coreServices: CoreServices, { version, flushDebounceMs, settings, shellNotifier, sessionLifecycleMode, handoffGitOperations, authManager, }?: LocalSessionManagerOptions);
    /** OTel lifecycle, exposed only while OTel is effectively enabled. */
    get otel(): OtelLifecycle | undefined;
    /**
     * Apply enterprise-mandated managed telemetry settings to the OTel
     * lifecycle. Managed settings are fetched after the interactive session is
     * already created, so when they newly enable OTel we retroactively attach
     * trackers to active sessions (using the options captured at creation).
     * Once the SDK has initialized the underlying lifecycle call is a no-op
     * (no live re-init); `trackSession` is idempotent so already-tracked
     * sessions are left untouched.
     */
    applyManagedTelemetry(managed: ManagedTelemetrySettings | null | undefined): void;
    /**
     * Apply the enterprise-managed MCP allow/deny policy layers resolved by the
     * host (the CLI, which fetches managed settings via its own app-level flow and
     * does not opt sessions into {@link SessionOptions.enableManagedSettings}) to
     * every active session, and retain them so sessions created later also receive
     * the policy at creation ({@link lastManagedMcpLayers}).
     *
     * The raw server + device layers are passed through so each session composes
     * the allowlist-intersection / deny-union itself and applies the same
     * fail-closed handling as the SDK self-fetch path.
     */
    applyManagedMcpPolicy(server: ManagedSettingsResponse | undefined, device: ManagedSettingsResponse | undefined, serverFetchFailed: boolean, deviceLoadFailed: boolean): void;
    /**
     * Declare that the enterprise-managed MCP allow/deny policy will be applied
     * later via {@link applyManagedMcpPolicy}, so MCP host creation defers until
     * it has. The CLI resolves managed settings asynchronously (app.tsx
     * onAuthChange), and a prompt can be submitted while that fetch is in flight;
     * arming the per-session MCP-load gate up front prevents a denied server from
     * starting and surfacing tools during that window. The caller MUST guarantee
     * {@link applyManagedMcpPolicy} is eventually invoked (in every branch,
     * fail-closed on failure), or the first MCP-backed turn would block. A no-op
     * once the policy has already been applied.
     */
    expectManagedMcpPolicy(): void;
    /**
     * Declare that enterprise-managed telemetry will be applied later (via
     * {@link applyManagedTelemetry}), so the OTel SDK defers initialising from
     * environment-derived config until managed settings resolve. The caller MUST
     * guarantee {@link applyManagedTelemetry} is eventually invoked, or OTel will
     * never initialise. See {@link OtelLifecycle.expectManagedTelemetry}.
     */
    expectManagedTelemetry(): void;
    /**
     * Build the OTel tracking options from session-creation options, retain
     * them for potential retroactive tracking ({@link applyManagedTelemetry}),
     * and offer the session to the lifecycle (a no-op while OTel is disabled).
     */
    private trackSessionTelemetry;
    getActiveSession(sessionId: string): LocalSession | undefined;
    registerExtensionToolsOnSession(params: {
        sessionId: string;
        loader?: unknown;
        options?: {
            enabled?: unknown;
        };
    }): {
        unsubscribe: () => void;
    };
    configureSessionExtensions(params: {
        sessionId: string;
        controller?: unknown;
    }): void;
    private getOrCreateExtensionController;
    private getOrCreateTelemetrySender;
    /**
     * Replace the session filesystem factory for all future sessions.
     * Must only be called when no sessions are active.
     */
    setSessionFsFactory(factory: (sessionId: string, settings?: SettingsStorageContext) => SessionFs): void;
    /** Create the OTel trace context resolver for a session so MCP calls propagate traceparent/tracestate. */
    private createMcpTraceContextResolver;
    /**
     * Wire the OTel parent-trace-context resolver onto a session so the
     * schema-driven `session.send` handler can update (or clear) the W3C
     * trace context for each agent turn. The resolver invokes
     * `otel.updateParentTraceContext` unconditionally so leftover trace
     * context from a previous send is
     * cleared rather than inherited.
     *
     * Passed to both {@link createSession} and {@link getSession} (the
     * resume path) — symmetrical to {@link createMcpTraceContextResolver}.
     */
    private createOtelParentContextResolver;
    private createTraceContextOptions;
    /**
     * Stop the foreground remote-control exporter (if any) when the
     * attached session is going away. Always clears any state pinned to
     * the session — `connecting` and `error` variants don't own an
     * exporter to stop, but their `attachedSessionId` would dangle. Safe
     * to call when nothing is attached.
     */
    private detachForegroundRemoteControlForSession;
    dispose(): Promise<void>;
    /**
     * Get effective settings, preferring options.configDir over this.settings
     */
    private getEffectiveSettings;
    private hasLegacyFlatSessionFile;
    /**
     * Let the session lazily resolve its Mission Control session ID (for the
     * `Copilot-Session` git trailer). Read each time the prompt is rebuilt, so
     * an asynchronously-created MC session ID is picked up on a later turn, and
     * so a resumed session that reattaches to its MC session still emits the
     * trailer. Must be installed on both the create and resume paths.
     *
     * Resolution order:
     *  1. The live remote-control exporter attached to this exact session, when
     *     remote control is active. This is the freshest source while a session
     *     is actively exporting. Exception: when that attached exporter is
     *     awaiting deferred MC-session creation, resolve to `undefined` (emit no
     *     trailer) rather than falling through to the persisted ID — deferred
     *     creation is only armed after reattach to the persisted session failed
     *     and it mints a new session, so the persisted ID is stale and would
     *     misattribute the commit until the new live ID is available.
     *  2. The MC session ID persisted to `workspace.yaml`. The live exporter
     *     starts asynchronously (fire-and-forget) and often isn't active yet
     *     when the first turn's prompt is built after create or resume — and a
     *     remote-control transfer between sessions can fail — so relying on the
     *     live exporter alone silently drops the trailer. Reading the persisted
     *     ID makes the trailer resilient: once a session has ever established an
     *     MC session, every subsequent turn and resume can still emit the
     *     trailer regardless of exporter startup timing or transfer state.
     */
    private installMissionControlSessionIdProvider;
    /**
     * Create a new file-backed session
     */
    createSession(options?: SessionOptions, emitStart?: boolean): Promise<LocalSession>;
    private getHooksDir;
    private createNativeHookSession;
    private getNativePluginHookInputs;
    /**
     * Wires the dynamic context board onto the session when COPILOT_SUBCONSCIOUS
     * is enabled. Resolves the board identity (falling back to a workspace-scoped
     * id when git is unavailable), attaches the store, and bumps the per-board
     * session counter. Errors are swallowed to debug logs so a missing/corrupt
     * board never blocks session creation or resume.
     */
    private initDynamicContextBoard;
    /** Wire session store live tracking. Skipped when enableSessionStore is explicitly false. */
    private wireSessionStoreTracking;
    /**
     * Flush any buffered session-store tracking data (e.g. partially-batched
     * turns) out to the persistent SQLite store without detaching tracking.
     * Called during shutdown and by {@link saveSessionById} so the persisted
     * store reflects the complete trajectory before observers (e.g., a
     * detached headless rem-agent child) read it.
     */
    private flushSessionStoreTracking;
    private unsubscribeSessionStoreTracking;
    private unsubscribeAllSessionStoreTracking;
    /**
     * Look up the dynamic-context board entry count for the given active
     * local session's repo+branch. Returns undefined when the sessionId is
     * not active locally, when no dynamic-context config is wired up, or
     * when the SQLite lookup throws — callers should treat undefined as
     * "metric unavailable" and never let it block their primary work
     * (e.g. spawning the rem-agent).
     *
     * The underlying query is a single indexed SELECT (~25 µs per
     * `hasDynamicContextBoardEntries` in `sidekickLaunchChecks.ts`).
     */
    getBoardEntryCount(sessionId: string): Promise<number | undefined>;
    startRemoteControl(params: {
        sessionId: string;
        config: RemoteControlConfig_2;
    }): Promise<RemoteControlStatus_2>;
    private setupForegroundExporter;
    transferRemoteControl(params: {
        toSessionId: string;
        expectedFromSessionId?: string;
    }): Promise<{
        status: RemoteControlStatus_2;
        transferred: boolean;
    }>;
    setRemoteControlSteering(params: {
        enabled: boolean;
    }): Promise<RemoteControlStatus_2>;
    stopRemoteControl(params?: {
        expectedSessionId?: string;
        force?: boolean;
    }): Promise<{
        status: RemoteControlStatus_2;
        stopped: boolean;
    }>;
    getRemoteControlStatus(): RemoteControlStatus_2;
    private remoteControlAttachedSessionId;
    private computeRemoteControlStatus;
    /**
     * Creates a {@link RemoteExportSession} adapter from a {@link LocalSession}.
     * Used internally for wiring remote export on runtime-spawned sessions.
     */
    private createRemoteExportSessionAdapter;
    /**
     * Loads deferred repo-level hooks after folder trust has been confirmed.
     * Must be called once after trust is granted. Idempotent — subsequent calls return
     * `{startupPrompts: [], hookCount: 0}`. Returns the same shape (with empty
     * `startupPrompts`) when no pending repo hooks exist for the session or when no
     * active session matches the given sessionId.
     *
     * @param sessionId - The active session ID to apply hooks to
     * @returns Repo-level startup prompts plus the total hook count loaded for the
     *   session by this call (captured atomically so callers don't race with
     *   concurrent invocations on other sessions).
     */
    loadDeferredRepoHooks(sessionId: string): Promise<{
        startupPrompts: string[];
        hookCount: number;
    }>;
    /**
     * Reload all hooks (user and plugin) and apply them to the active session.
     * Call after installing plugins so their hooks take effect immediately. No-op
     * when no active session matches the given sessionId.
     * @param sessionId - The active session ID to apply hooks to
     * @param deferRepoHooks - When true, skip repo hooks (use before folder trust is confirmed)
     */
    reloadPluginHooks(sessionId: string, deferRepoHooks?: boolean): Promise<void>;
    /**
     * Get existing session by ID
     * ALWAYS loads from disk to ensure freshness
     *
     * @throws Error if the session exists but cannot be parsed (e.g., unknown event types, corrupt data)
     * @returns The session, or undefined if the session does not exist
     */
    getSession(options: SessionOptions & {
        sessionId: string;
    }, resume?: boolean, behavior?: ResumeBehavior): Promise<LocalSession | undefined>;
    /**
     * Get the most recently updated session
     */
    getLastSession(options?: Omit<SessionOptions, "sessionId">, behavior?: ResumeBehavior): Promise<LocalSession | undefined>;
    /**
     * Get the ID of the most recently updated session
     */
    getLastSessionId(): Promise<string | undefined>;
    /**
     * Cheaply enumerate the most-recent non-empty (resumable) local session
     * IDs for the launch-time picker-vs-auto-resume decision.
     *
     * Walks sessions newest-first and prunes housekeeping-only ("empty")
     * sessions exactly like {@link listSessions}, but stops as soon as it has
     * collected `limit` of them (default 2 — all the caller needs to tell
     * "none" / "one" / "many" apart). In the common returning-user case the
     * two most-recent sessions carry a user message, so this reads ~2 JSONL
     * headers and **no** workspace.yaml files — cheaper than a
     * metadata-bearing `listSessions({ metadataLimit: 1 })` while keeping the
     * empty-session filtering that the decision depends on.
     *
     * Detached maintenance sessions are excluded, matching the
     * `includeDetached: false` listing the picker uses.
     */
    listNonEmptySessionIds(limit?: number): Promise<string[]>;
    /**
     * Get the ID of the most recently updated session, preferring sessions
     * that match the given working directory context (same repo+branch,
     * same repo, same git root, or same cwd — in descending priority).
     * Falls back to the most recent session if no context-matching sessions exist.
     */
    getLastSessionIdForContext(currentContext?: WorkingDirectoryContext_2): Promise<string | undefined>;
    /**
     * Updates the telemetry sender for a session based on the disable flag.
     * When disabled, clears the sender. When enabled, creates a new SessionTelemetry.
     * This consolidates telemetry setup so that create, disk-load resume, and
     * in-memory resume all go through the same code path.
     */
    updateSessionTelemetry(session: LocalSession, disable: boolean, options?: {
        remoteDefaultedOn?: boolean;
        remoteExporting?: boolean;
        configDir?: string;
        config?: UserSettings;
        detachedFromSpawningParentEngagementId?: string;
        initialWorkingDirectoryContext?: WorkingDirectoryContext_2;
    }): Promise<void>;
    /**
     * Resolve a session's persisted remote steering state.
     */
    getPersistedRemoteSteerable(sessionId: string, settings?: SettingsStorageContext): Promise<boolean | undefined>;
    /**
     * Find a local session by its Mission Control task ID.
     * Scans workspace.yaml files across all local sessions for a matching mc_task_id.
     * Returns the session ID if found, or undefined if no match.
     */
    findSessionByTaskId(taskId: string): Promise<string | undefined>;
    /**
     * Find a unique UUID session ID by abbreviated prefix.
     * Returns the full session ID if exactly one UUID session matches the prefix,
     * or undefined if no sessions match or the match is ambiguous.
     *
     * The prefix must be shorter than a full UUID (fewer than 36 characters),
     * start with at least 7 hexadecimal characters, and contain only
     * hexadecimal characters or hyphens thereafter. This allows partial UUID
     * copies like "a1b2c3d4-e5f6". Only canonical UUID session IDs participate
     * in prefix matching; non-UUID session IDs (which SDK clients can create
     * via the session API) are ignored. Note that user-facing names set via
     * /rename are display-only and do not affect session IDs or this lookup.
     *
     * 7 hex chars matches git's default prefix length. The first 8 hex chars
     * of a UUID v4 are pure random entropy, so 7 chars provides the same
     * collision resistance as git's 7-char commit prefixes.
     */
    findSessionByPrefix(prefix: string, settings?: SettingsStorageContext): Promise<string | undefined>;
    saveSession(session: Session): Promise<void>;
    /** Flush a session's pending events to disk by session ID. */
    saveSessionById(sessionId: string, options?: {
        force?: boolean;
    }): Promise<void>;
    /** Wire flush callback so shared APIs (e.g., history.truncate) can flush buffered events. */
    private wireFlushCallback;
    /**
     * Wire the plugin-hook reloader so `session.plugins.reload` can refresh user/plugin/repo
     * hooks for an active session without round-tripping through the manager-level
     * `sessions.reloadPluginHooks` RPC.
     */
    private wirePluginHookReloader;
    /**
     * Stop every plugin-owned MCP child process across all active local sessions.
     *
     * This is the shared cross-session cleanup primitive consumed by both the
     * server-level `server.plugins.*` API (wired via `CLIServer`) and the CLI's
     * interactive `/plugin …` slash commands (wired via `getCliPluginsApi`).
     * Both surfaces need the same behavior so that destructive plugin mutations
     * (uninstall, update, force-marketplace-remove) don't leave child processes
     * pointing at files we're about to delete or replace — important on Windows
     * where the OS holds executable handles open, and important everywhere to
     * avoid orphaned child processes.
     *
     * Errors are logged and swallowed so a single stuck server can never block
     * the mutation.
     */
    stopPluginMcpServersAcrossSessions(pluginName: string): Promise<void>;
    /**
     * Fork a session by copying its events to a new session directory.
     * Creates a new session with a fresh ID whose event history is a copy of the source session's
     * events, optionally truncated to a boundary event.
     *
     * @param sourceSessionId - The session ID to fork from
     * @param options - Optional fork settings, including an event boundary and friendly name
     * @returns The new session ID
     */
    forkSession(sourceSessionId: string, options?: ForkSessionOptions | string): Promise<ForkSessionResult>;
    private addSourceForkInfoEvent;
    private createForkInfoEvent;
    private getSourceForkInfoMessage;
    private getForkedSessionInfoMessage;
    private loadForkSourceWorkspace;
    private resolveForkSessionName;
    private getExistingSessionNameKeys;
    private getForkSourceNameBase;
    private getForkSourceEvents;
    private rewriteForkedSessionPaths;
    private getForkedCheckpointCount;
    private copyForkedSessionState;
    private copyForkedWorkspaceMetadata;
    private copySessionFsEntryIfExists;
    private copySessionFsEntry;
    private getSessionFsParentPath;
    private loadSession;
    /**
     * Resolve the on-disk JSONL event file path for a session. Useful for
     * tools that want to stream events without loading the full session.
     */
    getSessionEventFilePath(sessionId: string): string;
    /**
     * Get metadata for a single session by ID without loading the full session.
     * Returns undefined if the session does not exist.
     */
    getSessionMetadata({ sessionId }: {
        sessionId: string;
    }): Promise<LocalSessionMetadata | undefined>;
    /**
     * List all sessions by reading from disk.
     *
     * When `metadataLimit` is provided, only the first N sessions (sorted by
     * modification time) will have their workspace metadata loaded (context).
     * The remaining sessions are returned with basic info only (sessionId, times).
     * This avoids reading thousands of workspace.yaml files when only a screenful
     * of sessions will be displayed initially.
     */
    listSessions(options?: {
        metadataLimit?: number;
        includeDetached?: boolean;
    }): Promise<LocalSessionMetadata[]>;
    /**
     * List sessions sorted by relevance to the current working directory context.
     * Sessions matching the current repo+branch appear first, followed by same repo,
     * then same gitRoot or cwd, then all others sorted by time.
     *
     * @param currentContext The current working directory context to compare against
     */
    listSessionsSortedByRelevance(currentContext?: WorkingDirectoryContext_2): Promise<LocalSessionMetadata[]>;
    /**
     * List sessions with their relevance scores for grouping in the UI.
     * Sessions are sorted by score (descending), then by modifiedTime (descending).
     *
     * When `metadataLimit` is provided, only the first N sessions (by mtime)
     * will have full metadata loaded. This is the primary optimization for
     * the session picker: display recent sessions immediately, load older
     * session metadata lazily on scroll.
     *
     * @param currentContext The current working directory context to compare against
     * @param metadataLimit Max number of sessions to load full metadata for
     */
    listSessionsWithScores(currentContext?: WorkingDirectoryContext_2, metadataLimit?: number): Promise<ScoredSessionMetadata<LocalSessionMetadata>[]>;
    /**
     * Load full metadata (summary, context) for sessions that were loaded
     * without it (due to metadataLimit). Reads workspace.yaml for context
     * and falls back to JSONL for summary when workspace.yaml lacks one.
     *
     * Sessions confirmed to have no user prompt and no explicit name are
     * omitted from the result (returned as undefined, then filtered out).
     * Callers that batch enrichment should compare returned IDs against
     * the input batch to detect and remove pruned sessions from their lists.
     */
    enrichSessionMetadata(sessions: LocalSessionMetadata[]): Promise<LocalSessionMetadata[]>;
    private isDetachedSession;
    private getVisibleSessionEntriesWithBoundedDetachedDetection;
    private isDetachedSessionMarkerOnly;
    private hasDetachedSessionMarker;
    private writeDetachedSessionMarker;
    private readDetachedStatusFromSessionStart;
    /**
     * Delete a session from disk.
     */
    deleteSession(sessionId: string): Promise<void>;
    /**
     * Register an in-use lock for a session and check whether
     * another process already holds a lock on it.
     * @returns Whether the session was already in use by another process
     */
    registerSessionInUse(sessionId: string, settings?: SettingsStorageContext): Promise<boolean>;
    /**
     * Check which sessions from a list are currently in use by another process.
     * This is an advisory, opt-in check for UI display (e.g., session picker badges).
     * It does NOT register locks — only reads existing lock files.
     *
     * @param sessionIds - Session IDs to check
     * @returns Set of session IDs that have alive lock files held by other processes
     */
    checkSessionsInUse(sessionIds: string[]): Promise<Set<string>>;
    /**
     * Release the in-use lock for a session without performing a full
     * {@link closeSession} teardown. Use this when the CLI decides not to
     * continue with a session (e.g., user chose "Go back" from the
     * session-in-use confirmation) so the lock file doesn't linger.
     */
    releaseSessionLock(sessionId: string): Promise<void>;
    /**
     * Register an in-use lock for a session directory and check whether
     * another process already holds a lock on it.
     */
    private registerSessionLock;
    /**
     * Close a session: emit shutdown, flush/persist pending data, and release resources.
     * After this call the session is disposed and removed from active management.
     */
    closeSession(sessionId: string): Promise<void>;
    private waitForSessionClose;
    private closeSessionCore;
    /**
     * Get the sessions directory path (for debugging/logging)
     */
    getSessionsDirectory(): string;
    /**
     * Get the disk size of each session's workspace directory.
     *
     * @returns Map of sessionId to size in bytes
     */
    getSessionSizes(): Promise<Map<string, number>>;
    /**
     * Delete multiple sessions, cleaning up workspace directories and event files.
     *
     * @param sessionIds - Array of session IDs to delete
     * @returns Map of sessionId to bytes freed
     */
    bulkDeleteSessions(sessionIds: string[]): Promise<Map<string, number>>;
    /**
     * Find and optionally delete sessions older than a specified number of days.
     *
     * @param olderThanDays - Minimum age in days for a session to be eligible for pruning
     * @param options.dryRun - If true, only report what would be deleted (default: false)
     * @param options.includeNamed - If true, include sessions with a custom name (default: false)
     * @returns PruneResult with details about deleted/skipped sessions
     */
    pruneOldSessions(olderThanDays: number, options?: {
        dryRun?: boolean;
        includeNamed?: boolean;
        excludeSessionIds?: string[];
    }): Promise<PruneResult>;
    /**
     * Handoff a remote session to local by validating repository, checking git state,
     * and creating a local session with the remote session's events.
     * This is an async generator that yields progress updates.
     *
     * @param remoteSession - The remote session to handoff
     * @param sessionOptions - Optional session options to pass to createSession
     * @yields HandoffProgress updates for each step
     * @returns A new local session with the same events
     * @throws Error if validation fails or git operations fail
     */
    handoffSession(remoteSession: Session, sessionOptions?: SessionOptions, taskType?: "cca" | "cli"): AsyncGenerator<HandoffProgress | HandoffConfirmationRequest, LocalSession, HandoffConfirmationResponse | undefined>;
    /**
     * Helper method to fetch from git remote
     */
    private gitFetch;
}

declare type LocalSessionManagerOptions = {
    version?: string;
    flushDebounceMs?: number;
    settings?: RuntimeSettingsInput & SettingsStorageContext;
    /**
     * Shell notification sender. If a {@link DelegatingShellNotificationSender}
     * is provided, it is used directly (the caller retains ownership and can
     * reconfigure its delegate at any time). Otherwise a new delegating wrapper
     * is created internally.
     */
    shellNotifier?: DelegatingShellNotificationSender;
    sessionLifecycleMode?: SessionOptions["sessionLifecycleMode"];
    /** Git operations for remote→local session handoff */
    handoffGitOperations?: HandoffGitOperations;
    /**
     * Auth manager used by the runtime-managed remote-control singleton to
     * resolve Mission Control credentials. Required for `startRemoteControl`
     * / `transferRemoteControl`; without it those methods throw. Optional
     * for managers that never participate in remote control (e.g. unit
     * tests, prompt-mode runs).
     */
    authManager?: AuthManager;
};

export declare interface LocalSessionMetadata extends SessionMetadata {
    readonly isRemote: false;
    /** GitHub task ID persisted for sessions exported to remote control. */
    readonly mcTaskId?: string;
    /** True for detached maintenance sessions, such as background REM-agent consolidation runs. */
    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;
}

declare const localShellToolName = "local_shell";

/**
 * 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 */
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 enum LogLevel {
    None = 0,
    Error = 1,
    Warning = 2,
    Info = 3,
    Debug = 4,
    All = 4,// Logs everything
    Default = 3
}

declare type LogLevel_2 = 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. */
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_2, message: string): Promise<void>;
    /** @returns the current file path or other identifier if not writing to a file. */
    outputPath(): string;
}

/** 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;
}

/**
 * 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;
};

/**
 * 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[];
}

/**
 * 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;

export declare type ManagedSettingsEnforcedAction = WireTypes.ManagedSettingsEnforcedAction;

/** The category of runtime action that enterprise managed settings governed (blocked or capped) */
declare type ManagedSettingsEnforcedAction_2 = "bypass_permissions_blocked";

export declare type ManagedSettingsEnforcedData = WireTypes.ManagedSettingsEnforcedData;

/** 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. */
declare interface ManagedSettingsEnforcedData_2 {
    /** The category of runtime action that managed policy governed. */
    action: ManagedSettingsEnforcedAction_2;
    /** For a `bypass_permissions_blocked` action, which permission-escalation primitive was refused. Absent for actions without a specific escalation primitive. */
    escalation?: ManagedSettingsEnforcedEscalation_2;
    /** 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;
}

export declare type ManagedSettingsEnforcedEscalation = WireTypes.ManagedSettingsEnforcedEscalation;

/** For a `bypass_permissions_blocked` action, which permission-escalation primitive was refused */
declare type ManagedSettingsEnforcedEscalation_2 = "allow_all" | "approve_all" | "auto_approval" | "unrestricted_paths" | "unrestricted_urls";

export declare type ManagedSettingsEnforcedEvent = WireTypes.ManagedSettingsEnforcedEvent;

/** 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. */
declare interface ManagedSettingsEnforcedEvent_2 {
    /** 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_2;
    /** 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";
}

export declare type ManagedSettingsResolvedData = WireTypes.ManagedSettingsResolvedData;

/** Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. 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; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. */
declare interface ManagedSettingsResolvedData_2 {
    /** 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 the 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 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;
    /** Which channel supplied the effective managed settings (the winning layer), or `none` when no policy is in force */
    source: ManagedSettingsResolvedSource_2;
}

export declare type ManagedSettingsResolvedEvent = WireTypes.ManagedSettingsResolvedEvent;

/** Session event "session.managed_settings_resolved". Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. 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; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. */
declare interface ManagedSettingsResolvedEvent_2 {
    /** 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 where they came from, so SDK clients can show users what is enterprise-managed and by which authority. 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; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. */
    data: ManagedSettingsResolvedData_2;
    /** 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";
}

export declare type ManagedSettingsResolvedSource = WireTypes.ManagedSettingsResolvedSource;

/** Which channel supplied the effective enterprise managed settings (highest-authority present layer wins wholesale) */
declare type ManagedSettingsResolvedSource_2 = "server" | "device" | "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" | "strictKnownMarketplaces" | "telemetry" | "allowedMcpServers" | "deniedMcpServers">;

/**
 * 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;
}

/** Marks MCP/external tools deferred once the tool count exceeds `threshold`; mutates `tools` in place. */
declare function markToolsAsDeferred(tools: Tool[], externalToolNames: ReadonlySet<string>, threshold?: number): void;

/** 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) */
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 */
declare interface McpAppToolCallCompleteError {
    /** Human-readable error message */
    message: string;
}

export declare type McpAppToolCallCompleteEvent = WireTypes.McpAppToolCallCompleteEvent;

/** Session event "mcp_app.tool_call_complete". MCP App view called a tool on a connected MCP server (SEP-1865) */
declare interface McpAppToolCallCompleteEvent_2 {
    /** 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. */
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. */
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, optional redacted reason, and enterprise login. */
declare interface McpFilteredServer {
    /** Enterprise login associated with an allowlist policy */
    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;
    /**
     * When the server was blocked by an enterprise allowlist, the login of the
     * enterprise that owns the policy (e.g. `mcp-itsa`). Surfaces in the
     * user-facing warning so admins can be identified.
     */
    enterpriseName?: 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 */
declare interface McpHeadersRefreshCompletedData {
    /** How the pending MCP headers refresh request resolved. */
    outcome: McpHeadersRefreshCompletedOutcome;
    /** Request ID of the resolved headers refresh request */
    requestId: string;
}

export declare type McpHeadersRefreshCompletedEvent = WireTypes.McpHeadersRefreshCompletedEvent;

/** Session event "mcp.headers_refresh_completed". MCP headers refresh request completion notification */
declare interface McpHeadersRefreshCompletedEvent_2 {
    /** 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. */
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 */
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;
}

export declare type McpHeadersRefreshRequiredEvent = WireTypes.McpHeadersRefreshRequiredEvent;

/** Session event "mcp.headers_refresh_required". Dynamic headers refresh request for a remote MCP server */
declare interface McpHeadersRefreshRequiredEvent_2 {
    /** 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. */
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: RunnerLogger;
    protected onOAuthRequired?: McpHostOptions["onOAuthRequired"];
    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?;
    /** In-flight `handleToolsChanged` promises; awaited by `awaitPendingToolsChanges` (#7432). */
    private pendingToolsChanges;
    /**
     * Last-emitted tool-list fingerprint per server. A `tools/list_changed`
     * notification only re-emits the host-level `tools` list-changed event when
     * the fingerprint materially changes, and the entry is cleared whenever the
     * server leaves the connected state so a reconnect re-baselines.
     */
    private readonly serverToolFingerprints;
    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 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;
    private throwIfIntentionallyStopped;
    private emitListChanged;
    private beginServerConfigurationOperation;
    private currentServerStopVersion;
    private stopServerOperations;
    private isCurrentServerOperation;
    private withServerConfigurationLock;
    /** 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;
    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;
    /**
     * Called when a server sends a tools/list_changed notification
     */
    private handleToolsChanged;
    /**
     * Performs a live tool listing for a server and emits the host-level `tools`
     * list-changed event only when the tool set materially changed since the last
     * emit. Mirrors the pre-port snapshot gate so consumers (e.g. the session's
     * `mcp.tools.list_changed` event) are not notified on every notification.
     */
    private listServerToolsAndEmitIfChanged;
    /** 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;
    /**
     * 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;
    /**
     * 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: RunnerLogger, 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>;
    /**
     * Lists tools for a given server by delegating to the client's listTools.
     */
    listTools(serverName: string, options?: {
        timeoutMs?: number;
    }): Promise<LenientToolInfo[]>;
    /**
     * 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[]>;
    /**
     * Start a single MCP server with the given configuration
     * @param serverName - Unique name for the server
     * @param config - Server configuration
     * @param forceReauth - Optional flag to force re-authentication
     * @param customAgent - Optional custom agent information for OIDC token cache key derivation
     * @returns Promise that resolves when server is started
     */
    startServer(serverName: string, config: MCPServerConfig, forceReauth?: boolean, customAgent?: CustomAgentInfo, trustedFirstPartyStart?: boolean): Promise<void>;
    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>;
    /**
     * 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>;
    /**
     * 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): 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>;
    /**
     * Atomically update the sandbox policy and restart every currently-running
     * local (stdio) MCP server so they pick up the new policy.
     *
     * The sandbox is baked into the spawn at process creation time, so a policy
     * change is only observable after the server is restarted. Remote (HTTP/SSE)
     * servers are intentionally skipped — the sandbox would only apply to the
     * proxy/transport process, not the remote endpoint.
     *
     * 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): 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;
    /**
     * 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: RunnerLogger);
    /**
     * 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_2): 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;
}

declare interface McpHostOptions {
    logger: RunnerLogger;
    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) => Promise<OAuthClientProvider | undefined>;
    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[];
}

declare type McpHostSettingsContext = ClientNameContext & {
    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 enterprise allowlist 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_2;

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. */
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[];
}

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[];
}

/** MCP OAuth request completion notification */
declare interface McpOauthCompletedData {
    /** How the pending OAuth request was completed */
    outcome: McpOauthCompletionOutcome;
    /** Request ID of the resolved OAuth request */
    requestId: string;
}

export declare type McpOAuthCompletedEvent = WireTypes.McpOAuthCompletedEvent;

/** 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";
}

/** How the pending MCP OAuth request was completed */
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. */
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;
}

export declare type McpOAuthRequestedEvent = WireTypes.McpOAuthRequestedEvent;

declare type McpOAuthRequestReason = "initial" | "refresh" | "reauth" | "upscope";

/** Reason the runtime is requesting host-provided MCP OAuth credentials */
declare type McpOauthRequestReason = "initial" | "refresh" | "reauth" | "upscope";

/** OAuth authentication request for an MCP server */
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";
}

/** Static OAuth client configuration, if the server specifies one */
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;
}

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 */
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;
};

export declare type McpPromptsListChangedEvent = WireTypes.McpPromptsListChangedEvent;

/** Session event "mcp.prompts.list_changed". Payload identifying the MCP server associated with a list change. */
declare interface McpPromptsListChangedEvent_2 {
    /** 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_2<"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_2 | 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>>;
    constructor(logger: RunnerLogger, envValueMode?: EnvValueMode, settings?: ClientNameContext_2 | 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) => void | Promise<void>): void;
    setListChangedCallback(callback: (serverName: string, kind: McpListChangedKind) => void): void;
    notifyToolsChanged(serverName: string): void;
    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>): void;
    clearPendingConnectionIfCurrent(serverName: string, promise: Promise<void>): 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;
}

export declare type McpResourcesListChangedEvent = WireTypes.McpResourcesListChangedEvent;

/** Session event "mcp.resources.list_changed". Payload identifying the MCP server associated with a list change. */
declare interface McpResourcesListChangedEvent_2 {
    /** 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 (via keytar) 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>;
}

/** MCP server status entry, including config source/plugin source and any connection error. */
declare interface McpServer {
    /** 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, or not_configured */
    status: McpServerStatus_2;
}

declare interface McpServer_2 {
    connect(transport: Transport): Promise<unknown>;
    close?(): Promise<unknown>;
    registerTool?: unknown;
}

/**
 * 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_2> | ContentFilterMode_2;
    /**
     * Optional. Timeout in milliseconds for tool calls to this server.
     * If not specified, a default is used.
     */
    timeout?: number;
    /**
     * 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. 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 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;
    /** 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;
    /** 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[];
}

/** 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>;

/**
 * Abstraction for adding MCP servers and getting their tools.
 * This allows different implementations (OutOfProcMCPTransport, McpHost) to be used
 * interchangeably when setting up custom agents.
 */
declare interface McpServerProvider {
    /**
     * Add an MCP server and return the tools it provides.
     * @param serverName - Unique name for the server
     * @param serverConfig - Configuration for the server
     * @param logger - Logger for diagnostic messages
     * @param customAgent - Optional custom agent that owns this server
     * @returns an `McpToolsAndShutdown`
     */
    addServerAndGetTools(serverName: string, serverConfig: MCPServerConfig, logger: RunnerLogger, customAgent?: CustomAgentInfo): Promise<McpToolsAndShutdown>;
}

declare interface MCPServersConfig {
    mcpServers: Record<string, MCPServerConfig>;
}

/**
 * Telemetry event emitted when an MCP server setup completes.
 */
declare type McpServerSetupTelemetryEvent = TelemetryEvent_2<"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. */
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";
}

/** A single MCP server status summary in `session.mcp_servers_loaded`, including name, status, source, transport, and plugin metadata. */
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, 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 */
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, or not_configured */
declare type McpServerStatus = "connected" | "failed" | "needs-auth" | "pending" | "disabled" | "not_configured";

/** Connection status: connected, failed, needs-auth, pending, disabled, or not_configured */
declare type McpServerStatus_2 = "connected" | "failed" | "needs-auth" | "pending" | "disabled" | "not_configured";

/** Payload of `session.mcp_server_status_changed` for one MCP server's status and optional failure error. */
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, 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";
}

/** Transport mechanism: stdio, http, sse (deprecated), or memory (in-process MCP server) */
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 configuration for an individual MCP server start. */
declare interface McpStartServerRequest {
    /** MCP server configuration (stdio process or remote HTTP/SSE) */
    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;
}

/**
 * A set of MCP tools along with a shutdown function to clean up the servers
 * associated with those tools. Whether or not multiple servers are involved is
 * dependent on the context in which this type was used/returned/created.
 */
declare type McpToolsAndShutdown = {
    tools: tools.Tool[];
    shutdownMcpServers: () => Promise<void>;
    /** The normalized server names that were added (used to filter out overridden servers from outer agent) */
    serverNames?: string[];
};

export declare type McpToolsListChangedEvent = WireTypes.McpToolsListChangedEvent;

/** Session event "mcp.tools.list_changed". Payload identifying the MCP server associated with a list change. */
declare interface McpToolsListChangedEvent_2 {
    /** 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";
}

/** 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: RunnerLogger;
    protected readonly coreHandle: number;
    protected callbacks: McpTransportCallbacks;
    protected constructor(settings: RuntimeSettings, logger: RunnerLogger, cacheProviderTools?: boolean);
    setMcpAppsEnabled(enabled: boolean): void;
    setFidesIfcEnabled(enabled: boolean | undefined): void;
    setCallbacks(callbacks: McpTransportCallbacks): void;
    dispose(): void;
    invalidateClient(_clientName: string): void;
    loadTools(provider: ToolsProviderT): Promise<Tool[]>;
    refreshProvider(provider: ToolsProviderT): Promise<void>;
    protected abstract loadDescriptors(provider: ToolsProviderT): Promise<RustMcpToolDescriptor[]>;
    abstract invokeTool(toolId: string, toolParams: Record<string, unknown>, filterMode?: ContentFilterMode_2, toolCallId?: string, customAgentName?: string): Promise<ToolResultExpanded>;
    protected syncSecretFilter(): void;
    private attachLiveInvokeCallbacks;
    protected invokeDescriptorTool(toolId: string, toolParams: Record<string, unknown>, filterMode: ContentFilterMode_2, 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;
};

/** Display modes a view can be rendered in (SEP-1865). */
declare type McpUiDisplayMode = "inline" | "fullscreen" | "pip";

/**
 * 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. */
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. */
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";
}

declare interface MemoryConfiguration {
    /** Whether memory tools and prompt context are enabled for the session. */
    enabled: boolean;
}

/** Memory configuration for this session. */
declare interface MemoryConfiguration_2 {
    /** 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;
};

/**
 * Merge session-level provider headers with per-turn request headers.
 * Per-turn headers augment and overwrite session-level headers with the same key
 * (case-insensitive, since HTTP header names are case-insensitive per RFC 9110).
 * When a request header overwrites a provider header, the request header's
 * original casing is used in the result.
 * Returns `undefined` when neither source provides headers so callers can
 * avoid sending an empty object.
 */
export declare function mergeRequestHeaders(providerHeaders: Record<string, string> | undefined, requestHeaders: Record<string, string> | undefined): Record<string, string> | undefined;

/**
 * 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_3 | UserMessageEvent_3 | ToolMessageEvent;

declare type MessageExtraInfo = unknown;

/**
 * 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";

declare function missingRemoteBranchWarning(branch: string): string;

/** Agent mode change details including previous and new modes */
declare interface ModeChangedData {
    /** The session mode the agent is operating in */
    newMode: SessionMode_3;
    /** The session mode the agent is operating in */
    previousMode: SessionMode_3;
}

/** 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";
}

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_2;
            /**
             * 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 (flat format, API < 2026-06-01). */
        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;
    /** Default reasoning effort level (only present if model supports reasoning effort) */
    defaultReasoningEffort?: string;
    /** 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 time-boxed discount. */
    promo?: ModelBillingPromo;
    /** Token-level pricing information for this model */
    tokenPrices?: ModelBillingTokenPrices;
}

/** Active server-driven promotion for a model, including its discount and 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. Always present: the API only surfaces a promo whose expiry parses and is in the future. 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. */
    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;
}

export declare interface ModelCacheActivity {
    model: string;
    initiator?: string | null;
    cacheReadTokens: number;
    cacheWriteTokens: number;
    cacheTtlSeconds?: number;
    completedAtMs: number;
    durationMs: number;
}

export declare interface ModelCacheState {
    modelId: string;
    cacheExpiresAt: string;
    cacheTtlSeconds: 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. */
declare type ModelCallFailureBadRequestKind = "bodyless" | "structured_error";

/** Failed LLM API call metadata for telemetry */
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;
    /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */
    serviceRequestId?: string;
    /** Where the failed model call originated */
    source: ModelCallFailureSource_2;
    /** 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";
}

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>;
};

declare type ModelCallFailureEvent_3 = Extract<Event_2, {
    kind: "model_call_failure";
}>;

/** Boundary that produced a model call failure */
declare type ModelCallFailureKind = "api" | "transport";

/** Content-free structural summary of the failing request for diagnosing malformed 4xx calls */
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;
}

export declare type ModelCallFailureSessionEvent = WireTypes.ModelCallFailureSessionEvent;

export declare type ModelCallFailureSource = WireTypes.ModelCallFailureSource;

/** Where the failed model call originated */
declare type ModelCallFailureSource_2 = "top_level" | "subagent" | "mcp_sampling";

/** Transport used for a failed model call */
declare type ModelCallFailureTransport = "http" | "websocket";

/**
 * -----------------------------------------------------------------------
 * Events
 * -----------------------------------------------------------------------
 *
 * Event (Union Type)
 * ├── TurnStartedEvent
 * ├── TurnEndedEvent
 * ├── TurnFailedEvent
 * ├── TurnRetryEvent
 * ├── ModelCallSuccessEvent
 * ├── ModelCallFailureEvent
 * ├── ToolExecutionEvent
 * ├── ImageProcessingEvent
 * ├── BinaryAttachmentRemovalEvent
 * ├── TruncationEvent
 * ├── MessageEvent
 * │   ├── AssistantMessageEvent
 * │   ├── UserMessageEvent
 * │   └── ToolMessageEvent
 * ├── ResponseEvent
 * ├── MessagesSnapshotEvent
 * └── SessionLogEvent
 */
/**
 * All types of events that can be emitted by the `Client`.
 */
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;
    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 */
declare interface ModelCallStartData {
    /** Model identifier used for this API call, when known */
    model?: 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;
};

/** Session event "model.call_start". Model API dispatch metadata for internal telemetry */
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;
    /** 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;
};

/** 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[];
}

/** Optional capability overrides (vision, tool_calls, reasoning, etc.). */
declare interface ModelCapabilitiesOverride {
    /** Token limits for prompts, outputs, and context window */
    limits?: ModelCapabilitiesOverrideLimits;
    /** Feature flags indicating what the model supports */
    supports?: ModelCapabilitiesOverrideSupports;
}

/**
 * Deep-partial override for model capabilities, derived from {@link Model}.
 * Only non-undefined values are applied over the runtime-resolved capabilities.
 */
declare type ModelCapabilitiesOverride_2 = DeepOptional<Model["capabilities"]>;

/** 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;
    /** 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;
    /** 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 */
declare interface ModelChangeData {
    /** Reason the change happened, when not user-initiated. Currently `"rate_limit_auto_switch"` for changes triggered by the auto-mode-switch rate-limit recovery path. 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";
}

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;
};

/**
 * Per-model metrics tracked during a session
 */
export declare interface ModelMetrics {
    requests: {
        count: number;
        cost: number;
    };
    usage: {
        inputTokens: number;
        outputTokens: number;
        cacheReadTokens: number;
        cacheWriteTokens: number;
        reasoningTokens: number;
    };
    /** Accumulated nano-AI units cost for this model. */
    totalNanoAiu: number;
    /** Token count details per type (e.g. input, output, cache_read, cache_write). */
    tokenDetails: Map<string, TokenDetails>;
    /** Latest known prompt-cache expiration for this model. */
    cacheExpiresAt?: string;
    /** Retained cache lifetime used to refresh expiration after a cache read. */
    cacheTtlSeconds?: number;
}

/** 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;
};

/** 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;
    /** Override individual model capabilities resolved by the runtime */
    modelCapabilities?: ModelCapabilitiesOverride;
    /** 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. "none" disables reasoning. */
    reasoningEffort?: string;
    /** Reasoning summary mode to request for supported model clients */
    reasoningSummary?: ReasoningSummary_2;
    /** Output verbosity level to request for supported models */
    verbosity?: Verbosity_2;
}

/** The model identifier active on the session after the switch. */
declare interface ModelSwitchToResult {
    /** 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). */
declare interface NamedProviderConfig {
    /** API key. Optional for local providers like Ollama. */
    apiKey?: string;
    /** Azure-specific provider options. */
    azure?: ProviderConfigAzure;
    /** 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;
}

/**
 * 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_2 {
    /** 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_2;
    /** 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;
}

/** 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_2>;
};

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.
     *
     * 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;
    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;
    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;
    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(): boolean;
    private get progress();
    private toOutput;
    private handleLifecycle;
}

declare type NativeHookProcessorOptions = {
    cwd: string;
    logger: RunnerLogger;
    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: number;
    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`): the created
 * task reference the caller polls. Left open for verbatim fields.
 */
declare interface NativeMcpCreateTaskResult {
    task: NativeMcpTask;
    _meta?: unknown;
    [key: string]: 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;
}

/**
 * Result of `tasks/list` (`ListTasksResult`): the server's known tasks plus an
 * optional pagination cursor. Left open for verbatim fields.
 */
declare interface NativeMcpListTasksResult {
    tasks: NativeMcpTask[];
    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 buildSandboxedShellScript}; 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-1686).
     * `args` / `meta` behave as in {@link callTool}; `task` is the
     * task-augmentation object (e.g. `{ ttl }`) whose presence marks the call
     * task-augmented (defaults to `{}`). 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>, task?: 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 (`tasks/result`) — the original
     * call's result.
     */
    getTaskResult(taskId: string): Promise<NativeMcpCallToolResult>;
    /** Requests cancellation of a task (`tasks/cancel`), returning the updated task. */
    cancelTask(taskId: string): Promise<NativeMcpTask>;
    /**
     * Lists the server's known tasks (`tasks/list`), following the optional
     * pagination `cursor`.
     */
    listTasks(cursor?: string): Promise<NativeMcpListTasksResult>;
    /** 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;
}

/**
 * An MCP task (MCP Tasks / SEP-1686), mirroring the wire shape: the `taskId`,
 * lifecycle `status`, timestamps, and optional `ttl` / `pollInterval` /
 * `statusMessage`. Left open so callers can read fields the engine forwards
 * verbatim.
 */
declare interface NativeMcpTask {
    taskId: string;
    status: string;
    createdAt?: string;
    lastUpdatedAt?: string;
    ttl?: number | null;
    pollInterval?: number;
    statusMessage?: string;
    [key: string]: unknown;
}

/**
 * Discriminated outcome of a task-augmented `tools/call`. The server MAY enqueue
 * 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: number;
    disableSizeTruncation?: boolean;
} | {
    kind: "compaction";
    handle: number;
};

declare type NativePreRequestProcessorConfig = {
    kind: "truncator";
    handle: number;
    latestUserPromptIndex?: number;
    latestUserPromptMarker?: string;
    latestUserPromptMessage?: ChatCompletionMessageParam;
    latestUserPromptMessageJson?: string;
    disableSizeTruncation?: boolean;
} | {
    kind: "response_limits";
    handle: number;
    /** The response limits, when configured. */
    limits?: {
        maxAiCredits?: number;
    };
} | {
    kind: "compaction";
    handle: number;
    /**
     * 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;
};

declare type NativeRuntime = typeof RuntimeNative_3;

/**
 * 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`,
 * `contentExclusionShouldEnable`) 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;

export declare class NoopLogger extends BaseLogger implements RunnerLogger {
    constructor();
    debug(_message: string): void;
    log(_message: string): void;
    info(_message: string): void;
    notice(_message: string | Error): void;
    warning(_message: string | Error): void;
    error(_message: string | Error): void;
    startGroup(_name: string, _level?: LogLevel): void;
    endGroup(_level?: LogLevel): void;
}

/** No-op implementation of telemetry service */
declare class NoopTelemetryService extends TelemetryService {
    sendTelemetryEvent(_eventName: string, _properties?: TelemetryProperties, _measurements?: TelemetryMeasurements, _tags?: TelemetryTags): void;
    sendHydroEvent(_event: HydroEvent, _options?: HydroTelemetryOptions): void;
    shouldSendRestrictedTelemetry(): boolean;
    dispose(): void;
}

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 */
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";

export declare type OmittedBinaryResult = WireTypes.OmittedBinaryResult;

/** A binary result whose data was omitted from persistence due to the inline size limit */
declare interface OmittedBinaryResult_2 {
    /** 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. */
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;
};

/** Callback shape for tool-list updates. Re-exported from `otelLifecycle.ts`. */
declare type OnToolsUpdateFn = (callback: (tools: ToolMetadata[], model: string) => void) => () => void;

/** 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;
}

declare type Options = {
    settings?: SettingsStorageContext;
    sessionStoreEnabled?: boolean;
    sessionFs?: SessionFs;
    noPlanning?: boolean;
};

declare type Options_2 = ToolCallbackOptions<StrReplaceEditorOptions>;

/** 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";

/**
 * Classification of an orphaned tool call's permission/external tool state for resume.
 *
 * - interrupted: no permission/tool request boundary persisted for this tool call;
 *   it is reported as interrupted.
 * - awaiting-permission: permission requested but not yet decided; wait for a
 *   late decision or accept a user-message preempt.
 * - approved / denied: permission decision was persisted before suspend. For
 *   external tools, "approved" continues by re-issuing the tool request (the
 *   work hadn't started). For local tools, "approved" cannot be safely resumed
 *   (the in-process stack is gone) and is reported as interrupted.
 * - awaiting-external-tool: external tool was dispatched but not completed;
 *   wait for the consumer to re-supply the result via respondToExternalTool.
 * - external-tool-completed: a late completion arrived in-memory after resume
 *   but before classification; replay it.
 */
declare type OrphanedToolPermissionState = "interrupted" | "awaiting-permission" | "approved" | "denied" | "awaiting-external-tool" | "external-tool-completed";

/** Info about an orphaned tool call that needs resolution on resume. */
declare interface OrphanedToolResumeInfo {
    toolCallId: string;
    toolName: string;
    args: unknown;
    state: OrphanedToolPermissionState;
    permissionRequestId?: string;
    permissionResult?: PermissionRequestResult_2;
    /** The original permission request data. */
    permissionRequest?: PermissionRequest_2;
    externalToolRequestId?: string;
    externalToolCompletion?: ExternalToolCompletion;
    /** For external tools awaiting response: the original request data. */
    externalToolRequest?: {
        sessionId: string;
        toolName: string;
        arguments: unknown;
    };
}

/**
 * Owns the full OTel lifecycle: config resolution, lazy SDK initialisation
 * via the native runtime, per-session tracker creation / disposal, and
 * trace-context helpers used by the JSON-RPC server layer.
 *
 * The trace/metric SDK and per-session state machine are implemented in
 * `src/runtime/src/otel/*`. This class is the thin TS adapter that
 * the rest of the codebase imports.
 */
declare class OtelLifecycle {
    private config;
    private sdkHandle;
    private trackers;
    /**
     * When true, lazy SDK initialisation from the environment-derived config is
     * deferred until enterprise-managed telemetry has been applied at least once
     * (see {@link expectManagedTelemetry} / {@link applyManagedTelemetry}). This
     * prevents a user's environment variables (e.g. `OTEL_EXPORTER_OTLP_ENDPOINT`)
     * from initialising the SDK before managed settings resolve, which would let
     * env config silently pre-empt the enterprise-mandated policy. Off by default
     * so non-CLI consumers that never apply managed telemetry keep initialising
     * from env immediately; the CLI opts in via {@link expectManagedTelemetry}.
     */
    private awaitingManagedTelemetry;
    constructor();
    /** Whether OTel is enabled (config resolved to a non-null value). */
    get enabled(): boolean;
    /**
     * Declare that enterprise-managed telemetry will be applied via
     * {@link applyManagedTelemetry}, so the SDK must not initialise from the
     * environment-derived config until it has (managed settings win over env;
     * see {@link awaitingManagedTelemetry}). The caller MUST guarantee that
     * {@link applyManagedTelemetry} is eventually invoked (with the resolved
     * managed settings, or `undefined`/`null` when there are none), or OTel will
     * never initialise. Idempotent; a no-op once the SDK has initialised.
     */
    expectManagedTelemetry(): void;
    /**
     * Apply enterprise-mandated managed telemetry settings, re-resolving the
     * effective config (environment ⊕ managed, managed wins). Must be called
     * before the SDK initializes lazily on the first {@link trackSession}; once
     * the SDK handle exists this is a no-op (no live re-init of a running SDK).
     */
    applyManagedTelemetry(managed: ManagedTelemetrySettings | undefined): void;
    /** Whether a session already has a live tracker attached. */
    isTracking(sessionId: string): boolean;
    /** Lazily initialise the SDK and start tracking a session's event stream. */
    trackSession(session: OtelSession, options?: OtelTrackingOptions): Promise<void>;
    /** Stop tracking a single session (e.g. on close). */
    stopTracking(sessionId: string): void;
    /** Returns W3C trace context headers for an in-flight tool call, or `{}`. */
    getToolCallTraceContext(sessionId: string, toolCallId: string): {
        traceparent?: string;
        tracestate?: string;
    };
    /** Forward an updated parent trace context from an SDK caller. */
    updateParentTraceContext(sessionId: string, traceparent?: string, tracestate?: string): void;
    /** Dispose all trackers and shut down the OTel SDK. */
    dispose(): Promise<void>;
}

/** Minimal session surface the OTel lifecycle needs. */
declare type OtelSession = {
    sessionId: string;
    on(eventType: "*", handler: (event: SessionEvent) => void): () => void;
    onToolsUpdate?: OnToolsUpdateFn;
    getAvailableCustomAgents?: () => SweCustomAgent[];
    getSelectedCustomAgent?: () => SweCustomAgent | undefined;
    getAuthInfo?: () => AuthInfo | undefined;
};

/** Options forwarded from the session creation call. */
declare interface OtelTrackingOptions {
    model?: string;
    providerType?: string;
    providerBaseUrl?: string;
    streaming?: boolean;
    traceparent?: string;
    tracestate?: string;
    agentVersion?: string;
    reasoningLevel?: string;
}

declare function parseTodoCounts(todos: string): {
    total: number;
    completed: number;
    pending: number;
};

/**
 * Parse a markdown checklist into structured entries, preserving order.
 * Recognizes:
 *   - `- [x]` / `- [X]` → completed
 *   - `- [ ]` → pending
 *   - `- [-]` / `- [~]` / `- [/]` → in_progress (common community conventions)
 * Bullet markers may be `-`, `*`, `+`, or numbered (`1.` / `1)`). Lines without
 * a checkbox marker are ignored.
 *
 * The Rust runtime already yields the exact status union, so the entries are
 * returned directly with no TS-side narrowing or reshaping.
 */
declare function parseTodoEntries(todos: string): TodoEntry[];

/**
 * 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.
 */
declare type PassivePolicy = false | {
    type: "drop" | "wait-for-next-turn";
};

declare interface PathManager {
    /**
     * Get all allowed directories
     */
    getDirectories(): string[];
    /**
     * Get the directories recorded as standing explicit grants (added with
     * `markIndependent = true`: approve-for-session, `permissions.paths.add`,
     * the `/add-dir` slash). Callers carrying directories between managers use
     * this to preserve explicit-grant provenance instead of downgrading every
     * carried directory to location-scoped.
     */
    getIndependentDirectories(): string[];
    /**
     * Check if a path is within any of the allowed directories
     */
    isPathWithinAllowedDirectories(pathToCheck: string): Promise<boolean>;
    /**
     * Check if a path is within the workspace directory (session folder).
     * Used to auto-approve writes to workspace files like plan.md.
     */
    isPathWithinWorkspace(pathToCheck: string): Promise<boolean>;
    /**
     * Get the primary directory (usually the current working directory)
     */
    getPrimaryDirectory(): string;
    /**
     * Update the primary directory (e.g., when /cwd command is used)
     */
    updatePrimaryDirectory(newDir: string): Promise<void>;
    /**
     * Add an additional directory to the allowed list. When `markIndependent`
     * is true (the default, and the case for every genuine user grant -
     * approve-for-session, `permissions.paths.add`, the `/add-dir` slash) the
     * directory is recorded as a standing explicit grant that survives a later
     * cwd re-base. Internal allow-all copies (carrying dirs between managers)
     * pass false so a location-scoped dir is never mis-recorded as explicit.
     * Returns the resolved directory stored by the manager.
     */
    addDirectory(dir: string, markIndependent?: boolean): Promise<string>;
    /**
     * Atomically remove location-scoped directories (exact match against the
     * stored resolved entries; the primary is never removed) and add the given
     * directories if not already present. Used by the locations.apply re-key
     * to prune the previous location's directories.
     */
    replaceLocationDirectories(remove: string[], add: string[]): Promise<ReplaceLocationDirectoriesResult>;
}

/**
 * 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 */
declare interface PendingMessagesModifiedData {
}

export declare type PendingMessagesModifiedEvent = WireTypes.PendingMessagesModifiedEvent;

/** Session event "pending_messages.modified". Empty payload; the event signals that the pending message queue has changed */
declare interface PendingMessagesModifiedEvent_2 {
    /** 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[];
}

/**
 * Represents a pending queued item for UI display purposes.
 */
export declare interface PendingQueuedItem {
    kind: "message" | "command";
    displayText: string;
}

/**
 * Manages the request/response lifecycle for permission and user-input interactions.
 *
 * Emits events and awaits responses via pending promise maps.
 * Permission and external-tool request boundaries use the durable `emit`
 * callback so they are persisted to the session log and survive suspend/resume.
 * All other interactions (user input, elicitation, sampling, MCP OAuth,
 * commands, exit-plan-mode, auto-mode switch) use `emitEphemeral`.
 * Clients (TUI, SDK, ACP) subscribe to events and call the respond methods.
 *
 * Suspend/resume model:
 * - Permission and external-tool *request boundaries* are persisted to the
 *   session log so resume can recover what was outstanding. Permission decisions
 *   and external-tool-completion markers are also persisted; external tool
 *   *results* are not (they are caller-owned and must be re-supplied via
 *   respondToExternalTool after resume if the consumer tracked the call).
 * - Permissions can be re-driven safely. If a permission request is outstanding
 *   on resume, the consumer may either supply a late decision or (for SDKs that
 *   did not persist the prompt) re-prompt the user.
 * - External tool calls have side effects that the SDK consumer owns. The
 *   runtime never re-issues an external tool call that has already been
 *   dispatched; the consumer must re-supply the result if it tracked the call
 *   across suspend, otherwise the orphan is reported as interrupted.
 * - A new user message preempts any outstanding request — the same model as in
 *   the non-suspend flow; suspend just makes the lookup durable.
 */
declare class PendingRequestStore {
    private readonly emitEphemeral;
    private readonly emit;
    /** Tool call IDs that a preToolUse hook has explicitly allowed (permissionDecision: "allow"). */
    private readonly hookAllowedToolCallIds;
    private readonly permissionRequests;
    private readonly userInputRequests;
    private readonly elicitationRequests;
    private readonly samplingRequests;
    /**
     * Tracks all emitted MCP OAuth request IDs in one place. Legacy in-process
     * callers may still respond with their own provider, while host-delegated
     * requests store the pre-created provider that `handlePendingRequest` updates.
     */
    private readonly mcpOAuthRequests;
    private readonly mcpHeadersRefreshRequests;
    private readonly externalToolRequests;
    private readonly queuedCommandRequests;
    private readonly commandExecutionRequests;
    private readonly exitPlanModeRequests;
    private readonly autoModeSwitchRequests;
    private readonly sessionLimitsExhaustedRequests;
    private activeSessionLimitsExhaustedRequest;
    /**
     * Short-lived record of prompt IDs (requestId or toolCallId) for which a
     * permission / user-input / elicitation / exit-plan-mode request was
     * recently resolved. Lets `findXByPromptId` distinguish "raced and lost
     * to the in-process responder" (quiet `already-resolved`) from "never
     * existed" (loud `not-found` warning that signals a real drop).
     *
     * The tombstone is intentionally lightweight: a TTL-bounded Map of
     * promptId → expiry timestamp. Entries auto-expire on lookup. The TTL
     * is generous (60s) because MC steering responses can be authored by a
     * user on mobile after a meaningful delay; a fast in-process responder
     * commonly wins by seconds-to-minutes, not microseconds.
     */
    private readonly resolvedPromptIdTombstones;
    private static readonly TOMBSTONE_TTL_MS;
    /** Per-capability cancel callbacks. When a capability is lost, all registered callbacks fire. */
    private readonly capabilityCancellers;
    constructor(emitEphemeral: (type: string, data: Record<string, unknown>) => void, emit: (type: string, data: Record<string, unknown>) => void);
    /** Mark a tool call ID as pre-approved by a preToolUse hook. */
    addHookAllowedToolCallId(toolCallId: string): void;
    /** Check whether a tool call ID was pre-approved by a preToolUse hook. */
    isHookAllowedToolCallId(toolCallId: string): boolean;
    /** Clear all hook-allowed tool call IDs (called at the start of each preToolsExecution batch). */
    clearHookAllowedToolCallIds(): void;
    /** 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>;
    /**
     * Snapshot the live, still-pending user-input (ask_user) requests with their
     * original payloads. Because `user_input.requested` is emitted ephemerally
     * (not persisted to the event log), a client that attaches after the event
     * fired -- e.g. the foreground UI switching back to a backgrounded session --
     * cannot reconstruct the prompt from history the way it can for permissions.
     * Reading the in-memory map lets the UI re-surface the pending prompt on
     * switch-back. Resolved requests are removed from the map, so this never
     * returns a stale (already-answered) prompt.
     */
    getPendingUserInputRequests(): PendingUserInputRequest[];
    /** Respond to a pending permission request by its ID. */
    respondToPermission(requestId: string, result: PermissionPromptResponse): boolean;
    /**
     * 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;
    /**
     * Snapshot the live, still-pending elicitation requests with their original
     * payloads and source. Mirrors {@link getPendingUserInputRequests}: the
     * `elicitation.requested` event is ephemeral, so the foreground UI cannot
     * rebuild the dialog from history when it switches back to a backgrounded
     * session -- it reads the in-memory map instead. Resolved requests are
     * removed from the map, so a stale prompt is never returned.
     */
    getPendingElicitationRequests(): PendingElicitationRequest[];
    /** 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. Returns true if the request was still pending (and
     * was resolved by this call), false if the request ID was unknown or
     * already resolved.
     */
    respondToSampling(requestId: string, response?: CreateMessageResultWithTools): boolean;
    /**
     * Register a callback to fire when a capability is lost.
     * Returns an unregister function to clean up when the request completes normally.
     */
    private onCapabilityLost;
    /** 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): 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;
    /** 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;
    /** Emit an external tool request event and return a promise that resolves when responded to. */
    requestExternalTool(request: ExternalToolRequest): 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 without emitting completion events. */
    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; false when the request
     * was already resolved, cancelled, or unknown.
     */
    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. 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;
    /** 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), false if
     * the request ID was unknown or already resolved.
     */
    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;
    /**
     * Look up a pending user-input request by Mission Control `promptId`.
     * MC reports `promptId = toolCallId ?? requestId`, so we accept either:
     * direct map hit (promptId === requestId) or a scan for a matching
     * `toolCallId`. Returns either the host `requestId`, the literal
     * `"already-resolved"` (a recent responder beat us to it; the steer
     * response is a quiet race-loser, not a drop), or `undefined`.
     */
    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`.
     * Returns the host `requestId` and the original `promptRequest` (so the
     * caller can pass it to response builders that need request context,
     * e.g. for `scope: "session"` URL domain / command identifier
     * extraction), the literal `"already-resolved"`, or `undefined`.
     */
    findPermissionByPromptId(promptId: string): {
        requestId: string;
        promptRequest: PermissionPromptRequest_2;
    } | "already-resolved" | undefined;
    /**
     * Record that the given requestId (and optionally its toolCallId) was
     * just resolved. Subsequent `findXByPromptId` calls within the TTL
     * window will return `"already-resolved"` instead of `undefined`,
     * letting callers distinguish "raced and lost" from "never existed".
     */
    private tombstonePromptIds;
    /** Returns true if `promptId` is in the tombstone set and within TTL. */
    private consumeTombstone;
}

/** 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. */
declare type PermissionAllowAllMode = "off" | "on" | "auto";

/** Permission response variant indicating the request was approved without persisting an approval rule. */
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. */
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. */
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. */
declare interface PermissionAutoApproval {
    /** 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. */
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 */
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;
}

export declare type PermissionCompletedEvent = WireTypes.PermissionCompletedEvent;

/** Session event "permission.completed". Permission request completion notification signaling UI dismissal */
declare interface PermissionCompletedEvent_2 {
    /** 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 | 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 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 | 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 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 {
    /** 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;
}

/** 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";
}

/** 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 {
    /** Request ID of the pending permission request */
    requestId: string;
    /** The client's response to the pending permission prompt */
    result: PermissionDecision;
}

/** 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. */
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. */
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. */
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. */
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. */
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 */
declare type PermissionPromptRequest = PermissionPromptRequestCommands | PermissionPromptRequestWrite | PermissionPromptRequestRead | PermissionPromptRequestMcp | PermissionPromptRequestUrl | PermissionPromptRequestMemory | PermissionPromptRequestCustomTool | PermissionPromptRequestPath | PermissionPromptRequestHook | PermissionPromptRequestExtensionManagement | 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 */
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";
    /** 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 */
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 */
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 */
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;
}

/** Hook confirmation permission prompt */
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 */
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 */
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 */
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 */
declare type PermissionPromptRequestPathAccessKind = "read" | "shell" | "write";

/** File read permission prompt */
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";
    /** Path of the file or directory being read */
    path: string;
    /** Tool call ID that triggered this permission request */
    toolCallId?: string;
}

/** URL access permission prompt */
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";
    /** 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 */
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";
    /** 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_2 | 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 */
declare type PermissionRequest = PermissionRequestShell | PermissionRequestWrite | PermissionRequestRead | PermissionRequestMcp | PermissionRequestUrl | PermissionRequestMemory | PermissionRequestCustomTool | PermissionRequestHook | PermissionRequestExtensionManagement | 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 | ExtensionPermissionAccessRequest);

/** Custom tool invocation permission request */
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 */
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;
}

export declare type PermissionRequestedEvent = WireTypes.PermissionRequestedEvent;

/** Session event "permission.requested". Permission request notification requiring client approval with request details */
declare interface PermissionRequestedEvent_2 {
    /** 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 */
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 */
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;
}

/** Hook confirmation permission request */
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 */
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 */
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 */
declare type PermissionRequestMemoryAction = "store" | "vote";

/** Vote direction (vote only) */
declare type PermissionRequestMemoryDirection = "upvote" | "downvote";

/** File or directory read permission request */
declare interface PermissionRequestRead {
    /** Human-readable description of why the file is being read */
    intention: string;
    /** Permission kind discriminator */
    kind: "read";
    /** 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;
}

/** Indicates whether the permission decision was applied; false when the request was already resolved. */
declare interface PermissionRequestResult {
    /** Whether the permission request was handled successfully */
    success: boolean;
}

/**
 * The result of requesting permissions.
 */
declare type PermissionRequestResult_2 = {
    readonly kind: "approved";
} | {
    readonly kind: "approved-for-session";
    readonly approval: Extract<SessionApproval, {
        kind: UserToolPermissionRequest["kind"];
    }>;
} | {
    readonly kind: "approved-for-location";
    readonly approval: Extract<SessionApproval, {
        kind: UserToolPermissionRequest["kind"];
    }>;
    readonly locationKey: string;
} | {
    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;
};

/** Shell command permission request */
declare interface PermissionRequestShell {
    /** Whether the UI can offer session-wide approval for this command pattern */
    canOfferSessionApproval: boolean;
    /** 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";
    /** 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. */
declare interface PermissionRequestShellCommand {
    /** Command identifier (e.g., executable name) */
    identifier: string;
    /** Whether this command is read-only (no side effects) */
    readOnly: boolean;
}

/** A URL that may be accessed by a command in a shell permission request. */
declare interface PermissionRequestShellPossibleUrl {
    /** URL that may be accessed by the command */
    url: string;
}

/** URL access permission request */
declare interface PermissionRequestUrl {
    /** Human-readable description of why the URL is being accessed */
    intention: string;
    /** Permission kind discriminator */
    kind: "url";
    /** 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 */
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";
    /** 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;
}

/** The result of the permission request */
declare type PermissionResult = PermissionApproved | PermissionApprovedForSession | PermissionApprovedForLocation | PermissionCancelled | PermissionDeniedByRules | PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser | PermissionDeniedInteractivelyByUser | PermissionDeniedByContentExclusionPolicy | PermissionDeniedByPermissionRequestHook;

/**
 * Options for customizing permission denial messages.
 */
declare type PermissionResultMessages = {
    /** Custom message for when permission is denied by rules. If not provided, uses default. */
    deniedByRules?: 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 {
    /** 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. */
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";
}

/**
 * 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 permission service is responsible for managing permission to use tools and access paths.
 */
declare type PermissionService = {
    request: RequestPermissionFn;
    configure: (options: {
        approveAllToolPermissionRequests?: boolean;
        approveAllReadPermissionRequests?: boolean;
        rules?: {
            approved: ReadonlyArray<Rule>;
            denied: ReadonlyArray<Rule>;
        };
        pathManager?: PathManager;
        urlManager?: UrlManager;
        autoApprovalPermissionRequests?: boolean;
    }) => void;
    resetSessionToolApprovals: () => void;
    setApproveAllToolPermissionRequests: (value: boolean, source?: AllowAllSource) => void;
    /** Returns the current state of the approve-all-tool flag for this service. */
    getApproveAllToolPermissionRequests: () => boolean;
    setAutoApprovalPermissionRequests: (value: boolean) => void;
    getAutoApprovalPermissionRequests: () => boolean;
    addApprovedRules: (newRules: ReadonlyArray<Rule>) => void;
    removeApprovedRules: (rulesToRemove: ReadonlyArray<Rule>) => void;
    /** Add rules that came from location permissions (can be removed separately). */
    addLocationApprovedRules: (newRules: ReadonlyArray<Rule>) => void;
    /** Remove only rules that were added via addLocationApprovedRules. */
    removeLocationApprovedRules: () => void;
    /** Set the telemetry sender for permission-related telemetry events. */
    setTelemetrySender: (sender: TelemetrySender) => void;
    /** Set the callback invoked just before a permission prompt is shown to the user. */
    setOnPromptShown: (callback: ((message: string) => void) | undefined) => void;
    /** Check if MCP sampling is pre-approved for a given server. */
    checkSamplingApproval: (serverName: string) => "approved" | "unknown";
    /** The live PathManager used for filesystem permission checks. Mutations are visible immediately. */
    getPathManager: () => PathManager;
    /** The live UrlManager used for URL permission checks. Mutations are visible immediately. */
    getUrlManager: () => UrlManager;
    /**
     * Apply the enterprise managed-settings `permissions` slice verbatim as the
     * policy ceiling. The engine interprets it and returns whether escalation is
     * now capped (bypass-permissions mode disabled), so callers can mirror the
     * verdict for their own UX gate. `undefined` clears the policy.
     */
    setManagedPolicy: (permissions: ManagedPermissionsSlice | undefined) => boolean;
};

/** 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 | 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 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 {
}

/** No parameters; clears all session-scoped tool permission approvals. */
declare interface PermissionsResetSessionApprovalsRequest {
}

/** 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's active model is used. */
    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 */
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. */
declare type PersistedBinaryImageType = "image" | "resource";

export declare type PersistedBinaryResult = WireTypes.PersistedBinaryResult;

/** A model-facing binary result as persisted: full inline data, a size-omitted marker, or a deduplicated asset reference */
declare type PersistedBinaryResult_2 = PersistedBinaryImage | OmittedBinaryResult_2 | BinaryAssetReference_2;

declare interface PersistedSessionCwdInfo {
    /** Last known session working directory when a valid persisted `cwd` is present. */
    cwd: string | undefined;
    /**
     * Whether `workspace.yaml` contained a non-empty `cwd` field. This stays
     * true when the field was present but invalid, so callers can distinguish
     * "no persisted cwd" from "persisted cwd cannot be used".
     */
    persistedFieldPresent: boolean;
}

/** 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 */
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";
}

/** The type of operation performed on the plan file */
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;
}

/** 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;
    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;
}

declare type PrivateRepo = "private";

declare const processLargeOutput: (result: ToolResultExpanded, options?: LargeOutputOptions) => Promise<ToolResultExpanded>;

/**
 * A single progress line for a background agent task.
 */
export declare type ProgressLine = {
    /** Display message, e.g., "bash", "edit src/foo.ts". */
    message: string;
    /** When this event occurred. */
    timestamp: number;
};

declare type ProgressToken = string | number;

/**
 * A task currently waiting synchronously that can be promoted to background
 * execution from the CLI.
 */
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 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[];
    /** 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[];
}

/** 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_2;
    /**
     * 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_2;
    /** 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;
    /** 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. */
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, shared by {@link ProviderConfig} and
 * {@link NamedProviderConfig}.
 */
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 referencing a named provider. */
declare interface ProviderModelConfig {
    /** Optional capability overrides (vision, tool_calls, reasoning, etc.). */
    capabilities?: ModelCapabilitiesOverride;
    /** 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;
}

/**
 * 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_2 {
    /**
     * 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_2;
}

/** 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];

/** Result of a session prune operation. */
declare interface PruneResult {
    /** Session IDs that were deleted (empty in dry-run mode). */
    deleted: string[];
    /** Session IDs that would be deleted in dry-run mode (empty when not dry-run). */
    candidates: string[];
    /** Session IDs that were skipped (e.g., named sessions). */
    skipped: string[];
    /** Total bytes freed (actual) or that would be freed (dry-run). */
    freedBytes: number;
    /** Whether this was a dry run (no actual deletions). */
    dryRun: boolean;
}

declare type PublicRepo = "public";

/** 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;
}

/** 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.
 */
export 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;
};

/**
 * 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.
 */
export declare type QueuedItem = QueuedMessageItem | QueuedMessagesItem | QueuedCommandItem | QueuedModelChangeItem | QueuedResumePendingItem;

/**
 * Represents a queued user message to be processed by the agentic loop.
 */
export 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.
 */
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.
 */
export declare interface QueuedModelChangeItem {
    kind: "model_change";
    model: string;
    reasoningEffort?: ReasoningEffort;
    reasoningSummary?: ReasoningSummary_3;
    modelCapabilitiesOverrides?: ModelCapabilitiesOverride_2;
    contextTier?: ContextTier_3;
    verbosity?: Verbosity_3;
}

/**
 * Represents an internal wake-up to continue processing after a late permission
 * or external tool response was durably recorded.
 */
export declare interface QueuedResumePendingItem {
    kind: "resume_pending";
}

/** User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. */
declare interface QueuePendingItems {
    /** Human-readable text to display for this queue entry in the UI */
    displayText: 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[];
}

/** 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;
}

/** Logger that queues log messages until a real logger is set */
declare class QueuingProxyLogger implements Logger, Disposable_2 {
    private initialQueue;
    private initialQueueResolvers;
    private logWriter;
    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).
     */
    flush(): Promise<void>;
    /** Alias for Disposable interface */
    dispose(): Promise<void>;
    outputPath(): string | undefined;
    private logToLevel;
    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: LogLevel): boolean;
    notice(message: string | Error): void;
    startGroup(name: string, _?: LogLevel): void;
    endGroup(_?: LogLevel): 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;
    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") */
declare type ReasoningSummary = "none" | "concise" | "detailed";

/** Reasoning summary mode to request for supported model clients */
declare type ReasoningSummary_2 = "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_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 const registerTempFile: (fs: SessionFs, filePath: string) => void;

declare type RejectedToolResult = ToolResultExpanded & {
    resultType: "rejected";
};

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;
}

/**
 * Relevance score for a session relative to the current working directory.
 * Higher scores indicate more relevant sessions.
 */
declare type RelevanceScore = 0 | 1 | 2 | 3 | 4;

/** 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;
}

/**
 * Configuration for the runtime-managed remote-control singleton.
 *
 * Conceptually a "Mission Control connection" pointed at a single local
 * session at any one time. The CLI never constructs an exporter directly;
 * instead it asks the runtime to attach/transfer/stop remote control via
 * the {@link SessionsApi} surface, and the runtime owns the exporter
 * lifecycle, MC client, and credentials.
 */
declare interface RemoteControlConfig_2 {
    /** Whether remote export should be enabled. (False disables completely.) */
    remote: boolean;
    /** Whether the connected MC session may steer the local session (write mode). */
    steerable: boolean;
    /**
     * Whether the user explicitly requested remote (via `--remote` or
     * `/remote on`). Controls whether missing-repo warnings are surfaced to
     * the timeline (explicit) vs. only logged (implicit / session sync).
     */
    explicit: boolean;
    /**
     * When true, suppresses timeline messages from the exporter on
     * successful setup. Used for implicit session-sync exports.
     */
    silent: boolean;
    /** Existing Mission Control task to attach the exported session to. */
    taskId?: string;
    /** Existing Mission Control session to reattach to without creating a new one. */
    existingMcSession?: {
        mcSessionId: string;
        mcTaskId: string;
    };
    /** Enterprise managed remote-control setting for this host, when resolved by the caller. */
    managedRemoteControl?: ManagedRemoteControlSettings;
}

/** 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;

/**
 * State of the runtime-managed remote-control singleton.
 *
 * The state machine:
 * - `off` — no remote control active
 * - `connecting` — initial setup in flight for `attachedSessionId`
 * - `active` — connected and pointed at `attachedSessionId`
 * - `error` — last setup attempt failed (next start clears the error)
 *
 * `promptManager` on the `active` state is an opaque in-process handle —
 * the CLI passes it back to its `wrapAskUserForRemote` helpers without
 * introspecting its shape. Always undefined off the in-process boundary.
 */
declare type RemoteControlStatus_2 = {
    state: "off";
} | {
    state: "connecting";
    attachedSessionId: string;
} | {
    state: "active";
    attachedSessionId: string;
    frontendUrl?: string;
    isSteerable: boolean;
    promptManager?: unknown;
    /** True while a read-only/session-sync export is deferred, awaiting the first `user.message` before its MC session exists. */
    awaitingFirstMessage?: boolean;
} | {
    state: "error";
    error: string;
    attachedSessionId?: string;
};

/** 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.
 *
 * Registration only happens in the CLI TUI (`src/cli/app.tsx`). When the
 * runtime is driven by a JSON-RPC SDK consumer (e.g. `copilot --server
 * --stdio`) the TUI doesn't run, so the `pending` map stays empty and MC
 * steer responses for in-flight prompts would otherwise be silently
 * dropped at `debug` level.
 *
 * Each `findXByPromptId` accepts a `promptId` that matches either the
 * host `requestId` or the stored `toolCallId` (mirroring the TUI's
 * `promptId = toolCallId ?? requestId` contract). They return:
 * - `string` (requestId) — match found, dispatch via the matching
 *   `respondToX`.
 * - `"already-resolved"` — the entry was drained recently and is in the
 *   tombstone window (race-loser; classify as `already-resolved`, not
 *   `not-found`, to avoid steady-state warning spam).
 * - `undefined` — no matching pending request.
 */
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): boolean;
}

/** 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;
    /** The original resource identifier (task ID or PR node ID), preserved across fromEvents(). */
    readonly resourceId?: string;
    readonly isRemote: true;
    /** Whether this task originated from CCA or CLI `--remote`. */
    readonly taskType?: RemoteTaskType;
    /** Deadline at which a CLI remote session becomes stale without further heartbeats. */
    readonly staleAt?: Date;
    /** Server-side task state returned by GitHub. */
    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 */
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";
}

/** Discriminates whether a remote task originated from CCA or CLI `--remote`. */
export declare type RemoteTaskType = "cca" | "cli";

/**
 * Outcome of {@link PathManager.replaceLocationDirectories}: the resolved
 * directories genuinely inserted by the call and the entries that failed to
 * resolve (the rest still apply).
 */
declare interface ReplaceLocationDirectoriesResult {
    added: string[];
    failed: Array<{
        directory: string;
        error: string;
    }>;
}

declare const reply_to_comment: (config: ToolConfig, logger: RunnerLogger) => Tool;

declare const REPLY_TO_COMMENT_TOOL_NAME = "reply_to_comment";

declare class RepoChangeSet {
    private handle;
    private constructor();
    static create(git: GitHandler, repoLocation: string, baseCommit: string, abortSignal?: AbortSignal): Promise<RepoChangeSet>;
    static create(repoLocation: string, baseCommit: string, abortSignal?: AbortSignal): Promise<RepoChangeSet>;
    getFileRanges(): FileRange[];
    getChangedFiles(): Set<string>;
    getChangedFilesSince(previous: RepoChangeSet): Set<string>;
    dispose(): void;
    [Symbol.dispose](): void;
    private requireHandle;
}

declare type RepoHostType = "github" | "ado";

declare const report_progress: (config: ToolConfig, settings: ReportProgressSettings, logger: RunnerLogger, exec: RunnerExec) => Tool;

declare const REPORT_PROGRESS_ONLY_PUSH_FEATURE_FLAG = "sweagentd_report_progress_only_push";

declare const REPORT_PROGRESS_TOOL_NAME = "report_progress";

declare const reportProgressLegacyToolDescription: string;

declare const reportProgressPushOnlyToolDescription: string;

declare type ReportProgressSettings = Parameters<GitHandler["commitChanges"]>[0];

declare type RepoVisibility = PublicRepo | PrivateRepo;

/**
 * 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_2>;

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_2>;

declare type RequestUserInputFn = (request: AskUserRequest) => Promise<AskUserResponse>;

declare type ResolveArgs = {
    authInfo: AuthInfo;
    integrationId: string;
    sessionId: string;
    logger: RunnerLogger;
    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 (`accountApi.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>;

/** 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_2;
}

/**
 * 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.
 */
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;
};

/** Resolved prompt returned by {@link ScheduleRegistryHost.invokeCommand}. */
declare interface ResolvedScheduledPrompt {
    /** Prompt text to deliver to the agent. */
    readonly prompt: string;
    /** Optional user-facing label; falls back to the stored entry display when omitted. */
    readonly displayPrompt?: string;
    /** Optional session mode to set for this delivered message. */
    readonly mode?: SessionMode;
}

export declare function resolveExpFlag(featureFlagService: IFeatureFlagService | undefined, expFlag: ExpFlagKey, featureFlag: FeatureFlag, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

export declare function resolveFeatureFlags(isStaff: boolean, isExperimental: boolean, isTeam: boolean, options?: FeatureFlagResolutionOptions): FeatureFlags;

/** Whether Anthropic's built-in server-side tool search (`TOOL_SEARCH_BUILTIN_ANTHROPIC`) applies. */
declare function resolveIsBuiltinToolSearchEnabled(model: string, featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

declare function resolveIsGenericClientToolSearchEnabled(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>, modelConfigEnabled?: boolean, explicitlyEnabled?: boolean): Promise<boolean>;

/** Whether tool search is enabled for `model` via the override flag and model-family ExP. */
declare function resolveIsToolSearchEnabled(model: string, featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

export declare function resolveNoPlanningFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

export declare function resolveNoViewLineNumbersFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

export declare function resolveSessionModelOverrideFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

export declare function resolveSkillsListInSystemPromptFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly<Partial<Record<FeatureFlag, boolean>>>): Promise<boolean>;

/**
 * Resolve a relative file path within a base directory, rejecting path traversal attempts.
 * @internal Exported for testing only.
 */
export declare function resolveWorkspacePath(baseDir: string, filePath: string): string;

declare interface ResourceContent extends BaseContentBlock {
    type: "resource";
    resource: ResourceContents;
}

declare type ResourceContents = TextResourceContents | BlobResourceContents;

export declare type ResourceLink = WireTypes.ResourceLink;

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 ResponseLimitsExhaustedHandler = (status: ResponseLimitsStatus) => boolean | Promise<boolean>;

declare class ResponseLimitsPreRequestProcessor implements IPreRequestProcessor {
    private readonly getResponseLimits;
    private readonly getUsageMetrics;
    private readonly onLimitsStatus?;
    private readonly onLimitsExhausted?;
    private readonly nativeHandle;
    constructor(getResponseLimits: () => SessionLimitsConfig_3 | undefined, getUsageMetrics: () => UsageMetrics, onLimitsStatus?: ((status: ResponseLimitsStatus, state: ResponseLimitsEventState, message: string) => void) | undefined, onLimitsExhausted?: ResponseLimitsExhaustedHandler | undefined, nativeHandle?: number);
    beginResponse(): void;
    forkForSession(): ResponseLimitsPreRequestProcessor;
    forkForCurrentResponse(): ResponseLimitsPreRequestProcessor;
    nativePreRequestProcessorConfig(): NativePreRequestProcessorConfig;
    nativeUsageMetrics(): ReturnType<typeof toNativeUsageMetrics>;
    nativeLimitsConfig(): ReturnType<typeof toOptionalNativeLimitsConfig>;
    handleLimitsExhausted(status: ResponseLimitsStatus): Promise<boolean>;
    reconcileAfterUsage(): ResponseLimitsStatus | undefined;
    getCurrentStatus(): ResponseLimitsStatus | undefined;
    toJSON(): string;
}

declare interface ResponseLimitsStatus {
    aiCreditsUsed?: number;
    aiCreditsRemaining?: number;
    maxAiCredits?: number;
    isLimitsExhausted: boolean;
    /**
     * True when the next model call should be treated as the final call for this session.
     * Credit limits use a conservative low-remaining heuristic because exact AI credit
     * spend is only known after each call.
     */
    isFinalModelCall: boolean;
}

/**
 * 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 `core/responseLimits` (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";

/**
 * Per-call behavior knobs for `LocalSessionManager.getSession` /
 * `getLastSession`. Distinct from `SessionOptions` so CLI-internal
 * policies do not leak into the SDK surface (which exports `SessionOptions`
 * via `./sdk`).
 */
declare interface ResumeBehavior {
    /**
     * Caller-requested suppression of the resume `workspace.yaml` writeback.
     * Set by the CLI for non-interactive resume flows (e.g. `--prompt
     * --resume <id>`, `--continue`, single-session interactive startup)
     * where the CLI seeds an incidental `workingDirectory` (the resolved
     * launch/`-C` dir) at the call site. Rebinding the persisted record to
     * that incidental cwd would corrupt the saved session.
     *
     * `getSession()` honors this flag for the workspace.yaml writeback
     * ONLY when the resolved `workingDirectory` does not point at the
     * same directory as the persisted cwd (compared via
     * `workingDirectoryMatchesPersistedCwd`, which uses `realpath` so
     * symlinked equivalents still match). When the two match, the
     * writeback is a safe refresh of the persisted record (`cwd` is
     * already at the persisted location, only the live
     * `branch`/`gitRoot`/`repository` are written on top) and the flag
     * is ignored for the writeback gate -- this lets `--continue` from
     * the matching cwd refresh stale git context without needing a
     * separate signal from the CLI.
     *
     * The repo-hooks enqueue gate honors the RAW value of this flag in
     * the `persistedCwdInvalid` override branch (CLI's incidental
     * `workingDirectory` is not a hook-safe override); the cwd-match
     * softening does NOT apply there. Hook safety is a provenance
     * question and is independent from whether the writeback would
     * preserve the persisted record.
     *
     * `-C <dir>` overrides this flag at the call site, since `-C` is an
     * explicit user-expressed binding.
     */
    suppressResumeWorkspaceMetadataWriteback?: boolean;
    /**
     * Pre-loaded `workspace.yaml.cwd` lookup result. When supplied,
     * `getSession` skips its own `loadPersistedSessionCwd` call. Used by
     * `SDKServer.session.resume` to avoid a second `workspace.yaml` read on
     * the cold-load path: the server already loads this info to scope MCP /
     * config discovery, and re-loading inside `getSession` for the same
     * canonical session id is pure waste.
     *
     * Invariant: callers must pre-load using the same canonical session id
     * and effective settings that `getSession` would resolve to. In
     * particular, the lookup should be done AFTER `findSessionByPrefix`
     * canonicalization so the injected info matches the session the
     * resume actually targets.
     */
    persistedCwdInfo?: PersistedSessionCwdInfo;
}

/** Session resume metadata including current context and event count */
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 (the default), any such tool calls and permission requests are immediately marked as interrupted on resume. */
    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 attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. */
    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";
}

/**
 * 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: RunnerLogger, featureFlagService?: IFeatureFlagService, options?: {
    skipCache?: boolean;
}): Promise<{
    models: Model[];
    unfilteredModels: Model[];
    copilotUrl: string | undefined;
    quotaSnapshots?: QuotaSnapshotsByType;
}>;

/**
 * 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 const RUN_FACTORY_TOOL_NAME = "run_factory";

declare interface RunFactoryApi {
    run(name: string, options: {
        args: unknown;
        limits?: FactoryLimits;
        resumeFromRunId?: string;
    }): Promise<FactoryRunResult>;
}

declare interface RunnerExec {
    /**
     * Exec a command.
     * Output will be streamed to the live console.
     * Arguments included in filteredCmdArgs will be replaced by REDACTED in privacy-sensitive output.
     * For example, if args is ["notPrivate", "private1", "notPrivate", "private2"] then filteredCmdArgs should be ["private1", "private2"]
     * Returns promise with return code
     *
     * @param     commandLine        command to execute (can include additional args). Must be correctly escaped.
     * @param     args               optional arguments for tool. Escaping is handled by the lib.
     * @param     options            optional exec options.  See RunnerExecOptions
     * @param     filteredCmdArgs    values that occur in the args array and which should be hidden for privacy reasons.
     * @returns   Promise<number>    exit code
     */
    exec(commandLine: string, args?: string[], options?: RunnerExecOptions, filteredCmdArgs?: string[]): Promise<number>;
    /**
     * Exec a command and get the output.
     * Output will be streamed to the live console.
     * Arguments included in filteredCmdArgs will be replaced by REDACTED in privacy-sensitive output.
     * For example, if args is ["notPrivate", "private1", "notPrivate", "private2"] then filteredCmdArgs should be ["private1", "private2"]
     * Returns promise with the exit code and collected stdout and stderr
     *
     * @param     commandLine           command to execute (can include additional args). Must be correctly escaped.
     * @param     args                  optional arguments for tool. Escaping is handled by the lib.
     * @param     options               optional exec options.  See RunnerExecOptions
     * @param     filteredCmdArgs       values that occur in the args array and which should be hidden for privacy reasons.
     * @returns   Promise<RunnerExecOutput>   exit code, stdout, and stderr
     */
    execReturn(commandLine: string, args?: string[], options?: RunnerExecOptions, filteredCmdArgs?: string[]): Promise<RunnerExecOutput>;
}

/**
 * The user defined listeners for an exec call
 */
declare interface RunnerExecListeners {
    /** A call back for each buffer of stdout */
    stdout?: (data: Buffer) => void;
    /** A call back for each buffer of stderr */
    stderr?: (data: Buffer) => void;
    /** A call back for each line of stdout */
    stdline?: (data: string) => void;
    /** A call back for each line of stderr */
    errline?: (data: string) => void;
    /** A call back for each debug log */
    debug?: (data: string) => void;
}

declare interface RunnerExecOptions {
    /** optional working directory.  defaults to current */
    cwd?: string;
    /** optional envvar dictionary.  defaults to current process's env */
    env?: NodeJS.ProcessEnv;
    /** optional.  defaults to false */
    silent?: boolean;
    /** optional out stream to use. Defaults to process.stdout */
    outStream?: stream.Writable;
    /** optional err stream to use. Defaults to process.stderr */
    errStream?: stream.Writable;
    /** optional. whether to skip quoting/escaping arguments if needed.  defaults to false. */
    windowsVerbatimArguments?: boolean;
    /** optional.  whether to fail if output to stderr.  defaults to false */
    failOnStdErr?: boolean;
    /** optional.  defaults to failing on non zero.  ignore will not fail leaving it up to the caller */
    ignoreReturnCode?: boolean;
    /** optional.  defaults to true.  If true, debug logging is enabled in silent mode */
    silentDebugLogging?: boolean;
    /** optional. defaults to false.  If true, stderr output will be silenced (logged at debug level instead of error level) */
    silentErr?: boolean;
    /** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
    delay?: number;
    /** optional. input to write to the process on STDIN. */
    input?: Buffer;
    /** optional. Listeners for output. Callback functions that will be called on these events */
    listeners?: RunnerExecListeners;
    /** optional. In milliseconds the maximum amount of time the process is allowed to run. */
    timeout?: number | undefined;
    /** optional. Maximum bytes per output stream before terminating the process; applied independently to stdout and stderr. */
    maxBuffer?: number;
    shell?: string | undefined;
    /** optional. Affects how the command is logged.  defaults to false.  if true, be prefixed by "Copilot:"" in Actions logs */
    isDirectAgentCommand?: boolean;
    /** optional. An AbortSignal that can be used to cancel the process. */
    abortSignal?: AbortSignal;
}

/**
 * Interface for the output of execReturn()
 */
declare interface RunnerExecOutput {
    /**The exit code of the process */
    exitCode: number;
    /**The entire stdout of the process as a string */
    stdout: string;
    /**The entire stderr of the process as a string */
    stderr: string;
}

export declare interface RunnerLogger {
    /**
     * Log a message ignoring the configured log level.
     * This is useful for logging messages that should always be logged, regardless of the log level.
     * @param message The message to log.
     */
    log(message: string): void;
    /**
     * Returns true if the environment is set to debug.
     * Note: This is not the same as the log level being set to debug.
     */
    isDebug(): boolean;
    /**
     * Log a debug message. This is only logged if the log level is set to debug.
     * @param message The message to log.
     */
    debug(message: string): void;
    /**
     * Log an info message. This is only logged if the log level is set to info or debug.
     * @param message The message to log.
     */
    info(message: string): void;
    /**
     * Log a notice message. This is only logged if the log level is set to warning, info, or debug,
     * but logs using the logger's info method.
     * This is useful for logging messages that are not errors, but are important enough to log on
     * less verbose log levels.
     * @param message The message to log.
     */
    notice(message: string | Error): void;
    /**
     * Log a warning message. This is only logged if the log level is set to warning, info, or debug
     * @param message The message to log.
     */
    warning(message: string | Error): void;
    /**
     * Log an error message. This is only logged if the log level is set to error, warning, info, or debug
     * @param message The message to log.
     */
    error(message: string | Error): void;
    /**
     * Returns true if a message at the given level would be written by this logger
     * (i.e. the configured log level is at least as verbose as `level`). Use this
     * to short-circuit expensive message construction (e.g. JSON.stringify of a
     * large request body) at debug-only call sites.
     *
     * Optional for backwards compatibility with SDK consumers implementing this
     * interface. Call sites should fall back to `true` (log) when not implemented:
     * `logger.shouldLog?.(LogLevel.Debug) ?? true`. Built-in loggers (BaseLogger
     * subclasses, CompoundLogger) always implement it.
     */
    shouldLog?(level: LogLevel): boolean;
    /**
     * Log a message that starts a new group.
     * @param name The name of the group.
     * @param level The log level of the group. Defaults to info.
     */
    startGroup(name: string, level?: LogLevel): void;
    /**
     * Log a message that ends the current group.
     * @param level The log level of the group. Defaults to info.
     */
    endGroup(level?: LogLevel): void;
}

/** 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 RuntimeSettings = {
    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;
    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;
    };
    lsp?: {
        clientName: string;
    };
    onlineEvaluation?: {
        disableOnlineEvaluation?: boolean;
        enableOnlineEvaluationOutputFile?: boolean;
    };
    problem?: {
        action?: "fix" | "fix-pr-comment" | "task";
        contentFilterMode?: ContentFilterMode_2;
        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 RuntimeSettings_2 = RuntimeSettings;

declare type RuntimeSettings_3 = RuntimeSettings;

export declare type RuntimeSettingsInput = RuntimeSettings;

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_2;
};

declare type SafetyAssessment = {
    readonly result: "failed";
    readonly reason: string;
} | {
    readonly result: "completed";
    readonly commands: ReadonlyArray<AssessedCommand>;
    readonly possiblePaths: ReadonlyArray<PossiblePath>;
    readonly possibleUrls: ReadonlyArray<PossibleUrl>;
    readonly hasWriteFileRedirection: boolean;
    readonly canOfferSessionApproval: boolean;
    readonly hasDangerousExpansion: boolean;
    readonly warning?: string;
};

/** Sampling request completion notification signaling UI dismissal */
declare interface SamplingCompletedData {
    /** Request ID of the resolved sampling request; clients should dismiss any UI for this request */
    requestId: string;
}

export declare type SamplingCompletedEvent = WireTypes.SamplingCompletedEvent;

/** Session event "sampling.completed". Sampling request completion notification signaling UI dismissal */
declare interface SamplingCompletedEvent_2 {
    /** 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 */
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;
}

export declare type SamplingRequestedEvent = WireTypes.SamplingRequestedEvent;

/** Session event "sampling.requested". Sampling request from an MCP server; contains the server name and a requestId for correlation */
declare interface SamplingRequestedEvent_2 {
    /** 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 sandboxing is enabled for the session. */
    enabled: boolean;
    /** Whether to export `GH_TOKEN` so the `gh` CLI authenticates inside the sandbox without the OS keyring the sandbox blocks. Default: false (opt-in). */
    ghAuth?: boolean;
    /** Whether to inject the Copilot GitHub token as an `http.<host>.extraheader` so authenticated HTTPS git works inside the sandbox without the shell-based credential helper the sandbox blocks. Default: false (opt-in). */
    gitAuth?: boolean;
    /** User-managed sandbox policy fragment merged into the auto-discovered base policy. */
    userPolicy?: SandboxConfigUserPolicy;
}

declare type SandboxConfig_2 = {
    enabled: boolean;
    userPolicy?: StoredSandboxUserPolicy;
} & Omit<StoredSandboxConfig, "enabled" | "userPolicy">;

/** 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;
}

/** 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;
    [key: string]: unknown;
};

declare type SandboxPathPolicy = {
    readwritePaths?: string[];
    readonlyPaths?: string[];
    deniedPaths?: string[];
    clearPolicyOnExit?: boolean;
    [key: string]: unknown;
};

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>;
};

declare interface ScheduleAddOptions {
    recurring?: boolean;
    displayPrompt?: string;
    tz?: string;
}

declare interface ScheduleApi {
    list(): ScheduleEntry_2[];
    hasSelfPaced(): boolean;
    add(interval: string, prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    addCron(cron: string, prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    addAt(at: number, prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    addSelfPaced(prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    rearmSelfPaced(id: number, at: number): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    stop(id: number): ScheduleEntry_2 | undefined;
}

/** Scheduled prompt cancelled from the schedule manager dialog */
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";
}

/** Scheduled prompt registered via /every or /after */
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;
    /** 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;
}

/** Payload persisted for a created schedule. Exactly one of `intervalMs`/`cron`/`at`/`selfPaced` is set. */
declare interface ScheduleCreatedData_2 {
    id: number;
    intervalMs?: number;
    cron?: string;
    tz?: string;
    at?: number;
    prompt: string;
    recurring: boolean;
    displayPrompt?: string;
    selfPaced?: boolean;
}

/** 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";
}

/** Signature of the optional CLI-side dispatcher registered on {@link Session}. */
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;
}

declare interface ScheduleEntry_2 {
    readonly id: number;
    readonly intervalMs?: number;
    readonly cron?: string;
    readonly tz?: string;
    readonly at?: number;
    readonly prompt: string;
    readonly recurring: boolean;
    readonly selfPaced?: boolean;
    readonly displayPrompt?: string;
    readonly nextRunAt: number;
}

/** Narrowed payload of the events the registry subscribes to. */
declare type ScheduleHostEventPayload<T> = Extract<SessionEvent, {
    type: T;
}>;

/** Snapshot of the currently active recurring prompts for this session. */
declare interface ScheduleList {
    /** Active scheduled prompts, ordered by id. */
    entries: ScheduleEntry[];
}

/** Self-paced schedule re-armed for its next run */
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";
}

/**
 * Tracks per-session scheduled prompts and the timers that fire them.
 * Backs `/every` (recurring) and `/after` (one-shot).
 *
 * Lifetime is tied to the session: the registry subscribes to the session's
 * `session.shutdown` event and disposes itself there. A `Session` that owns a
 * registry should let the shutdown wiring drive cleanup; explicit `dispose()`
 * is only needed when an external owner recreates the registry.
 *
 * Schedule changes are persisted as `session.schedule_created`,
 * `session.schedule_rearmed` (self-paced next-run times), and
 * `session.schedule_cancelled` events. On construction the registry walks past
 * events, rebuilds the active set, and resumes the cadence — the next tick
 * of each surviving schedule waits for its full interval rather than firing
 * immediately on resume.
 */
declare class ScheduleRegistry implements ScheduleApi {
    private readonly host;
    private readonly entries;
    private readonly unsubscribeShutdown;
    private readonly unsubscribeIdle;
    private readonly unsubscribeUserMessage;
    private nextId;
    private disposed;
    /**
     * Source of the most recently *started* turn, captured from `user.message`
     * (which fires when the prompt is delivered into a run, not when its tick
     * is armed). Only a turn-STARTING delivery updates it — one delivered `idle`
     * (fired while the session was idle) or `queued` (queued mid-turn, then run
     * as its own later turn). Any other `user.message` rides along on a turn
     * that is already in flight and must not steal its identity, so it is
     * ignored: a `steering` delivery (e.g. a fixed schedule steering mid-turn
     * into a self-paced loop's run) and a mid-turn synthetic injection
     * (`jit-instruction`, `last-turn-warning`, ... — re-emitted with a source
     * but no delivery) both fall here.
     * An aborted `session.idle` reports only that *some* turn was cancelled, not
     * which one, so this lets {@link rearmAbortedSelfPaced} attribute the abort to
     * the turn that was actually running and re-arm only that entry.
     */
    private lastStartedTurnSource;
    constructor(host: ScheduleRegistryHost);
    /**
     * Parse interval, validate, and register a new relative-interval prompt.
     * The first tick fires after the interval has elapsed (not immediately).
     *
     * When `recurring` is true (default) the schedule re-arms after every
     * tick. When false the prompt fires once and is automatically removed.
     */
    add(interval: string, prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    /**
     * Validate and register a recurring calendar (cron) prompt. The cron is
     * evaluated in `options.tz` (defaulting to the host timezone), and the
     * first tick fires at the next matching occurrence.
     */
    addCron(cron: string, prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    /**
     * Register a one-shot prompt that fires at an absolute time (epoch millis).
     * Used by `/after` with a calendar phrase ("tomorrow at 9am"). A time in
     * the past fires as soon as the timer arms. Defaults to non-recurring.
     */
    addAt(at: number, prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    /**
     * Register a self-paced ("dynamic") prompt. There is no fixed cadence: the
     * registry stores the raw task and arms an immediate first run, then PARKS
     * the entry after each run (no auto-rearm). The model decides when (or
     * whether) to run again by calling `manage_schedule` with the `wakeup` action,
     * which routes to {@link rearmSelfPaced}. If the model stops re-arming, the
     * parked entry is swept on the next `session.idle` (see {@link sweepParkedSelfPaced}).
     */
    addSelfPaced(prompt: string, options?: ScheduleAddOptions): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    /**
     * Re-arm an existing self-paced entry to fire next at `at` (epoch millis).
     * Cancels any pending timer and arms a fresh one. Returns an error if the id
     * is unknown (e.g. the user cancelled it) or the entry is not self-paced; the
     * manage_schedule `wakeup` action surfaces that so the model ends the loop.
     */
    rearmSelfPaced(id: number, at: number): {
        entry: ScheduleEntry_2;
    } | {
        error: string;
    };
    private assertActive;
    /**
     * Assign an id, persist a `session.schedule_created` event, and arm the
     * first tick. Shared by {@link add}, {@link addCron}, and {@link addAt}.
     */
    private register;
    /** Snapshot of the currently active entries, ordered by id. */
    list(): ScheduleEntry_2[];
    /**
     * Whether any active (non-cancelled) entry is self-paced. The session uses
     * this to keep the `manage_schedule` wakeup tool exposed for a session that
     * owns a running self-paced loop, even when the foreground UI would otherwise
     * disable it: a backgrounded self-paced `/every` whose timer fires must still
     * be able to re-arm via the tool, or the loop is swept on the next idle.
     */
    hasSelfPaced(): boolean;
    /** Stop a single entry by id. Returns the removed entry, or undefined. */
    stop(id: number): ScheduleEntry_2 | undefined;
    /** Stop everything and unsubscribe from session events. Idempotent. */
    dispose(): void;
    private cancelAll;
    private cancelScheduled;
    /**
     * Walk past `session.schedule_*` events to rebuild the active set, seed
     * the id sequence, and start timers. On resume each surviving schedule is
     * re-armed for its next *future* fire: an interval waits its full period,
     * a cron jumps to its next occurrence, a one-shot calendar fire targets
     * its absolute instant, and a self-paced schedule targets the last
     * model-armed `nextRunAt` replayed from `schedule_rearmed` (each firing
     * immediately only if already due).
     *
     * Called explicitly by Session when its event log is ready (e.g.
     * after a resume replay). Safe to call multiple times: clears any
     * existing entries and timers before rebuilding.
     */
    hydrate(): void;
    /**
     * Insert the entry into the active map and arm its first tick.
     *
     * For fixed schedules `nextRunAt` is set inside {@link scheduleNextTick},
     * which is the single source of truth for that field — both new and
     * rehydrated schedules go through the same arming path. Self-paced entries
     * have no computable cadence: a fresh one arms an immediate first run, while
     * a resumed one restores `selfPacedArmAt` (the last persisted next-run time);
     * thereafter the model controls the timing via {@link rearmSelfPaced}.
     */
    private scheduleEntry;
    /**
     * Arm a self-paced entry to fire at `at` (epoch millis). Unlike
     * {@link scheduleNextTick} this never derives the time from a cadence — the
     * caller supplies it (now for the first run / resume, now+delay for a model
     * re-arm). Re-arming clears the "parked" state so the idle sweep leaves the
     * entry alone.
     */
    private armSelfPacedRun;
    /**
     * A self-paced entry that is "parked": it delivered a run and the model's turn
     * ended without re-arming it — no pending timer and no in-flight delivery.
     *
     * The `inFlightCleanup` guard is what makes this race-safe when a first run
     * was delivered while another turn was busy: delivery sets `inFlightCleanup`
     * synchronously before any await, so a `session.idle` from the unrelated turn
     * sees the entry as in-flight and skips it. By the time the entry is both
     * timer-less and not in-flight, its own run's turn has ended.
     *
     * Both the idle sweep (which ends the loop, {@link sweepParkedSelfPaced}) and
     * the aborted re-arm (which keeps it alive, {@link rearmAbortedSelfPaced}) act
     * on exactly this state, so they share this single predicate to stay in lockstep.
     */
    private isParkedSelfPaced;
    /**
     * Remove self-paced entries that are "parked" (see {@link isParkedSelfPaced}).
     * This is how omitting the manage_schedule `wakeup` action ends a self-paced
     * loop.
     */
    private sweepParkedSelfPaced;
    /**
     * Re-arm the self-paced entry whose own run was interrupted by an *aborted*
     * turn — the user hit Ctrl+C before the model reached its final `wakeup`
     * call. Unlike {@link sweepParkedSelfPaced}, this keeps the loop alive on its
     * established cadence (or {@link ABORTED_REARM_FALLBACK_MS} if it never picked
     * one) instead of ending it: an interrupt cancels the run, not the schedule.
     * This gives self-paced loops the same mid-run-abort resilience a fixed
     * `/every` already has by pre-arming its next tick.
     *
     * Only the entry matching {@link lastStartedTurnSource} — the turn that was
     * actually running when the abort landed — is re-armed. A self-paced loop that
     * already ended cleanly sits parked until the next normal idle sweeps it;
     * without this source check, aborting some *later, unrelated* queued turn
     * would resurrect that intentionally-ended loop.
     */
    private rearmAbortedSelfPaced;
    /**
     * Compute the entry's next fire time and arm its timer. Each tick
     * reschedules itself only after the previous prompt has been delivered
     * into the conversation, so a slow agent turn can never cause overlapping
     * ticks for the same schedule to pile up in the queue.
     *
     * `nextRunAt` is recomputed from the wall clock on every arm via
     * {@link computeNextRunAt}, so interval schedules advance by their period,
     * cron schedules jump to their next occurrence, and one-shot calendar
     * schedules target their absolute instant. There is no catch-up: a missed
     * occurrence is never backfilled — the next *future* fire is always used.
     */
    private scheduleNextTick;
    /**
     * Arm a `setTimeout` for the entry's `nextRunAt`, clamping the delay to
     * {@link MAX_TIMER_MS} so a far-future fire (e.g. a yearly cron) doesn't
     * exceed Node's timer ceiling. If the timer wakes before the real fire
     * time — because the delay was clamped, or the wall clock jumped back — it
     * re-arms instead of firing. This keeps long and calendar schedules robust
     * to sleep and clock changes.
     */
    private armTimer;
    private runTick;
    /**
     * Send the entry's prompt and resolve when the matching `user.message`
     * lands. Correlation is by id via `source: schedule-<id>`, so two
     * scheduled entries with the same prompt text — or a manually-typed
     * prompt that looks identical — never collapse the no-overlap guarantee.
     *
     * Rejects if `Session.send` itself fails (e.g. validation error).
     * `runTick` swallows the rejection and reschedules anyway, so a transient
     * send failure won't kill the schedule.
     *
     * When the entry's `prompt` begins with `/` it is treated as a slash
     * command: the registry routes it through `host.invokeCommand` first and
     * uses the returned prompt/displayPrompt/mode for the actual send. A null
     * or thrown result skips the tick with a warning so the schedule survives
     * transient command failures.
     *
     * The listener is tracked on the `ScheduledEntry` so that
     * `cancelScheduled` can unsubscribe it if the entry is stopped while a
     * tick is in flight, preventing listener leaks.
     */
    private sendAndAwaitDelivery;
    private deliverPrompt;
}

/**
 * Narrow structural target the registry needs from the owning session. Lets
 * tests substitute a fake session without depending on the full Session class.
 */
declare interface ScheduleRegistryHost {
    emit(type: "session.schedule_created", data: ScheduleCreatedData_2): void;
    emit(type: "session.schedule_cancelled", data: {
        id: number;
    }): void;
    emit(type: "session.schedule_rearmed", data: {
        id: number;
        nextRunAt: number;
    }): void;
    /**
     * Dispatch a prompt onto the session. The registry only awaits delivery
     * via the `user.message` event listener, so the return value is unused
     * (left as `unknown` to accept both `Session.send` and any schema-shaped
     * wrapper).
     */
    send(options: SendParams): unknown;
    /**
     * Whether the session is currently processing its item queue. May be true
     * between turns while administering non-message items (e.g. a queued
     * command or model change) when no model turn is in flight.
     */
    isProcessingMessages?(): boolean;
    /**
     * Whether a model turn is currently in flight. A steering (`immediate`)
     * scheduled prompt delivered now rides along on that turn; when this is
     * false there is no active turn to drain it.
     */
    isAgentTurnActive?(): boolean;
    /**
     * Resolve a scheduled slash-command prompt into a concrete prompt. Called
     * once per tick when the entry's `prompt` begins with `/` (see
     * {@link parseLeadingCommand}). Returning `null` (or rejecting) means the
     * tick should be skipped without killing the schedule — typically because
     * the command returned a non-agent-prompt result (`text` / `completed` /
     * `select-subcommand`).
     *
     * Implementations should bypass any "agent turn is active" gate: the
     * registry handles delivery — steering a plain resolved prompt into an
     * in-flight run, or enqueuing a mode-bearing one (e.g. `/plan`) so it runs
     * as its own mode-aware turn — so the command's deferred delivery is fine
     * even when the user has an in-flight turn.
     */
    invokeCommand?(name: string, input: string): Promise<ResolvedScheduledPrompt | null>;
    on(type: "session.shutdown", listener: (event: ScheduleHostEventPayload<"session.shutdown">) => void): Unsubscribe;
    on(type: "user.message", listener: (event: ScheduleHostEventPayload<"user.message">) => void): Unsubscribe;
    on(type: "session.idle", listener: (event: ScheduleHostEventPayload<"session.idle">) => void): Unsubscribe;
    getEvents(): readonly SessionEvent[];
}

/** 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;
}

/**
 * Session metadata with its relevance score for display grouping.
 */
declare interface ScoredSessionMetadata<T extends SessionMetadata = SessionMetadata> {
    session: T;
    score: RelevanceScore;
}

/**
 * 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;
}

export declare type SdkCommandsChangedEvent = WireTypes.SdkCommandsChangedEvent;

/**
 * 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>>;

/**
 * Product label combining integrity and confidentiality dimensions.
 * Operations are component-wise.
 */
declare class SecurityLabel implements Lattice<SecurityLabel> {
    readonly integrity: IntegrityLabel;
    readonly confidentiality: ConfidentialityLabel;
    constructor(integrity: IntegrityLabel, confidentiality: ConfidentialityLabel);
    static default(): SecurityLabel;
    leq(other: SecurityLabel): boolean;
    join(other: SecurityLabel): SecurityLabel;
    meet(other: SecurityLabel): SecurityLabel;
    equals(other: SecurityLabel): boolean;
    toString(): string;
    /**
     * Like {@link toString} but redacts repo identities (see
     * {@link ConfidentialityLabel.toLogString}). Use this in logs to avoid
     * leaking private repo names into debug output.
     */
    toLogString(): string;
    toJSON(): {
        integrity: string;
        confidentiality: string[];
    };
    /**
     * Inverse of {@link toJSON}. Returns undefined for malformed input so
     * callers fail closed. Used to round-trip a full label through an in-process
     * seam (e.g. the subagent result's `ifc_full` metadata) without losing repo
     * compartments to the coarse wire form.
     */
    static fromJSON(value: unknown): SecurityLabel | undefined;
}

export declare type SelectionAttachment = WireTypes.SelectionAttachment;

/** 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_3[];
    /** 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 match one of three forms: the literal `system`, `command-<command-id>` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-<numeric-id>` for messages originating from a scheduled job. */
    source?: string;
}

/**
 * Public-facing parameters for the session `sendMessages` method, owned by the
 * Rust wire contract (`SendMessagesRequest`). The multi-message sibling of
 * {@link SendParams}: it carries an ordered list of per-message objects plus
 * turn-level options. Used as the parameter type on the impl method
 * `Session.sendMessagesForSchema`.
 */
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. */
    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?: AgentMode;
    /**
     * Source identifier for this message.
     * - `"system"`: runtime-generated notifications hidden from the timeline.
     * - `` `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`).
     */
    source?: "system" | `command-${string}` | `schedule-${number}`;
    /** Structured metadata for system notifications. Only used when source is "system". */
    notificationKind?: SystemNotificationKind;
    /** Revalidates and commits a deferred system notification when it is emitted. */
    notificationDelivery?: {
        isStillValid?: () => boolean;
        onDelivered: () => number | void;
    };
    /**
     * 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;
}

/**
 * Public-facing parameters for the session `send` method, owned by the Rust
 * wire contract (`SendRequest`). Mirrors the fields of the runtime's internal
 * `SendOptions` that are appropriate for SDK consumers; runtime-only fields
 * (`notificationKind`) are absent from the wire contract and remain available
 * to internal callers via the full `SendOptions` type. Used as the parameter
 * type on the impl method `Session.sendForSchema`.
 */
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_3[];
    /** 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 match one of three forms: the literal `system`, `command-<command-id>` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-<numeric-id>` for messages originating from a scheduled job. */
    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. */
    wait?: boolean;
}

/** Result of sending a user message */
declare interface SendResult {
    /** Unique identifier assigned to the message */
    messageId: string;
}

/** 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>;
    instructions: {
        discover(params: InstructionsDiscoverRequest): ServerInstructionSourceList | Promise<ServerInstructionSourceList>;
        getDiscoveryPaths(params: InstructionsGetDiscoveryPathsRequest): InstructionDiscoveryPathList | Promise<InstructionDiscoveryPathList>;
    };
    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: {
        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>;
    };
    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>;
        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>;
        getPersistedRemoteSteerable(params: SessionsGetPersistedRemoteSteerableRequest): SessionsGetPersistedRemoteSteerableResult | Promise<SessionsGetPersistedRemoteSteerableResult>;
        getRemoteControlStatus(): RemoteControlStatusResult | Promise<RemoteControlStatusResult>;
        getSizes(): SessionSizes | Promise<SessionSizes>;
        list(params?: SessionsListRequest): SessionList | Promise<SessionList>;
        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;
    /** 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;
};

/**
 * A single line in a service's server log.
 */
export declare type ServiceLogEntry = {
    /** 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;
}

/**
 * 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.
 */
export declare type ServiceTask = {
    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;
    /** 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[];
};

/** 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 every leaf in the schema and asserts that the resolved impl
 * member exists on `LocalSession.prototype`. 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.
 */
declare abstract class Session<SM extends SessionMetadata = SessionMetadata> {
    /**
     * 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 `name.set()` persists a rename for this session type. */
    get supportsRename(): boolean;
    protected subagentSettings?: UserSettings["subagents"];
    /**
     * Hook for subclasses to replace a session API namespace with an alternate
     * implementation. The default returns the local factory result unchanged;
     * `RemoteSession` overrides this to substitute a Proxy that routes calls
     * through Mission Control RPC for namespaces listed in
     * `REMOTE_API_NAMESPACES`.
     *
     * Called from this class's field initializers via virtual dispatch, so the
     * most-derived override decides whether to build the local factory at all.
     * Pass a thunk for `localFactory` so subclasses can skip building a local
     * implementation they don't need.
     *
     * Subclass overrides must not access subclass instance fields here: those
     * fields aren't initialised yet when the base class's field initializers
     * run. Lazy closures over `this` (resolved later, on method call) are fine.
     */
    protected resolveSessionApi<T>(_name: string, localFactory: () => T): T;
    readonly gitHubAuth: SessionGitHubAuthApi;
    readonly canvas: SessionCanvasRuntimeApi;
    readonly factory: SessionFactoryApi;
    /**
     * Durable open-canvas set, keyed by `instanceId`, rebuilt during replay from
     * the `session.canvas.recorded` / `session.canvas.removed` companion events.
     * Cold resume seeds these entries as stale and rehydrates URLs through providers.
     */
    private readonly durableOpenCanvases;
    readonly model: SessionModelApi;
    readonly mode: SessionModeApi;
    readonly name: SessionNameApi;
    readonly plan: SessionPlanApi;
    readonly workspaces: SessionWorkspaceApi;
    readonly instructions: SessionInstructionsApi;
    readonly fleet: SessionFleetApi;
    readonly agent: SessionAgentApi;
    readonly skills: SessionSkillsApi;
    readonly mcp: SessionMcpApi & {
        oauth: SessionMcpOauthApi;
        headers: SessionMcpHeadersApi;
        apps: SessionMcpAppsApi;
        resources: SessionMcpResourcesApi;
    };
    readonly plugins: SessionPluginsApi;
    readonly debug: SessionDebugApi;
    readonly provider: SessionProviderApi;
    readonly options: SessionOptionsApi;
    readonly lsp: SessionLspApi;
    readonly extensions: SessionExtensionsApi;
    readonly tasks: SessionTasksApi;
    readonly tools: SessionToolsApi;
    readonly commands: SessionCommandsApi;
    readonly completions: SessionCompletionsApi;
    readonly telemetry: SessionTelemetryApi;
    readonly ui: SessionUiApi;
    /**
     * Mutable location-permission bookkeeping shared between the permissions
     * API factory and the session-open persisted-dir seeding in
     * `ensurePermissionService`. Declared before `permissions` because that
     * field's initializer reads it.
     */
    readonly permissionsRuntimeState: SessionPermissionsRuntimeState;
    readonly permissions: SessionPermissionsApi;
    readonly log: SessionLogApi["log"];
    readonly metadata: SessionMetadataApi;
    readonly settings: SessionSettingsApi;
    readonly history: SessionHistoryApi;
    readonly queue: SessionQueueApi;
    readonly eventLog: SessionEventsApi;
    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.
     */
    readonly scheduleRegistry: ScheduleRegistry;
    private shellNotifier;
    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;
    protected permissionServiceOptions: {
        approveAllToolPermissionRequests: boolean;
        approveAllReadPermissionRequests?: boolean;
        autoApprovalPermissionRequests?: boolean;
        rules: {
            approved: ReadonlyArray<Rule>;
            denied: ReadonlyArray<Rule>;
        };
        pathManager?: PathManager;
        urlManager?: UrlManager;
        managedPermissions?: ManagedPermissionsSlice;
    };
    private allowAllPermissionOverride;
    /**
     * Optional model id to use for the `auto`-mode auto-approval safety judge.
     * Set when auto approval is enabled with an explicit model (e.g. the CLI
     * passing a dedicated, capable safety-review model) so the judge runs on that model
     * instead of the session's active one. `undefined` means "use the session's
     * active model". Only read by sessions that run the judge locally.
     */
    protected autoApprovalModel: string | undefined;
    /** Whether the session may emit permission.requested events and await a user response. */
    protected permissionRequestEventsEnabled: boolean;
    /**
     * 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;
    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;
    }): void;
    /**
     * Forward the managed `permissions` slice to the live permission service and
     * any in-flight creation. The slice is also stored in
     * `permissionServiceOptions.managedPermissions` so a lazily created service
     * picks it up at construction. The engine is the authoritative enforcer; the
     * synchronous UX mirror is derived separately from the same pure policy eval.
     */
    private applyManagedPolicyToPermissionService;
    /** The effective enterprise managed settings in force for this session, if any. */
    getManagedSettings(): ManagedSettings | undefined;
    /**
     * Public entry point for a host (e.g. the CLI) that resolves managed settings
     * outside the session's own self-fetch path to push the enterprise MCP
     * allow/deny layers into this session. The CLI applies managed settings via
     * its own app-level flow (bypass/telemetry/model) and does not opt into
     * {@link SessionOptions.enableManagedSettings}, so without this the composed
     * MCP policy would stay empty and the allow/deny lists would not be enforced.
     * Delegates to {@link updateManagedMcpPolicyLayers} (same fail-closed and
     * live-host propagation semantics as the self-fetch path).
     */
    applyManagedMcpPolicyLayers(serverResponse: ManagedSettings | undefined, deviceResponse: ManagedSettings | undefined, serverFetchFailed: boolean, deviceLoadFailed: boolean): void;
    /**
     * Declare that the host (CLI) will apply the enterprise-managed MCP policy
     * out-of-band via {@link applyManagedMcpPolicyLayers}, so MCP host creation
     * must block until it has. This closes the exposure window in which a denied
     * server could start and surface tools while the managed-settings fetch is
     * still in flight. The caller MUST guarantee {@link applyManagedMcpPolicyLayers}
     * is eventually invoked (with the resolved layers, or fail-closed on failure),
     * or the first MCP-backed turn would block indefinitely. Idempotent; a no-op
     * once the policy has been applied or the MCP host already exists.
     */
    expectManagedMcpPolicy(): void;
    /**
     * Update the retained managed-settings layers from a resolution result and
     * push the composed MCP allow/deny policy to a live MCP host, if one exists.
     *
     * Fail-closed for MCP on BOTH layers: when a server fetch failed
     * (`serverFetchFailed`) or device discovery threw (`deviceLoadFailed`), the
     * respective previously-known layer is preserved rather than dropped, so a
     * transient failure never lifts an enterprise MCP restriction (mirrors the
     * bypass-permissions fail-closed behavior). A device layer is only cleared on
     * a *successful* discovery that returns no policy (genuine removal).
     */
    protected updateManagedMcpPolicyLayers(serverResponse: ManagedSettings | undefined, deviceResponse: ManagedSettings | undefined, serverFetchFailed: boolean, deviceLoadFailed: boolean): void;
    /**
     * Immediately restrict MCP to a fail-closed (deny-all non-default) state
     * while a *new* managed-settings identity's policy is being fetched, then
     * relax it once the policy resolves (via {@link updateManagedMcpPolicyLayers}).
     *
     * Analogous to the immediate bypass-permissions lock at the self-fetch
     * bootstrap: without this, an account switch from an unrestricted account to
     * a governed one would leave the previous account's MCP servers connected and
     * callable throughout the fetch window. Pushes the interim policy to any live
     * host so already-running servers are torn down at once.
     */
    protected beginInterimManagedMcpFailClosed(): void;
    /**
     * Push the currently-composed managed MCP policy (or the interim fail-closed
     * policy) to the live primary host and every cached subagent host.
     * Fire-and-forget: the enforcement is async (it may stop servers) but callers
     * are synchronous.
     */
    private pushComposedManagedMcpPolicyToHosts;
    /** Compose the enterprise MCP allow/deny policy from the retained layers. */
    protected composeManagedMcpPolicy(): ManagedMcpPolicy;
    /**
     * The composed enterprise MCP allow/deny policy in the {@link McpHost} option
     * shape (empty lists normalized to `undefined`). Shared by every MCP host
     * construction — the primary session host and agent-scoped subagent hosts —
     * so custom-agent MCP servers are governed identically.
     */
    protected composedManagedMcpHostOptions(): {
        managedAllowedMcpServerLists?: ManagedMcpServerMatcher[][];
        managedDeniedMcpServers?: ManagedMcpServerMatcher[];
    };
    /**
     * Names of trusted first-party MCP servers that are exempt from the enterprise
     * managed allow/deny policy, derived from provenance rather than a forgeable
     * config field or reserved name.
     *
     * A server is vouched only when it carries the `source: "builtin"` marker,
     * which trusted first-party assembly sets (e.g. computer-use) and which the
     * Rust config parser (`base_server_config`) strips from ALL user/workspace
     * `.mcp.json` config. So a governed end user cannot get `source: "builtin"`
     * onto a server, and because this set is snapshotted from the host's initial
     * config, a later dynamic `startServer` (or a server named after a reserved
     * built-in) is never exempt.
     */
    protected trustedDefaultServerNames(mcpServers: Record<string, MCPServerConfig> | undefined): string[];
    /** Whether enterprise managed settings disable bypass-permissions mode for this session. */
    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;
    /**
     * (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}.
     */
    private refreshManagedSettings;
    /**
     * Emit the SDK-consumable `session.managed_settings_resolved` event from a
     * resolved {@link ManagedSettingsResolvedInfo}. Fired after managed policy is
     * (re)applied so clients can render what is enterprise-managed.
     *
     * Emitted as an ephemeral (non-persisted) live snapshot: at session start
     * managed settings resolve *before* `session.start` is emitted, so persisting
     * this event would put a non-`session.start` event first in the log and make
     * the session unresumable. Subscribers still receive it live; consumers that
     * need a durable/session-independent value use the `getManagedSettings()` pull.
     */
    private emitManagedSettingsResolved;
    /**
     * 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?: AllowAllSource): Promise<void>;
    setAutoApprovalPermissions(enabled: boolean, model?: string): Promise<void>;
    /**
     * 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`,
     * `sessionPermissionsApi.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;
    /** 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 sessionPluginsApi}.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>;
    /** Flush any pending writes to disk. No-op if no flush callback is registered. */
    flushPendingWrites(options?: {
        force?: boolean;
    }): Promise<void>;
    /** Backing field for currentMode getter/setter */
    private _currentMode;
    /** 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;
    isPlanModeWriteGateActive(): boolean;
    /** Tracks the current user-message turn number for turn-scoped session state. */
    protected currentTurn: number;
    /** Dedupes root assistant.intent emissions within a single turn. */
    protected lastEmittedIntent: {
        intent: string;
        turn: number;
    } | undefined;
    readonly sessionId: 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.
     */
    readonly detachedFromSpawningParentSessionId?: string;
    readonly startTime: Date;
    readonly modifiedTime: Date;
    readonly summary?: string;
    /** Friendly name provided at session creation via `--name`, threaded to workspace init. */
    protected _initialName?: string;
    /** 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 resolvedFeatureFlagService(): IFeatureFlagService;
    /** Whether experimental mode is enabled for this session */
    isExperimentalMode: 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 */
    alreadyInUse: boolean;
    /** Whether the main agent turn is currently active. */
    isAgentTurnActive(): 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;
    /**
     * Get the per-session schedule registry, lazily creating it on first
     * access. Used by `/every` and the `manage_schedule` tool to share a
     * single set of timers per session. The registry auto-disposes on
     * `session.shutdown`.
     */
    getScheduleRegistry(): ScheduleRegistry;
    /**
     * Get the per-session autopilot objective registry, lazily creating it on first access.
     * Used by `/autopilot <objective>` and objective-aware autopilot continuation.
     */
    getAutopilotObjectiveRegistry(): AutopilotObjectiveRegistry;
    /** 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;
    /**
     * 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[];
    /** Diagnostics (warnings/errors) emitted during the most recent skill load. */
    getLastSkillLoadDiagnostics(): {
        warnings: string[];
        errors: string[];
    };
    /**
     * 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>;
    /** True iff plugins were configured via marketplace, --plugin-dir, or pluginDirectories. */
    private hasInstalledPlugins;
    /**
     * `enableConfigDiscovery` and explicit plugins both unlock the custom-agent discovery
     * path. Centralizing the rule keeps the three gate sites (constructor, ensureAgentsLoaded,
     * reloadCustomAgents) consistent and removes the double-negative at each call site.
     */
    private shouldDiscoverCustomAgents;
    /**
     * 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;
    protected resolveDefaultMcpPolicyOptions(config?: {
        mcp3pEnabled?: boolean;
        configFilter?: McpConfigFilter;
    }): Promise<{
        mcp3pEnabled: boolean;
        configFilter?: McpConfigFilter;
        managedAllowedMcpServerLists?: ManagedMcpServerMatcher[][];
        managedDeniedMcpServers?: ManagedMcpServerMatcher[];
    }>;
    protected resolveActiveGitHubTokenForMcpEnv(): Promise<string | undefined>;
    /**
     * Ensure MCP servers have been initialized. If the MCP host hasn't been created yet
     * (i.e., no message has been sent), this creates and starts it so that
     * session.mcp.list returns accurate results without waiting for the first message.
     */
    ensureMcpLoaded(): 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;
    /** Get a summary of MCP server states for the current session. */
    getMcpServerSummaries(): Array<{
        name: string;
        status: ServerConnectionStatus;
        source?: MCPServersConfig["mcpServers"][string]["source"];
        error?: string;
        transport?: "stdio" | "http" | "sse" | "memory";
        pluginName?: string;
        pluginVersion?: string;
    }>;
    /** 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 and dynamic headers refresh always install host callbacks. Listener
     * presence is re-checked when a request arrives, so SDK clients can call
     * `eventLog.registerInterest` after `session.create` and still handle later
     * sampling / headers-refresh traffic (same pattern as OAuth).
     *
     * OAuth always uses `buildMcpOAuthHandler()`: typed `mcp.oauth_required`
     * listeners get interactive host delegation; otherwise the handler tries
     * non-interactive cached-token auth and leaves servers in `needs-auth`
     * when no usable credential exists.
     */
    protected getMcpEventHandlers(): Pick<McpHostOptions, "elicitationHandler" | "samplingHandler" | "onOAuthRequired" | "onHeadersRefresh" | "mcpAppsEnabled">;
    /**
     * Always-on MCP sampling host callback. Presence is re-checked per request
     * so post-create `eventLog.registerInterest("sampling.requested")` still
     * works for later requests. Without a consumer, cancel.
     */
    protected buildMcpSamplingHandler(): NonNullable<McpHostOptions["samplingHandler"]>;
    /**
     * 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;
    /**
     * Host context exposed to MCP App guests on `ui/initialize` (SEP-1865).
     * SDK consumers can set this to advertise theme, locale, or other
     * host-specific metadata to the guest UI; renderers read it via
     * `mcp.apps.getHostContext` when building the `ui/initialize` response.
     */
    private mcpAppsHostContext;
    /** Replace the host context returned to MCP App guests on `ui/initialize`. */
    setMcpAppsHostContext(context: HostContext): void;
    /** Read the current host context. */
    getMcpAppsHostContext(): HostContext;
    /**
     * 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"]>;
    /**
     * List MCP App–visible tools from a connected server (SEP-1865).
     *
     * Returns tools whose `_meta.ui.visibility` is unset (default `["model","app"]`)
     * or includes `"app"`. Use this to populate the tool list a rendered MCP App
     * is allowed to call back into. Requires the `mcp-apps` session capability.
     *
     * @param serverName - MCP server hosting the tools.
     * @param options.originServerName - **Required.** Name of the server whose
     *   `ui://` view issued the request. Per SEP-1865 ("callable by the app from
     *   this server only"), an app MUST only list tools on its own server. The
     *   call is rejected when `originServerName !== serverName`, and rejected
     *   outright when this field is missing — the host MUST pass it for every
     *   request that originates from an iframe view.
     */
    listMcpAppTools(serverName: string, options: {
        originServerName: string;
    }): Promise<{
        tools: unknown[];
    }>;
    /**
     * Call an MCP tool from an MCP App view (SEP-1865).
     *
     * Enforces `_meta.ui.visibility`: tools that explicitly exclude `"app"` are
     * rejected. Spec-default visibility is `["model","app"]`, so tools without
     * an explicit visibility array are callable from the app side. This is the
     * security boundary that prevents a rendered iframe from invoking
     * model-only tools. Requires the `mcp-apps` session capability.
     *
     * @param options.originServerName - **Required.** Name of the server whose
     *   `ui://` view issued the request. Per SEP-1865 ("callable by the app from
     *   this server only"), an app MUST only call tools on its own server. The
     *   call is rejected when `originServerName !== serverName`, and rejected
     *   outright when this field is missing — the host MUST pass it for every
     *   request that originates from an iframe view.
     */
    callMcpAppTool(serverName: string, toolName: string, args: Record<string, unknown> | undefined, options: {
        originServerName: string;
    }): Promise<unknown>;
    private callMcpAppToolWithOAuthRetry;
    /**
     * Fetch an MCP resource from a connected server. Wraps the underlying
     * `Client.readResource` so SDK consumers can pull resources on demand.
     * Errors are surfaced via {@link formatError}.
     */
    readMcpResource(serverName: string, uri: string): Promise<{
        contents: Array<{
            uri: string;
            mimeType?: string;
            text?: string;
            blob?: string;
            _meta?: Record<string, unknown>;
        }>;
    }>;
    /**
     * 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;
    }>;
    /**
     * Diagnose MCP Apps wiring for a specific server. Used by SDK consumers
     * to figure out why interactive UIs aren't appearing — distinguishes
     * "runtime didn't advertise the extension" from "server didn't include
     * `_meta.ui`" from "session lacks the capability".
     *
     * Unlike the rest of the MCP-Apps API surface, this method does NOT
     * require the `mcp-apps` session capability: its whole purpose is to
     * surface the capability state via `sessionHasMcpApps`, so guarding on
     * the capability would make the most informative failure case
     * unreachable. Lazy-loads the MCP host so it works immediately after
     * `session.create` without needing a user message first; when the host
     * cannot be initialized (e.g. no MCP servers configured) the method
     * returns `server.connected: false` rather than throwing.
     */
    diagnoseMcpApps(serverName: string): Promise<{
        capability: {
            sessionHasMcpApps: boolean;
            featureFlagEnabled: boolean;
            advertised: boolean;
        };
        server: {
            connected: boolean;
            toolCount: number;
            toolsWithUiMeta: number;
            sampleToolNames: string[];
        };
    }>;
    /**
     * 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: {
        mcpServers: Record<string, MCPServerConfig>;
        disabledServers?: string[];
        enabledServers?: string[];
        mcp3pEnabled?: boolean;
        configFilter?: McpConfigFilter;
        statusCallback?: ServerStatusCallback;
        githubMcpToolOptions?: Required<GitHubMcpConfigOptions>;
        /** 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;
    }): Promise<StartServersResult>;
    /**
     * 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;
    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 events;
    private lastEventId;
    protected _chatMessages: ChatCompletionMessageParam[];
    protected _systemContextMessages: ChatCompletionMessageParam[];
    protected _selectedModel: string | undefined;
    protected modelSelectionVersion: number;
    private lastEffectiveModelForHistoryRewrite;
    protected originalUserMessages: string[];
    /** Skills invoked during this session, for preservation across compaction */
    protected invokedSkills: InvokedSkillInfo[];
    /**
     * Per-tool-call message source map populated when assistant.message events
     * are processed (carrying tool_calls) and consumed when the corresponding
     * tool.execution_complete pushes a `role: "tool"` message. Used by the
     * `/usage` attribution path to recognize MCP tool results and sub-agent
     * task results without re-parsing tool arguments.
     */
    private _messageSourceByToolCallId;
    /**
     * Maps toolCallId -> tool name, populated when assistant.message events are
     * processed (carrying tool_calls) and read back when the corresponding
     * tool.execution_complete rebuilds its `role: "tool"` message (the completion
     * event does not carry the tool name). Replaces an O(N) scan of the entire
     * chat history per tool result with an O(1) lookup — the scan made resuming
     * tool-heavy sessions O(N²). Model changes that remap tool-call ids update
     * this map alongside the history (see {@link rewriteChatHistoryForModel}).
     */
    protected _toolCallNameById: Map<string, string>;
    /**
     * True only while {@link Session.fromEvents} is replaying persisted events to
     * rebuild state. Used to skip per-event work that is redundant during a bulk
     * replay and only needs to run once at the end (e.g. the tool-call-result
     * repair, whose per-event O(N) rebuild made resume O(N²)).
     */
    private _replayingEvents;
    /**
     * Set of tool-call ids that currently have a `role: "tool"` result message in
     * {@link _chatMessages}. Allocated only during a {@link Session.fromEvents}
     * replay and used to answer the "do we already have a result for this call?"
     * duplicate check in O(1) instead of scanning the whole (growing) history per
     * `tool.execution_complete` — that scan was the last O(N²) term in the replay.
     * Maintained incrementally on each tool-result push and rebuilt in full via
     * {@link rebuildReplayToolResultIndex} whenever `_chatMessages` is replaced
     * wholesale during replay (orphan completion, compaction, boundary repair).
     */
    private _replayToolResultCallIds;
    /**
     * Maps toolCallId -> command string for user-requested shell commands.
     * Populated from `tool.user_requested` events so that when `tool.execution_complete`
     * fires, we can inject a user message with the command and its output.
     */
    private _userRequestedCommandByToolCallId;
    /**
     * Maps skill name -> plugin name, populated from `skill.invoked` events so
     * the subsequent skill-injected `user.message` (which only carries a
     * `skill-<name>` source string) can recover the plugin attribution.
     */
    private _skillPluginByName;
    private compactionCheckpointLength;
    private compactionCheckpointMessageRef;
    private compactionCheckpointEventIndex;
    protected staticContextWarningEmitted: boolean;
    private eventProcessingQueue;
    private processUserRequestedShellContextPartForLlm;
    private eventHandlers;
    private wildcardEventHandlers;
    private usageMetricsTracker;
    private modelCacheCheckpointPending;
    private readonly binaryAssetRegistry;
    protected integrationId: string;
    protected availableTools?: string[];
    /**
     * The explicit tool filter policy to propagate to nested subagents.
     * `availableTools` may later be replaced with model-specific effective
     * tool names by a subagent executor.
     */
    protected subagentAvailableTools?: string[];
    protected excludedTools?: string[];
    protected toolFilterPrecedence?: ToolFilterPrecedence;
    protected defaultAgentExcludedTools?: string[];
    /** Local policy plus a parent link keeps inheritance downward-only. */
    private builtinAgentPolicyState;
    private observedBuiltinAgentPolicyRevision;
    protected get includedBuiltinAgents(): string[] | undefined;
    protected set includedBuiltinAgents(value: string[] | undefined);
    protected get excludedBuiltinAgents(): string[] | undefined;
    protected set excludedBuiltinAgents(value: string[] | undefined);
    protected enableScriptSafety?: boolean;
    protected suppressToolChangedNotice?: boolean;
    protected parentWorkspacePath?: string;
    protected shellInitProfile?: ShellInitProfile;
    protected shellProcessFlags?: string[];
    protected sandboxConfig?: SandboxConfig_2;
    /** Cached ShellConfig, invalidated when options change. */
    protected resolvedShellConfig?: ShellConfig;
    protected logInteractiveShells?: boolean;
    protected mcpServers?: Record<string, MCPServerConfig>;
    protected mcpHost?: McpHost;
    protected allowAllMcpServerInstructions: boolean;
    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>>;
    protected turnActive: boolean;
    /** 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 envValueMode?: EnvValueMode;
    protected pendingGitHubMcpServers: Map<string, MCPRemoteServerConfig>;
    protected hasUserNamedGitHubServer: boolean;
    protected hasUserConfiguredGitHubServer: boolean;
    protected lastGitHubAuthInfo: AuthInfo | null;
    protected githubMcpToken: string | undefined;
    protected githubMcpToolOptions?: Required<GitHubMcpConfigOptions>;
    protected selectedAgentMcpServerNames: Set<string>;
    protected lastInitializedAgentMcpServers?: Record<string, MCPServerConfig>;
    protected nativeHookProcessor?: NativeHookProcessor;
    protected ownsNativeHookSession: boolean;
    protected customAgents?: SweCustomAgent[];
    /**
     * 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;
    /** Custom agents explicitly supplied via session options; these are not reloadable discovery cache entries. */
    protected providedCustomAgents?: SweCustomAgent[];
    protected selectedCustomAgent?: SweCustomAgent;
    protected customAgentsLocalOnly: boolean;
    /** When true, skip injecting the selected custom agent's prompt into the user message. */
    protected suppressCustomAgentPrompt: boolean;
    protected instructionDirectories?: string[];
    protected organizationCustomInstructions?: string;
    protected skipCustomInstructions: boolean;
    protected skipEmbeddingRetrieval: boolean;
    protected embeddingCacheStorage: "persistent" | "in-memory";
    protected dynamicInstructionState: DynamicInstructionState;
    protected disabledInstructionSources?: ReadonlySet<string>;
    protected coauthorEnabled?: boolean;
    protected systemMessageConfig?: SystemMessageConfig;
    protected sectionTransformFn?: SectionTransformFn;
    protected workingDir: string;
    /**
     * 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;
    protected featureFlags?: FeatureFlags;
    /**
     * Base (pre-experiment) values of the two dynamic-retrieval flags, captured
     * whenever `featureFlags` is set from options. {@link applyDynamicRetrievalArm}
     * 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 baseDynamicRetrieval: boolean;
    protected baseDynamicRetrievalBlackbird: boolean;
    protected featureFlagService: IFeatureFlagService;
    private ownedFeatureFlagService?;
    protected coreServices: CoreServices;
    protected interactionType: "conversation-agent" | "conversation-subagent";
    protected subAgentDepth: number;
    protected readonly parentPlanModeWriteGateActive?: () => boolean;
    /**
     * Stable child trajectory 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 stable trajectory id on hook payloads via
     * `this.stableAgentId`, preserving the existing hook contract
     * after the McpHost/CAPI/OAuth consumers were moved to read the root
     * `sessionId` directly.
     */
    protected readonly agentId?: string;
    protected readonly parentAgentId?: string;
    /** Stable trajectory identity for this session: the child id, or the root session id. */
    protected get stableAgentId(): string;
    protected readonly taskRegistryAgentId?: string;
    protected ifcEngine?: IFCEngine;
    /**
     * FIDES IFC context label inherited from the parent at subagent-spawn time.
     * The delegating prompt is an ingress into the child carrying the parent's
     * taint, so the child engine is seeded with this label on lazy-init instead
     * of starting at the lattice default. Set by {@link createSubagentSession};
     * undefined for top-level sessions (which start at the default).
     */
    protected inheritedIfcLabel?: SecurityLabel;
    /**
     * The current FIDES IFC context label, or undefined when the engine has not
     * been initialised (FIDES off, or no `send()` yet). Public so a parent can
     * read a finished subagent's ending label and join it into its own context.
     */
    getIfcContextLabel(): SecurityLabel | undefined;
    /**
     * Emits the `parent_to_child_seed` propagation event when a subagent is
     * spawned, recording the label crossing into the child. `taintCrossed` is
     * false when the parent was at the lattice default (a no-op seed). A no-op
     * when FIDES is off (no parent label). Wrapped so telemetry can't break spawn.
     */
    private emitSubagentSeedTelemetry;
    protected skillDirectories?: string[];
    protected enableConfigDiscovery: boolean;
    protected enableOnDemandInstructionDiscovery: boolean;
    /**
     * Per-session cap (decoded bytes) for inline model-facing binary tool
     * results persisted in session events. Undefined falls back to
     * {@link DEFAULT_MAX_INLINE_BINARY_BYTES}. Resolved via
     * {@link getMaxInlineBinaryBytes}.
     */
    protected maxInlineBinaryBytes: number | undefined;
    private _hostGitOperationsEnabled;
    protected enableSkills?: boolean;
    protected disabledSkills?: Set<string>;
    protected disabledMcpServers?: string[];
    protected _loadedSkills: Skill_2[];
    protected _skillsLoaded: boolean;
    protected _skillsLoadingPromise?: Promise<void>;
    /** Diagnostics from the most recent skill load (mutated alongside `_loadedSkills`). */
    private _lastSkillLoadDiagnostics;
    /** Bumped by clearLoadedSkills so in-flight loads with a stale generation discard their results. */
    private _skillsGeneration;
    protected _agentsLoadingPromise?: Promise<void>;
    private _reloadAvailableModels?;
    protected _mcpLoadingPromise?: 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>;
    protected installedPlugins?: InstalledPlugin[];
    protected _pluginInstructionSourcesPromise?: Promise<InstructionSource_2[]>;
    protected askUserDisabled?: boolean;
    protected onExitPlanMode?: (request: ExitPlanModeRequest) => Promise<ExitPlanModeResponse>;
    private _directAutoModeSwitchHandlerCount;
    private _autopilotObjectiveRegistry?;
    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;
    /** Consecutive agentStop-hook `block` continuations in the current streak (see MAX_CONSECUTIVE_AGENT_STOP_BLOCKS). */
    protected consecutiveAgentStopBlocks: number;
    protected extensionController?: ExtensionController;
    /**
     * Whether the `manage_schedule` tool is exposed to the agent. Mirrors
     * {@link SessionOptions.manageScheduleEnabled}. The schedule registry
     * itself is always present so schema callers can list/add/stop entries
     * regardless of this flag; this field only gates tool exposure.
     */
    protected manageScheduleEnabled: boolean;
    protected agentContext?: AgentContext;
    protected sessionTelemetry?: DisposableTelemetrySender;
    protected userMessageSentimentTelemetry?: UserMessageSentimentTelemetry;
    protected runningInInteractiveMode?: boolean;
    protected sessionCapabilities: Set<SessionCapability_2>;
    protected additionalContentExclusionPolicies?: ContentExclusionApiResponse[];
    /** Handler that delegates permission requests to a parent session. */
    protected permissionRequestHandler?: (request: PermissionRequest_2) => Promise<PermissionRequestResult_2>;
    /** Content exclusion service auto-created by Session when auth and feature flags are available. */
    protected contentExclusionService?: ContentExclusionService;
    /** Returns the content exclusion service, or undefined if not yet initialized. */
    getContentExclusionService(): ContentExclusionService | undefined;
    /**
     * Sets (or clears) this session's content exclusion service.
     *
     * The service owns a native runtime handle that must be released deterministically,
     * so holders are tracked with retain/dispose refcounting: the creator owns the
     * service (`ownsService = true`, refcount starts at 1) and subagents that inherit it
     * borrow it (`ownsService = false`, bumping the refcount via `retain()`). Replacing or
     * clearing the service releases this holder's reference; the underlying handle is only
     * disposed once the last holder releases it.
     *
     * Note: a replaced/cleared service is deliberately NOT invalidated. Subagents that
     * borrowed it keep using their snapshot (with rules intact) even after the parent
     * reconfigures and creates a fresh service — preserving the original shared-reference
     * semantics rather than poisoning still-live borrowers.
     */
    protected setContentExclusionService(service: ContentExclusionService | undefined, ownsService: boolean): void;
    protected trajectoryFile?: string;
    protected eventsLogDirectory?: string;
    protected transcriptPath?: string;
    protected hydrateIfcEngineFromPersistedToolEvents(ifcProjector: IFCStateProjector): Promise<void>;
    /**
     * Recomputes the IFC context label from the events that survive a rewind
     * (`/undo` / `/rewind`). Re-running ingress alone only ever joins the label
     * upward, so the engine is first reset to its FLOOR and then re-derived from
     * exactly the retained tool reads. The result is the least-upper-bound of the
     * surviving reads (joined onto the floor), which is always ⊑ the pre-rewind
     * label — a rewind only lowers the label as tainted reads leave the context,
     * never raises it.
     *
     * SECURITY: the floor is the inherited spawn-seed label, NOT the bare lattice
     * default. A subagent's delegating prompt carried the parent's taint into the
     * child as an ingress that is the child's ENTRY CONDITION — it is not a tool
     * read in the retained log, so no `/undo` can ever remove it (you cannot
     * rewind before the spawn prompt). Flooring at the bare default would silently
     * drop that inherited taint and UNDER-RESTRICT the child: e.g. parent reads a
     * private repo → spawns child → child `/undo` → child collapses to
     * (trusted, public) and can now write the parent's private bytes to a public
     * sink with no prompt. Flooring at `inheritedIfcLabel` mirrors the lazy-init
     * seed (`new IFCEngine(logger, this.inheritedIfcLabel, …)`), so the two places
     * that establish the engine's base label agree. Top-level sessions have no
     * inherited label and so floor at the lattice default (unchanged behavior).
     */
    protected rewindIfcEngineToPersistedToolEvents(ifcProjector: IFCStateProjector): 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;
    protected authInfo?: AuthInfo;
    protected copilotUrl?: string;
    /**
     * Effective enterprise managed settings applied to this session, or
     * `undefined` when no managed policy is in force. Set via
     * {@link applyManagedSettings} at bootstrap from the self-fetched server
     * policy and/or device MDM.
     */
    protected effectiveManagedSettings?: ManagedSettings;
    /**
     * The last-known-good managed-settings layers (raw server + device
     * responses) used to compose the enterprise MCP allow/deny policy across
     * sources. Retained separately from {@link effectiveManagedSettings} (which
     * resolves the winner wholesale) so allowlist-intersection / deny-union
     * composition can see BOTH layers, and so a failed server fetch preserves the
     * previously-known server layer rather than lifting an MCP restriction.
     */
    protected managedSettingsLayers?: {
        serverResponse?: ManagedSettings;
        deviceResponse?: ManagedSettings;
    };
    /**
     * Interim account-switch lock for the MCP allow/deny policy: set the instant
     * a new managed-settings identity begins its self-fetch, forcing a
     * deny-all-non-default policy until the new account's policy resolves, then
     * cleared by {@link updateManagedMcpPolicyLayers}. Mirrors the immediate
     * bypass-permissions fail-closed lock so a switch to a governed account can't
     * leave the previous account's MCP servers connected during the fetch window.
     */
    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;
    /**
     * Account identity (`host\0login`) that the most recent self-fetch was
     * triggered for. Dedupes repeat triggers and detects account switches.
     */
    private managedSettingsFetchIdentity?;
    /** In-flight (or last) self-fetch promise, awaited by bootstrap when auth is present at create. */
    private managedSettingsIngestPromise?;
    /**
     * Gate that blocks MCP host creation until the host (CLI) has applied the
     * enterprise-managed MCP allow/deny policy at least once (or released it
     * fail-closed). Armed only when the host declares it will resolve managed
     * settings out-of-band via {@link expectManagedMcpPolicy} (the CLI does not
     * opt into {@link SessionOptions.enableManagedSettings}, so the self-fetch
     * `managedSettingsIngestPromise` never gates it). Resolved by
     * {@link applyManagedMcpPolicyLayers}. Without this, the MCP host could start
     * and briefly expose a denied server during the managed-settings fetch
     * window before the policy is applied. `undefined` once resolved.
     */
    private managedMcpPolicyGate?;
    /** True once the managed MCP policy has been applied (or the gate released). */
    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;
    protected byokProvider?: ProviderConfig;
    /**
     * BYOK provider registry (additive to CAPI auth), built once in the constructor
     * from `options.providers`. Keyed by provider name. Coexists with CAPI — it does
     * NOT bypass CAPI auth the way legacy `byokProvider` does. Mutually exclusive with
     * legacy `byokProvider` (validated at construction).
     */
    protected byokProviders: Map<string, NamedProviderConfig_2>;
    /** BYOK model registry, keyed by the provider-qualified selection id (`provider/id`). */
    protected byokModels: Map<string, ProviderModelConfig_2>;
    /** Synthesized {@link Model} metadata per provider-qualified selection id (`billing.multiplier = 0`). */
    protected byokModelMetadata: Map<string, Model>;
    /** Auto-mode session manager; provided by `coreServices.autoModeManager` and used to resolve the virtual `"auto"` model selection. */
    protected autoModeManager: AutoModeSessionManager;
    /**
     * A dedicated auto-mode session token minted for this session as a
     * complementary-strategy subagent (e.g. rubber-duck), paired with a specific
     * model. Set by {@link createSubagentSession} from
     * {@link SubagentSessionOptions.autoModeSession}. When the resolved model
     * matches `pairedModel`, {@link resolveAndValidateModel} attaches this token
     * so the child forwards its own `Copilot-Session-Token` for billing.
     */
    protected subagentAutoModeSession?: AutoModeSession;
    protected modelCapabilitiesOverrides?: ModelCapabilitiesOverride_2;
    protected contextTier?: ContextTier_3;
    protected enableCitations?: boolean;
    protected sessionLimits?: SessionLimitsConfig_3;
    protected reasoningEffort?: ReasoningEffort;
    protected reasoningSummary?: ReasoningSummary_3;
    protected verbosity?: Verbosity_3;
    private hasProcessedInitialOptions;
    protected enableStreaming: boolean;
    protected continueOnAutoMode: boolean;
    protected continueOnAutoModeSettingsLoaded: boolean;
    protected handoffContext?: string;
    protected externalToolDefinitions?: ExternalToolDefinition[];
    /** Bumped when externalToolDefinitions changes, used by refreshTools to detect mid-turn changes */
    protected externalToolsVersion: number;
    /** SDK-supplied configuration for the runtime's built-in tool-search behavior.  */
    protected toolSearchOverride?: SessionToolSearchOptions;
    /**
     * Tool-search override supplied through `externalToolDefinitions` (a definition
     * named `tool_search_tool` with `overridesBuiltInTool`). Hoisted out of
     * the external tool list at ingestion so both override sources are handled
     * uniformly and the rest of the pipeline never special-cases it.
     */
    protected toolSearchOverrideFromExternal?: ExternalToolDefinition;
    /** Bumped on every MCP `tools/list_changed` notification so refreshTools can detect mid-turn changes (#7432) */
    protected mcpToolsVersion: number;
    protected clientName?: string;
    protected clientKind?: SessionClientKind;
    protected largeOutputConfig?: LargeToolOutputConfig;
    protected runtimeSettings?: RuntimeSettings;
    private settingsHandle?;
    protected configDir?: string;
    protected repositoryName?: string;
    protected workspaceContext?: WorkspaceContextInfo;
    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: ShellContextHolder<InteractiveShellToolContext>;
    /** True when shellContext is inherited from a parent session (subagent). Prevents dispose from killing shared shells. */
    protected inheritedShellContext: boolean;
    /** True when sessionFs is inherited from a parent session (subagent). Prevents dispose from closing shared database. */
    protected inheritedSessionFs: boolean;
    /** Inherited sendInboxPublisher for sidekick child sessions. */
    protected sendInboxPublisher?: SendInboxPublisher;
    /** Parent agent task ID for CAPI X-Parent-Agent-Id header. */
    protected parentAgentTaskId?: 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).
     */
    notifySubagentComplete?: () => void;
    protected getSessionShellContext(): InteractiveShellToolContext | undefined;
    protected activeShellContext(): InteractiveShellToolContext | undefined;
    private _currentSystemMessageContent?;
    private _currentSystemMessageFlat?;
    private _currentCustomInstructionsMessage?;
    private _currentToolMetadata?;
    protected currentNonExternalToolMetadata?: ToolMetadata[];
    protected currentTools?: Tool[];
    protected currentToolNamesForChangeNotice?: string[];
    /** Generic client-search tools activated during this persisted session. */
    protected readonly genericClientDiscoveredToolNames: Set<string>;
    /** 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[];
    protected previousModelUsed?: string;
    protected previousCwdUsed?: string;
    private additionalDirectories;
    protected previousAdditionalDirectoriesUsed?: string[];
    private _currentToolDefinitions?;
    private _currentSystemMessageObj?;
    protected get currentSystemMessage(): string | undefined;
    protected get currentSystemMessageContent(): SystemMessageContent | undefined;
    protected set currentSystemMessage(value: string | undefined);
    /**
     * 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;
    protected set currentCustomInstructionsMessage(value: string | undefined);
    protected get currentToolMetadata(): ToolMetadata[] | undefined;
    protected set currentToolMetadata(value: ToolMetadata[] | undefined);
    /**
     * 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`.
     */
    protected modelListCache: 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;
    /** Get the cached model list (session-scoped CAPI models, if populated). */
    getModelListCache(): readonly Model[] | undefined;
    /** Pre-populate the model list cache (used by createSubagentSession to share parent's model list). */
    setModelListCache(models: Model[]): void;
    /** Pre-populate the unfiltered (include-hidden) model list cache (shared by createSubagentSession). */
    setUnfilteredModelListCache(models: Model[]): void;
    protected readonly pendingRequests: PendingRequestStore;
    /**
     * Tracks per-event-type "interest" registrations from out-of-process
     * consumers (SDK clients) and in-process facades that subscribe via the
     * event-log long-poll. These registrations don't appear as listeners on
     * the EventEmitter itself (subscribers get events via the persisted log),
     * so {@link hasEventListeners} ORs them with the EventEmitter listener
     * count to decide which behavior path to take.
     *
     * Counts are per event type; handles map back to their event type so
     * removal is O(1). Both the maps live on the abstract base because every
     * subclass shares the same hasEventListeners semantics.
     */
    private readonly _interestCounts;
    private readonly _interestHandles;
    private _interestHandleCounter;
    /** 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): boolean;
    private requestToolPermissionFromUser;
    private requestPathPermissionFromUser;
    private requestUrlPermissionFromUser;
    protected requestAutoApprovalFromModel(_rawPermissionRequest: PermissionRequest_2, _promptRequest: PermissionPromptRequest_2): Promise<AutoApprovalModelOutput>;
    private withAutoApprovalRecommendation;
    /**
     * A sandbox-bypass request — a shell command, or a built-in file tool's
     * read/write that asked to run outside the sandbox filesystem policy — is a
     * privilege escalation that must always be confirmed by the user; hook
     * `allow` results and resumed/cached approvals are not permitted to
     * short-circuit it.
     */
    protected isSandboxBypassRequest(permissionRequest: PermissionRequest_2): boolean;
    /**
     * 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): Promise<PermissionRequestResult_2 | null>;
    protected emitHookResolvedPermission(permissionRequest: PermissionRequest_2, result: PermissionRequestResult_2): void;
    /**
     * 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_2>;
    /**
     * 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_2>;
    /** 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[];
    /**
     * 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/remoteExportContracts.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_2>;
    /**
     * 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): 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;
    /** Respond to a pending MCP headers refresh request by its ID. */
    respondToMcpHeadersRefresh(requestId: string, headers: Record<string, string> | undefined): boolean;
    /** 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).
     * Note: getEffectiveCapabilities() always returns a concrete Set, so the
     * hasCapability fallback for undefined (returns true) won't trigger here.
     */
    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_2): void;
    /**
     * Dynamically add a capability to this session.
     * Returns true if the capability was newly added, false if already present.
     */
    addCapability(capability: SessionCapability_2): 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_2): boolean;
    /** 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 dispatch failure). */
    rejectExternalTool(requestId: string, error: Error): boolean;
    private hasRecordedPermissionRequest;
    private hasRecordedPermissionCompletion;
    private findRecordedPermissionToolCallId;
    private hasRecordedExternalToolRequest;
    private hasRecordedExternalToolCompletion;
    protected refreshPendingResumeOrphans(): OrphanedToolResumeInfo[] | undefined;
    protected loadPendingResumeOrphans(): OrphanedToolResumeInfo[] | undefined;
    protected takeResumePermissionResult(toolCallId: string): PermissionRequestResult_2 | undefined;
    protected hasResumePermissionResult(toolCallId: string): boolean;
    private takeResumeExternalToolCompletion;
    private findExternalToolCallId;
    private findPendingExternalToolCallId;
    protected enqueueResumePendingWake(): void;
    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;
    /** SDK-registered commands keyed by name. */
    private readonly sdkCommands;
    /** 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` → CLI
     * fallback resolver (when set) → null (registry skips the tick).
     */
    invokeCommand(name: string, input: string): 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/sessionApi.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 `sendParamsSchema`
     *   is forwarded to {@link send}; runtime-only fields (`source`,
     *   `notificationKind`, `prepend`) 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>;
    executeUserRequestedShellCommand(command: string, options?: UserRequestedShellCommandOptions): Promise<UserRequestedShellCommandResult_2>;
    /**
     * 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;
    /**
     * Get the current usage metrics for this session.
     * Returns aggregated metrics including premium requests, tokens, and code changes.
     */
    get usageMetrics(): UsageMetrics;
    protected applyModelCacheActivity(activity: ModelCacheActivity): string | undefined;
    protected get modelCacheState(): ModelCacheState[];
    protected flushModelCacheCheckpoint(): void;
    protected get lastUsageCheckpointTotalNanoAiu(): number | undefined;
    /**
     * 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` (the tracker is private, so the
     * `RelaySession` subclass needs a Session-level entry point). See
     * {@link UsageMetricsTracker.setCodeChanges} for the semantics (net vs
     * cumulative-activity divergence).
     */
    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 this._chatMessages)
     */
    protected computeContextBreakdown(messages?: readonly ChatCompletionMessageParam[]): {
        totalTokens: number;
        systemTokens: number;
        conversationTokens: number;
        toolDefinitionsTokens: number;
    };
    /**
     * Tracks whether `sessionStart` hooks have already been fired for this session.
     * Used to ensure sessionStart hooks execute only once per session, even when
     * `send()` is called multiple times in interactive mode.
     */
    protected _sessionStartHooksFired: boolean;
    /**
     * Cached `additionalContext` returned by `sessionStart` hooks.
     * Injected into every turn's messages so later prompts still see the context.
     */
    protected _sessionStartAdditionalContext: string | undefined;
    /**
     * When true, this session was restored from persisted events via `fromEvents()`.
     * Used to set the correct `source` field on `sessionStart` hooks.
     */
    protected _createdFromEvents: boolean;
    /**
     * Orphaned tool calls whose durable permission/external-tool state still needs to
     * be consumed or preempted. These are resolved at the start of the next
     * `runAgenticLoop()` call, after tools are built and before model inference starts.
     */
    protected _pendingResumeOrphans: OrphanedToolResumeInfo[] | undefined;
    /** Ensures only one internal resume wake-up item is queued at a time. */
    protected _resumePendingWakeQueued: boolean;
    /**
     * Tracks `toolCallId`s of "approved" orphans that were deferred during
     * a {@link resolveResumeOrphans} pass because the corresponding tool
     * wasn't in the supplied `toolMap` (typically because MCP tools
     * hadn't loaded yet on the early pass). On a subsequent pass where
     * the tool is STILL missing, the orphan is marked interrupted
     * instead of being re-deferred indefinitely — `hasAwaitingResumeOrphans()`
     * does not block on the "approved" state, so without this the
     * runtime could exit with the orphan silently unresolved.
     *
     * Held on `this` rather than on the orphan info itself because
     * {@link refreshPendingResumeOrphans} re-classifies orphans from the
     * event log and would otherwise clobber a per-orphan flag.
     */
    protected readonly _approvedOrphansDeferredForMissingTool: Set<string>;
    /** Pre-recorded permission results consumed while continuing resumable orphans. */
    protected readonly _resumePermissionResultsByToolCallId: Map<string, PermissionRequestResult_2>;
    /**
     * In-memory external tool completions supplied after resume.
     *
     * We intentionally do not serialize these into the event log. If a caller
     * reconnects after suspend, it must hand the result back to the resumed
     * session, which keeps it here just long enough to continue or preempt.
     */
    protected readonly _resumeExternalToolCompletionsByToolCallId: Map<string, ExternalToolCompletion_2>;
    /**
     * In-memory idempotence guard for external tool completions.
     *
     * Once a request has been answered or preempted in this process, we ignore
     * duplicate late responses. The persisted `external_tool.completed` event
     * carries only the requestId; result data lives in
     * `_resumeExternalToolCompletionsByToolCallId` and must be re-supplied by
     * the SDK consumer after a suspend/resume.
     */
    protected readonly _resolvedExternalToolRequestIds: Set<string>;
    /**
     * When true, the session waits for all orphaned tool calls to reach terminal
     * state before processing user messages after resume. The agentic continuation
     * loop blocks (while keeping `isProcessing=true`) so that user sends are
     * naturally queued via the existing `send()` guard.
     *
     * When false (default), the resume handler immediately marks any orphaned
     * tool calls as interrupted, leaving the resumed session in a clean state
     * indistinguishable from a fresh send. No resume-specific code paths run
     * in `runAgenticLoop` in this mode.
     */
    protected _continuePendingWork: boolean;
    /**
     * 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;
    /**
     * When true, `sessionEnd` hooks are NOT fired at the end of each `runAgenticLoop()`.
     * Instead, {@link shutdown} fires them once when the session truly ends, so that
     * interactive sessions (where multiple `send()` calls share one logical session
     * lifetime) don't fire `sessionEnd` after every individual turn.
     */
    protected _deferSessionEnd: boolean;
    /** 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 hasShutdown;
    private _shutdownPromise;
    shutdown(params?: ShutdownParams): Promise<void>;
    protected disposeOwnedFeatureFlagService(): Promise<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
         * (`SessionEventState.load`), whose Rust 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;
    }): Promise<S>;
    /**
     * 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): void;
    replaceNativeHookProcessor(processor: NativeHookProcessor, ownsHandle?: boolean): void;
    /**
     * Snapshots the base (pre-experiment) values of the two dynamic-retrieval
     * flags from a freshly-assigned feature-flag set. Called wherever
     * `featureFlags` is set from options so {@link LocalSession.applyDynamicRetrievalArm}
     * can restore them when no experiment arm is assigned.
     */
    protected captureDynamicRetrievalBase(flags: FeatureFlags | undefined): void;
    /**
     * 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 `this.byokProvider`).
     *
     * 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_2[], models: readonly ProviderModelConfig_2[]): Model[];
    /** 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;
    /**
     * Builds the legacy-shaped {@link ProviderConfig} for a registry BYOK model by merging
     * its named provider's connection fields with the model's wire/behavior/limit fields.
     */
    private buildByokProviderConfig;
    /**
     * Synthesizes the selectable {@link Model} metadata for a registry BYOK model.
     * The model's `id` is the provider-qualified selection id (so the model list and
     * `switchTo` use the self-describing identifier); the display name defaults to that
     * same qualified id so a bare token never matches a BYOK entry by name.
     */
    private synthesizeByokModelMetadata;
    /**
     * 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): void;
    protected disposeUserMessageSentimentTelemetry(): void;
    /**
     * 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[];
    /**
     * 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;
    /**
     * Get the SDK client name for this session.
     * This identifies the SDK consumer (e.g., "autopilot", "sdk").
     */
    getClientName(): 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;
    /**
     * 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;
    /**
     * The effective tool-search tool definition, hoisted from an
     * `externalToolDefinitions` override. Returns the model-facing fields the
     * `createToolSearchTool` shim consumes (the `tool_search_tool` NAME stays
     * fixed), normalizing the override's `parameters` into `input_schema`.
     */
    protected getToolSearchToolDefinition(): {
        description?: string;
        title?: string;
        input_schema?: ToolInputSchema;
    } | undefined;
    /**
     * Splits a tool-search override (a definition named `tool_search_tool`
     * with `overridesBuiltInTool`) out of the incoming external tool list, storing
     * it under {@link toolSearchOverrideFromExternal}, and returns the remaining
     * regular external tools.
     */
    protected hoistToolSearchOverrideFromExternal(definitions: ExternalToolDefinition[]): ExternalToolDefinition[];
    protected getExternalToolMetadata(definitions: readonly ExternalToolDefinition[] | undefined): ToolMetadata[];
    private getEnabledExternalToolMetadata;
    protected getValidOverridingExternalToolNames(): Set<string>;
    protected filterToolsForSelectedAgent<T extends ToolMetadata>(allTools: T[]): T[];
    /**
     * 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;
    protected composeCurrentToolMetadata(nonExternalToolMetadata: readonly ToolMetadata[], externalToolMetadata: readonly ToolMetadata[]): ToolMetadata[];
    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 getToolCallSummary;
    private formatBackgroundToolActivity;
    /**
     * 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;
    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;
    /**
     * 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;
    updateSubagentSettings(subagentSettings: UserSettings["subagents"] | undefined): void;
    /**
     * 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: {
        agentType: string;
        prompt: string;
        name: string;
        description?: string;
        model?: string;
        factoryRunId?: string;
        suppressMultiTurn?: boolean;
    }): Promise<string>;
    /**
     * Notify listeners that background tasks have changed.
     * Called internally when tasks start or complete.
     */
    protected notifyBackgroundTaskChange(): void;
    /** Hook called after compaction replaces chat messages. Override to reset per-turn dedup state. */
    protected onCompactionApplied(): void;
    protected onUsageMetricsUpdated(_event: SessionEvent): void;
    protected getResponseLimitsPreRequestProcessorForSubagent(): ResponseLimitsPreRequestProcessor | undefined;
    setInheritedResponseLimitsPreRequestProcessor(_processor: ResponseLimitsPreRequestProcessor): void;
    protected getRuntimeSettings(): RuntimeSettings;
    protected getModelResolverSettings(): RuntimeSettings;
    protected getCurrentSettingsForHandle(): RuntimeSettings;
    protected clearAutoModeSessionTokenFromSettings(): void;
    protected clearCachedAutoModeSessionTokenFromSettings(): void;
    protected overlayCurrentSessionSettingsForHandle(settings: RuntimeSettings): RuntimeSettings;
    private getSettingsHandle;
    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 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 `this.events`.
     *
     * @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;
    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[];
    getInitialEvents(): readonly SessionEvent[];
    /**
     * Returns the tools that were resolved during the last `initializeAndValidateTools()` or `send()` call.
     * Prefers currentTools (from send()) when available, falls back to initializedTools (from
     * initializeAndValidateTools()). Returns an empty array if tools have not been initialized yet.
     */
    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 (e.g., via SessionEventState.truncate).
     *
     * @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[]>;
    /**
     * 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[];
    /**
     * 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;
    /**
     * 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;
    private getPromptContextMessagesSnapshot;
    private upsertSystemContextMessage;
    /**
     * 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 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_3 | 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_3 | undefined;
    /**
     * 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): 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>;
    /**
     * 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 {@link DEFAULT_MAX_INLINE_BINARY_BYTES} 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<InstructionSource_2[]>;
    /** Loads and caches instruction sources derived from installed plugin rules. */
    protected getPluginInstructionSources(): Promise<InstructionSource_2[]>;
    /**
     * Returns instruction sources discovered dynamically via file access.
     */
    getDynamicInstructionSources(): InstructionSource_2[];
    /**
     * Returns the raw dynamic instruction state for telemetry aggregation.
     */
    getDynamicInstructionState(): DynamicInstructionState;
    /**
     * 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_2>;
    /**
     * 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>;
    /**
     * Get the absolute file path of the autopilot objective state file.
     * Returns null if workspace storage is not enabled.
     */
    getAutopilotObjectivePath(): string | null;
    /**
     * 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">;
    /**
     * Delete the machine-managed autopilot objective state file.
     */
    deleteAutopilotObjective(): Promise<boolean>;
    /**
     * Check if the machine-managed autopilot objective state file exists.
     */
    autopilotObjectiveExists(): Promise<boolean>;
    /**
     * 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>;
    /**
     * Get the per-session WorkspaceManager, if available.
     * Returns null when workspace features are not enabled (e.g. non-infinite sessions, CCA runtime).
     */
    getWorkspaceManager(): WorkspaceManager | null;
    /**
     * 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_2, reasoningSummary?: ReasoningSummary_3, contextTier?: ContextTier_3, verbosity?: Verbosity_3): Promise<void>;
    protected applyModelChange(model: string, options?: {
        reasoningEffort?: ReasoningEffort;
        reasoningSummary?: ReasoningSummary_3;
        verbosity?: Verbosity_3;
        modelCapabilitiesOverrides?: ModelCapabilitiesOverride_2;
        contextTier?: ContextTier_3;
        cause?: string;
    }): Promise<void>;
    /**
     * Compacts the conversation history into a single summary message.
     * Used by the /compact slash command for manual compaction.
     *
     * @param customInstructions - Optional user-provided instructions to focus the compaction summary
     * @returns Promise that resolves with compaction results
     * @throws Error if compaction fails or is not supported
     */
    abstract compactHistory(customInstructions?: string): 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.
     *
     * Awaiting-* orphans are left in `_pendingResumeOrphans` for the wait-loop
     * in `runAgenticLoop`. Other states are replayed (denied → synthetic failure,
     * approved → re-invoke, external-tool-completed → emit stored result).
     */
    protected resolveResumeOrphans(tools: Tool[], settings: RuntimeSettings, toolsetComplete: boolean): Promise<void>;
    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): Promise<void>;
    private getInterruptedToolMessage;
    protected rewriteChatHistoryForModel(newModel: string): Promise<void>;
    protected maybeRewriteChatHistoryForEffectiveModel(newModel: string): Promise<void>;
    /**
     * Recovers the tool name for a tool call recorded during event replay. The
     * `tool.execution_complete` event doesn't carry the tool name, but the
     * assistant message that issued the call does; that name is indexed by
     * call id in {@link _toolCallNameById} when the assistant tool_calls are
     * processed (and kept addressable across model-change id remaps), so this is
     * an O(1) lookup rather than a scan of the whole chat history. Covers both
     * function and custom tool calls, keeping name-based screenshot detection
     * consistent with the live image path on rebuild/resume. Returns `undefined`
     * if no matching tool call was recorded.
     */
    private findToolNameForToolCallId;
    /**
     * Rebuild {@link _replayToolResultCallIds} from the current {@link _chatMessages}.
     * Called after any operation that replaces the message array wholesale during
     * a replay (orphan completion, compaction, boundary repair) so the O(1)
     * duplicate-result check stays in sync with the messages that actually remain.
     * No-op outside a replay (the index is only allocated in {@link Session.fromEvents}).
     */
    private rebuildReplayToolResultIndex;
    /**
     * Rebuild {@link _toolCallNameById} from the assistant tool_calls currently in
     * {@link _chatMessages}. Unlike the replay-only result-id index, this name
     * index lives for the whole session and backs {@link findToolNameForToolCallId}
     * on both the live and replay paths. It must be refreshed at every wholesale
     * history replacement that can drop assistant tool calls (compaction), so that
     * a call summarized away no longer leaves a stale, addressable name — a late
     * completion for a removed id would otherwise inherit the wrong tool name (e.g.
     * a spurious screenshot hint) — and so the map does not grow unbounded across a
     * long-lived session. Rebuilding from the surviving messages both prunes gone
     * entries and preserves names for calls still awaiting a result.
     */
    protected rebuildToolCallNameIndex(): void;
    /**
     * Process event to update internal state (_chatMessages, _selectedModel, etc.)
     */
    private processEventForState;
    private emitCustomAgentsUpdated;
    private getProvidedCustomAgents;
    private mergeProvidedCustomAgents;
    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>;
    /**
     * Clears compaction checkpoint state. Called after compaction completes (success or failure)
     * and when cancelling a background compaction to avoid retaining stale references.
     */
    protected resetCompactionCheckpoint(): void;
    /**
     * Applies compaction to chat messages by replacing the checkpoint prefix with
     * Rust-built post-compaction messages while preserving messages added after the checkpoint.
     *
     * @param checkpointLength - The number of messages at the compaction checkpoint
     * @param summaryContent - The summary content from compaction
     * @returns The compacted messages and any new messages added after the checkpoint
     */
    protected applyCompactionToMessages(checkpointLength: number, summaryContent: string, modelId?: string): Promise<{
        compacted: ChatCompletionMessageParam[];
        newMessages: ChatCompletionMessageParam[];
    }>;
    /**
     * Event types that are transient/ephemeral and can be safely evicted after
     * compaction. These events are not needed for state reconstruction (they
     * don't contribute to chat messages) and are the primary source of memory
     * growth in long-running sessions.
     */
    private static readonly TRANSIENT_EVENT_TYPES;
    /**
     * Evicts transient events from the events array for events that occurred
     * before the given index. This reduces memory without affecting state
     * reconstruction or timeline display for structural events.
     */
    private evictTransientEventsBeforeIndex;
    /**
     * 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>;
    protected resolveIsRubberDuckAgentExpEnabled(): Promise<boolean>;
    /**
     * 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;
    private inheritBuiltinAgentPolicyState;
}

/** Modes settable on session.currentMode (excludes shell, which is TUI-only) */
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(): AgentList | Promise<AgentList>;
        reload(): AgentReloadResult | Promise<AgentReloadResult>;
        select(params: AgentSelectRequest): AgentSelectResult | Promise<AgentSelectResult>;
    };
    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>;
    };
    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>;
        journal: {
            get(params: FactoryJournalGetRequest): FactoryJournalGetResult | Promise<FactoryJournalGetResult>;
            put(params: FactoryJournalPutRequest): FactoryAckResult | Promise<FactoryAckResult>;
        };
        log(params: FactoryLogRequest): FactoryAckResult | Promise<FactoryAckResult>;
        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>;
        compact(params?: HistoryCompactRequest): HistoryCompactResult | Promise<HistoryCompactResult>;
        summarizeForHandoff(): HistorySummarizeForHandoffResult | Promise<HistorySummarizeForHandoffResult>;
        truncate(params: HistoryTruncateRequest): HistoryTruncateResult | Promise<HistoryTruncateResult>;
    };
    instructions: {
        getSources(): InstructionsGetSourcesResult | Promise<InstructionsGetSourcesResult>;
    };
    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: {
            handlePendingRequest(params: McpOauthHandlePendingRequest): McpOauthHandlePendingResult | Promise<McpOauthHandlePendingResult>;
            login(params: McpOauthLoginRequest): McpOauthLoginResult | Promise<McpOauthLoginResult>;
        };
        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 | Promise<PermissionRequestResult>;
        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: {
        clear(): void | Promise<void>;
        pendingItems(): QueuePendingItemsResult | Promise<QueuePendingItemsResult>;
        removeMostRecent(): QueueRemoveMostRecentResult | Promise<QueueRemoveMostRecentResult>;
    };
    remote: {
        disable(): void | Promise<void>;
        enable(params: RemoteEnableRequest): RemoteEnableResult | Promise<RemoteEnableResult>;
        notifySteerableChanged(params: RemoteNotifySteerableChangedRequest): RemoteNotifySteerableChangedResult | Promise<RemoteNotifySteerableChangedResult>;
    };
    schedule: {
        list(): ScheduleList | Promise<ScheduleList>;
        stop(params: ScheduleStopRequest): ScheduleStopResult | Promise<ScheduleStopResult>;
    };
    send(params: SendRequest): SendResult | Promise<SendResult>;
    sendMessages(params: SendMessagesRequest): SendMessagesResult | Promise<SendMessagesResult>;
    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 | Promise<UserRequestedShellCommandResult>;
        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: {
        createFile(params: WorkspacesCreateFileRequest): void | Promise<void>;
        diff(params: WorkspacesDiffRequest): WorkspaceDiffResult | Promise<WorkspaceDiffResult>;
        getWorkspace(): WorkspacesGetWorkspaceResult | Promise<WorkspacesGetWorkspaceResult>;
        listCheckpoints(): WorkspacesListCheckpointsResult | Promise<WorkspacesListCheckpointsResult>;
        listFiles(): WorkspacesListFilesResult | Promise<WorkspacesListFilesResult>;
        readCheckpoint(params: WorkspacesReadCheckpointRequest): WorkspacesReadCheckpointResult | Promise<WorkspacesReadCheckpointResult>;
        readFile(params: WorkspacesReadFileRequest): WorkspacesReadFileResult | Promise<WorkspacesReadFileResult>;
        saveLargePaste(params: WorkspacesSaveLargePasteRequest): WorkspacesSaveLargePasteResult | Promise<WorkspacesSaveLargePasteResult>;
    };
}

/** 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: "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;
}

export declare type SessionAutopilotObjectiveChangedEvent = WireTypes.SessionAutopilotObjectiveChangedEvent;

export declare type SessionBackgroundTasksChangedEvent = WireTypes.SessionBackgroundTasksChangedEvent;

export declare type SessionBinaryAssetEvent = WireTypes.SessionBinaryAssetEvent;

/** 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"];

export declare type SessionCanvasClosedEvent = WireTypes.SessionCanvasClosedEvent;

export declare type SessionCanvasOpenedEvent = WireTypes.SessionCanvasOpenedEvent;

export declare type SessionCanvasRegistryChangedEvent = WireTypes.SessionCanvasRegistryChangedEvent;

declare interface SessionCanvasRuntimeApi extends SessionCanvasApi {
    registerProvider(params: {
        connectionId: string;
        connection: CanvasProviderConnection;
        info: CanvasProviderInfo;
        canvases: CanvasContribution[];
    }): void;
    unregisterProvider(connectionId: string): void;
    /**
     * Seeds the open-instance snapshot from the runtime's own replayed durable
     * set on cold resume. Seeded instances start as `stale` until their owning
     * provider reconnects or the agent re-opens them, and the seed never emits
     * `session.canvas.opened` (the host learns about a restored instance only
     * once it rehydrates to `ready`) and never appends a durable record (the
     * snapshots are already in the event log).
     */
    seedOpenInstances(instances: OpenCanvasInstance[]): void;
    /**
     * Returns the extension/canvas identity that owns the given canvas
     * instance, or `undefined` if the instance is not tracked.
     */
    getOpenInstanceOwner(instanceId: string): {
        extensionId: string;
        canvasId: string;
    } | undefined;
    /**
     * Releases the per-session state held in the native runtime. Called during
     * session lifecycle cleanup; subsequent calls on the returned API have undefined
     * behaviour.
     */
    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";

/**
 * # Session Capabilities
 *
 * Session capabilities control what prompt content, tools, and behaviors are available in a
 * given session. They prevent features intended for one client type from leaking into others —
 * for example, TUI keyboard shortcuts appearing in SDK prompts, or memory tools being offered
 * to headless clients that don't support them.
 *
 * ## Capability matrix
 *
 * | Capability                    | CLI TUI | SDK | ACP | General Agent |
 * |-------------------------------|---------|-----|-----|---------------|
 * | tui-hints                     |    ✓    |     |     |               |
 * | plan-mode                     |    ✓    |     |  ✓  |               |
 * | memory                        |    ✓    |     |     |       ✓       |
 * | cli-documentation             |    ✓    |     |     |       ✓       |
 * | ask-user                      |    ✓    |  ✓  |     |       ✓       |
 * | interactive-mode              |    ✓    |  ✓  |  ✓  |               |
 * | system-notifications          |    ✓    |  ✓  |  ✓  |               |
 * | elicitation                   |    ✓    |     |     |               |
 * | session-store                 |    ✓    |     |  ✓  |       ✓       |
 * | mcp-apps                      |         |     |     |               |[^1]
 * | canvas-renderer               |    ✓    |     |     |               |[^2]
 *
 * [^1]: `mcp-apps` is opt-in across all client types (excluded from
 *       `DEFAULT_SESSION_CAPABILITIES`, `SDK_CAPABILITIES`, and
 *       `ACP_CAPABILITIES`). SDK consumers request it via
 *       `session.create({ requestMcpApps: true })`, which is additionally
 *       gated on the `MCP_APPS` feature flag / `COPILOT_MCP_APPS=true` env
 *       override. Embedded hosts (CLI TUI / ACP) request it by adding
 *       `"mcp-apps"` to the constructor-supplied `sessionCapabilities` set.
 *
 * [^2]: `canvas-renderer` is enabled by the CLI TUI. SDK consumers request it
 *       via `session.create({ requestCanvasRenderer: true })` or
 *       `session.resume({ requestCanvasRenderer: true })`.
 *
 * ## Where capabilities are checked
 *
 * 1. **Prompt generation** (`src/cli/prompts/system.ts`) — Conditional sections are included
 *    or excluded based on `hasCapability()`.
 * 2. **Tool creation** (`src/agents/config.ts`) — Tools are only added when their capability
 *    is active.
 *
 * ## Runtime overrides
 *
 * `Session.getEffectiveCapabilities()` can further narrow capabilities at runtime:
 * - `askUserDisabled` → removes `ask-user`
 * - `runningInInteractiveMode === false` → removes `interactive-mode`
 *
 * ## When to add a new capability vs reuse an existing one
 *
 * **Add a new capability when:**
 * - You're introducing a tool or prompt section only relevant to a subset of client types
 * - No existing capability's client set matches who needs this feature
 *
 * **Reuse an existing capability when:**
 * - Your feature naturally belongs to the same audience (e.g., a new keyboard shortcut → `tui-hints`)
 * - The feature would always be enabled/disabled together with an existing one
 *
 * **Guiding principle:** A capability represents a _category of functionality for a type of
 * client_, not an individual feature. Keep the list small.
 *
 * ## What capabilities are NOT for
 *
 * - **Feature flags**: Use `FeatureFlagManager` for gradual rollouts. Capabilities are static per client type.
 * - **Model capabilities**: `SweBenchAgentCapabilities` (e.g., `parallel_tool_calls`) describes model support.
 * - **Runtime modes**: Concepts like autopilot that are purely behavioral toggles don't need capabilities.
 *
 * ## Adding a new capability
 *
 * 1. Add the literal to `SessionCapability` below
 * 2. Add it to `ALL_SESSION_CAPABILITIES`
 * 3. Add it to the appropriate client sets (`SDK_CAPABILITIES`, `ACP_CAPABILITIES`, etc.)
 * 4. Use `hasCapability(caps, "your-capability")` in prompt generation and/or tool creation
 * 5. Add behavioral tests in `test/core/sessionCapabilities.test.ts`
 * 6. Update snapshots: `npm run test:update-snapshots`
 */
declare type SessionCapability_2 = "tui-hints" | "plan-mode" | "memory" | "cli-documentation" | "ask-user" | "interactive-mode" | "system-notifications" | "elicitation" | "session-store" | "mcp-apps" | "canvas-renderer";

/**
 * Structured client kind used for behavior gates.
 * Unlike clientName, this is not a telemetry branding identifier and should not depend on a literal name.
 */
export declare type SessionClientKind = "cli" | "acp" | "sdk";

declare type SessionCommandsApi = SessionApi["commands"];

export declare type SessionCompactionCompleteData = SessionCompactionCompleteEvent["data"];

export declare type SessionCompactionCompleteEvent = WireTypes.SessionCompactionCompleteEvent;

export declare type SessionCompactionStartEvent = WireTypes.SessionCompactionStartEvent;

/** 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"];

/**
 * Working directory context for session tracking.
 */
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 = {
    compactions: {
        count: number;
    };
    entries: {
        attributes?: Record<string, string>;
        id: string;
        kind: string;
        label: string;
        parentId?: string;
        tokens: number;
    }[];
    totalTokens: number;
} | null;

export declare type SessionContextChangedEvent = WireTypes.SessionContextChangedEvent;

/** 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>;

export declare type SessionCustomAgentsUpdatedEvent = WireTypes.SessionCustomAgentsUpdatedEvent;

/**
 * Public TypeScript facade for Rust-owned per-session SQLite orchestration.
 */
declare class SessionDatabase {
    private readonly sessionFs;
    /**
     * Stable per-instance key used when the underlying RPC-backed `SessionFs`
     * does not expose a session id. The Rust runtime caches default-table
     * initialization by session id; without a unique fallback, multiple
     * sessionless providers would collide on the empty string and the second
     * and later databases would skip default-table creation. A per-instance id
     * preserves the legacy per-`SessionDatabase` initialization semantics. The
     * default reverse-call handler dispatches directly to this `SessionFs`
     * instance, so this synthetic id never affects request routing.
     */
    private readonly fallbackSessionId;
    constructor(sessionFs: SessionFs);
    /**
     * Execute a SQL query and return the results.
     *
     * Delegates local/RPC sqlite routing to the Rust runtime.
     *
     * @param queryType - How to execute: 'exec' (DDL), 'query' (SELECT), or 'run' (INSERT/UPDATE/DELETE)
     * @param query - The SQL query to execute
     * @returns Query results
     */
    execute(queryType: SqliteQueryType, query: string): Promise<SqlResult | undefined>;
    /**
     * Execute multiple SQL statements in a batch.
     * Useful for transactions or multi-statement operations.
     *
     * @param queries - Array of `[queryType, sql]` pairs to execute
     * @returns Array of results for each query
     */
    batch(queries: [SqliteQueryType, string][]): Promise<(SqlResult | undefined)[]>;
    /**
     * Get the list of all table names in the database.
     * If the database doesn't exist yet, it will be initialized (creating default tables).
     */
    getTableNames(): Promise<string[]>;
    /**
     * Get the list of all table names in the database if it already exists.
     * Returns an empty array if the database hasn't been created yet (without creating it).
     */
    getTableNamesIfExists(): Promise<string[]>;
    /**
     * Get todo status counts from the todos table.
     * Returns null if the database doesn't exist or has no todos.
     */
    getTodoStatus(): Promise<{
        pending: number;
        in_progress: number;
        done: number;
        blocked: number;
        total: number;
    } | null>;
    /**
     * Derive the current user-visible intent from the todo list.
     * Returns null if the database doesn't exist or there is no candidate intent.
     */
    getCurrentIntent(): Promise<string | null>;
    closeAll(): Promise<void>;
    private get sessionStatePath();
    private get handler();
    private get sessionId();
}

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[];
}

export declare type SessionErrorEvent = WireTypes.SessionErrorEvent;

export declare type SessionEvent = WireTypes.SessionEvent;

/** Union of all session event variants emitted by the Copilot CLI runtime. */
declare type SessionEvent_2 = 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 | CompactionStartEvent | CompactionCompleteEvent | TaskCompleteEvent | UserMessageEvent_2 | PendingMessagesModifiedEvent_2 | AssistantTurnStartEvent_2 | AssistantTurnRetryEvent | AssistantIntentEvent_2 | AssistantServerToolProgressEvent_2 | AssistantReasoningEvent_2 | AssistantReasoningDeltaEvent_2 | AssistantToolCallDeltaEvent_2 | AssistantStreamingDeltaEvent_2 | AssistantMessageEvent_2 | AssistantMessageStartEvent_2 | AssistantMessageDeltaEvent_2 | AssistantTurnEndEvent_2 | AssistantIdleEvent_2 | AssistantUsageEvent_2 | ModelCallFailureEvent | ModelCallStartEvent | AbortEvent_2 | ToolUserRequestedEvent_2 | ToolExecutionStartEvent_2 | ToolExecutionPartialResultEvent_2 | ToolExecutionProgressEvent_2 | ToolExecutionCompleteEvent_2 | ToolSearchActivatedEvent_2 | SkillInvokedEvent_2 | SubagentStartedEvent_2 | SubagentCompletedEvent_2 | SubagentFailedEvent_2 | SubagentSelectedEvent_2 | SubagentDeselectedEvent_2 | HookStartEvent_2 | HookEndEvent_2 | HookProgressEvent_2 | BinaryAssetEvent | SystemMessageEvent_2 | SystemNotificationEvent_2 | PermissionRequestedEvent_2 | PermissionCompletedEvent_2 | UserInputRequestedEvent_2 | UserInputCompletedEvent_2 | ElicitationRequestedEvent_2 | ElicitationCompletedEvent_2 | SamplingRequestedEvent_2 | SamplingCompletedEvent_2 | McpOauthRequiredEvent | McpOauthCompletedEvent | McpHeadersRefreshRequiredEvent_2 | McpHeadersRefreshCompletedEvent_2 | CustomNotificationEvent_2 | ExternalToolRequestedEvent_2 | ExternalToolCompletedEvent_2 | CommandQueuedEvent_2 | CommandExecuteEvent_2 | CommandCompletedEvent_2 | AutoModeSwitchRequestedEvent_2 | AutoModeSwitchCompletedEvent_2 | SessionLimitsExhaustedRequestedEvent | SessionLimitsExhaustedCompletedEvent | AutoModeResolvedEvent_2 | ManagedSettingsResolvedEvent_2 | ManagedSettingsEnforcedEvent_2 | CommandsChangedEvent | CapabilitiesChangedEvent_2 | ExitPlanModeRequestedEvent_2 | ExitPlanModeCompletedEvent_2 | ToolsUpdatedEvent | BackgroundTasksChangedEvent | SkillsLoadedEvent | CustomAgentsUpdatedEvent | McpServersLoadedEvent | McpServerStatusChangedEvent | McpToolsListChangedEvent_2 | McpResourcesListChangedEvent_2 | McpPromptsListChangedEvent_2 | ExtensionsLoadedEvent | CanvasOpenedEvent | CanvasRegistryChangedEvent | CanvasClosedEvent | CanvasUnavailableEvent | CanvasRecordedEvent | CanvasRemovedEvent | ExtensionsAttachmentsPushedEvent | McpAppToolCallCompleteEvent_2;

declare type SessionEventsApi = SessionApi["eventLog"];

export declare type SessionEventType = SessionEvent["type"];

declare type SessionEventType_2 = SessionEvent_2["type"];

declare type SessionExtensionsApi = SessionApi["extensions"];

export declare type SessionExtensionsAttachmentsPushedEvent = WireTypes.SessionExtensionsAttachmentsPushedEvent;

export declare type SessionExtensionsLoadedEvent = WireTypes.SessionExtensionsLoadedEvent;

declare type SessionFactoryApi = SessionApi["factory"];

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 `node:fs`.
 *
 * 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 {
    /**
     * Per-session SQLite database, or `undefined` when the underlying
     * filesystem provider does not support SQLite.
     */
    readonly sessionDatabase: SessionDatabase | undefined;
    constructor(sqliteSupported: boolean);
    /**
     * 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>;
    /** 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. */
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;
}

/**
 * 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"];

export declare type SessionHandoffEvent = WireTypes.SessionHandoffEvent;

declare type SessionHistoryApi = SessionApi["history"];

export declare type SessionIdleEvent = WireTypes.SessionIdleEvent;

export declare type SessionInfoEvent = WireTypes.SessionInfoEvent;

/** 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;
    /** 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, and optional subpath. */
declare interface SessionInstalledPluginSourceGitHub {
    path?: string;
    ref?: string;
    repo: 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, and optional subpath. */
declare interface SessionInstalledPluginSourceUrl {
    path?: string;
    ref?: string;
    /** Constant value. Always "url". */
    source: "url";
    url: string;
}

declare type SessionInstructionsApi = SessionApi["instructions"];

/** Session limits update details. Null clears the limits. */
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. */
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. */
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. */
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. */
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. */
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. */
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. */
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"];

/**
 * SessionManager interface
 */
export declare interface SessionManager<TSessionMetadata extends SessionMetadata = SessionMetadata, TSession extends Session<TSessionMetadata> = Session<TSessionMetadata>> {
    createSession(sessionOptions: SessionOptions): Promise<TSession>;
    getSession(options: {
        sessionId: string;
    }): Promise<TSession | undefined>;
    getLastSession(): Promise<TSession | undefined>;
    getLastSessionId(): Promise<string | undefined>;
    listSessions(): Promise<TSessionMetadata[]>;
    saveSession(session: TSession): Promise<void>;
    deleteSession(sessionId: string): Promise<void>;
    closeSession(sessionId: string): Promise<void>;
}

/**
 * SessionManager options - same as SessionOptions but used for creating the manager
 */
export declare type SessionManagerOptions = {
    logger?: RunnerLogger;
    integrationId?: string;
};

declare type SessionMcpApi = Omit<SessionApi["mcp"], "oauth" | "headers" | "apps" | "resources">;

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 type SessionMcpServersResolvedEvent = WireTypes.SessionMcpServersResolvedEvent;

export declare type SessionMcpServerStatusChangedEvent = WireTypes.SessionMcpServerStatusChangedEvent;

export declare type SessionMemoryChangedEvent = WireTypes.SessionMemoryChangedEvent;

export declare interface SessionMetadata {
    readonly sessionId: string;
    readonly startTime: Date;
    readonly modifiedTime: Date;
    readonly summary?: string;
    /** Optional human-friendly name (set via rename). */
    readonly name?: string;
    /** Runtime client name that created/last resumed this session (telemetry identifier). */
    readonly clientName?: string;
    readonly isRemote: boolean;
    /** Most recent working directory context (from last start or resume). */
    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;
}

export declare type SessionMode = (typeof SESSION_MODES)[number];

/** The session mode the agent is operating in */
declare type SessionMode_2 = "interactive" | "plan" | "autopilot";

/** The session mode the agent is operating in */
declare type SessionMode_3 = "interactive" | "plan" | "autopilot";

declare type SessionModeApi = SessionApi["mode"];

export declare type SessionModeChangedEvent = WireTypes.SessionModeChangedEvent;

declare type SessionModelApi = SessionApi["model"];

export declare type SessionModelChangeEvent = WireTypes.SessionModelChangeEvent;

/** 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[];
    /** 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_2;
    /** 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[];
    /** 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: 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;
    /** 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;
    /** 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_2;
    /** Initial model identifier. */
    model?: string;
    /** Initial model capability overrides. */
    modelCapabilitiesOverrides?: ModelCapabilitiesOverride;
    /** BYOK model definitions added to the selectable model list, each referencing a provider name. */
    models?: ProviderModelConfig[];
    /** 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[];
    /** Initial reasoning effort level. */
    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;
    /** Shell init profile. */
    shellInitProfile?: string;
    /** Per-shell process flags. */
    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_2;
    /** 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.
     * Valid values: "low", "medium", "high", "xhigh", "max"
     * Only applies to models where reasoning effort is supported.
     */
    reasoningEffort?: ReasoningEffort;
    /**
     * Reasoning summary mode for models that support it.
     * When omitted, the client uses model/runtime defaults.
     */
    reasoningSummary?: ReasoningSummary_3;
    /**
     * Output verbosity level for supported models.
     * Ignored by providers that do not expose a real wire-level verbosity setting.
     */
    verbosity?: Verbosity_3;
    /**
     * 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_2[];
    /**
     * 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_2[];
    /**
     * 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.
     * - `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_2;
    /**
     * 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;
    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;
    /**
     * Controls which profile/startup scripts the shell sources during initialization.
     * @see ShellInitProfile
     */
    shellInitProfile?: ShellInitProfile;
    /**
     * Custom flags passed to the shell process on startup (e.g., PowerShell flags).
     * Overrides the default flags for the shell type.
     */
    shellProcessFlags?: string[];
    /** Sandbox configuration for shell commands. */
    sandboxConfig?: SandboxConfig_2;
    /** 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` and the runtime-side
     * ON_DEMAND_INSTRUCTIONS feature flag.
     * 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
     * {@link DEFAULT_MAX_INLINE_BINARY_BYTES} (10 MB).
     */
    maxInlineBinaryBytes?: number;
    /**
     * Shared store for de-duplicated binary tool-result assets (images,
     * resources). When provided, this session uses the given registry instead of
     * creating its own. Subagent sessions are constructed with their parent's
     * registry so an asset interned by either side is seen as already-tracked by
     * the other: the child never re-emits a `session.binary_asset` the parent
     * already logged (avoiding duplicate asset events in the bridged parent log),
     * and either session can resolve references to assets the other interned.
     * When unset, the session creates its own registry.
     */
    binaryAssetRegistry?: BinaryAssetRegistry;
    disabledSkills?: Set<string>;
    /**
     * When true, enables loading of `.github/hooks/` filesystem hooks.
     * 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[];
    mcpServers?: Record<string, MCPServerConfig>;
    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;
    trajectoryFile?: string;
    eventsLogDirectory?: string;
    /**
     * 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;
    /**
     * Working directory for the session. Should be an absolute path under the
     * session filesystem's path convention. `getWorkingDirectory()` treats a
     * relative, empty, or whitespace-only value as "no override": on session
     * creation it falls back to the session filesystem's initial working
     * directory (or the process cwd), and on `updateOptions` it leaves the
     * current working directory unchanged, rather than resolving the value
     * against the launcher's process cwd. Tool operations resolve against the
     * resulting directory.
     */
    workingDirectory?: 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<WorkingDirectoryContext_2> | WorkingDirectoryContext_2;
    /**
     * 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
     */
    enableManagedSettings?: 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;
    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;
    /**
     * 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 {@link DEFAULT_SESSION_CAPABILITIES}.
     * @see SessionCapability for available capabilities
     */
    sessionCapabilities?: Set<SessionCapability_2>;
    /**
     * 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 (default), resume immediately marks any tool calls or
     * permission requests that were in flight at suspend as interrupted — matching the behaviour of earlier
     * runtime versions. The session resumes in a clean state, and subsequent
     * sends run with no resume-specific code paths active.
     */
    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;
    /**
     * 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;
    /**
     * 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.
     */
    permissionRequestHandler?: (request: PermissionRequest_2) => Promise<PermissionRequestResult_2>;
}

declare type SessionOptionsApi = SessionApi["options"];

declare type SessionPermissionsApi = SessionApi["permissions"];

export declare type SessionPermissionsChangedEvent = WireTypes.SessionPermissionsChangedEvent;

declare interface SessionPermissionsRuntimeState {
    appliedLocationKey?: string;
    appliedLocationRules: Rule[];
    locationApplyQueue: Promise<unknown>;
    /**
     * Resolved directories the last persisted-dir application genuinely added
     * to the live path manager (the primitive's `added` output). This is the
     * candidate removal set for the next location re-key: recording only
     * genuinely inserted entries means the primary, prompt-approved, and
     * flag-provided directories (all dedup-skipped on apply) can never be
     * pruned. Deliberately NOT cleared by resetSessionApprovals: the native
     * reset clears rules only, so the directories survive and must stay
     * prunable.
     */
    appliedLocationDirectories: string[];
}

declare type SessionPlanApi = SessionApi["plan"];

export declare type SessionPlanChangedEvent = WireTypes.SessionPlanChangedEvent;

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>;
}

export declare type SessionRemoteSteerableChangedEvent = WireTypes.SessionRemoteSteerableChangedEvent;

export declare type SessionResumeEvent = WireTypes.SessionResumeEvent;

/**
 * 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 = SessionApi["schedule"] & {
    /**
     * Install (or clear) the CLI-side fallback resolver invoked by the
     * schedule registry's tick path for slash commands that live in the CLI
     * layer (e.g. `/pr`) and so aren't in `getRuntimeSlashCommand`.
     *
     * **In-process structural extra** — only present on local (in-process)
     * sessions, where the schedule namespace is the runtime `Session`'s own
     * object. Remote facades omit it because a resolver closure can't cross
     * the JSON-RPC boundary, so callers must guard on `client.isRemote`
     * before invoking and use optional chaining.
     */
    setCommandResolver?(resolver: ScheduledCommandResolver | undefined): void;
    /**
     * Register a self-paced ("dynamic") schedule directly, bypassing the
     * natural-language cadence parse the `/every` runtime command runs. The
     * first run fires immediately and the model paces subsequent runs via the
     * `manage_schedule` `wakeup` action (see {@link wrapSelfPacedPrompt}).
     *
     * Used by CLI features that already KNOW they want a self-paced loop and
     * supply a fully-formed task prompt (e.g. `/pr auto`), so routing the prompt
     * through the schedule parser — which runs the main model and could misread
     * cadence-like text inside the prompt as a fixed interval — is both wasteful
     * and unsafe.
     *
     * **In-process structural extra** — like {@link setCommandResolver}, only
     * present on local sessions. The registry it drives lives in-process, so
     * remote facades omit it; callers must guard with optional chaining and
     * provide their own fallback for remote/relay sessions.
     */
    addSelfPaced?(prompt: string, options?: {
        displayPrompt?: string;
    }): {
        entry: ScheduleEntry;
    } | {
        error: string;
    };
};

export declare type SessionScheduleCancelledEvent = WireTypes.SessionScheduleCancelledEvent;

export declare type SessionScheduleCreatedEvent = WireTypes.SessionScheduleCreatedEvent;

export declare type SessionScheduleRearmedEvent = WireTypes.SessionScheduleRearmedEvent;

/** 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 {
}

/**
 * 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;
    logger: RunnerLogger;
    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 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;
}

export declare type SessionShutdownData = SessionShutdownEvent["data"];

export declare type SessionShutdownEvent = WireTypes.SessionShutdownEvent;

/** 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"];

export declare type SessionSkillsResolvedEvent = WireTypes.SessionSkillsResolvedEvent;

/** 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;
}

export declare type SessionSnapshotRewindEvent = WireTypes.SessionSnapshotRewindEvent;

/** 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;
};

export declare type SessionStartEvent = WireTypes.SessionStartEvent;

/**
 * Global session store backed by SQLite + FTS5.
 *
 * Lives at `~/.copilot/session-store.db` (shared across all sessions).
 * The store is populated incrementally by live hooks — no background indexing.
 */
declare class SessionStore {
    private handle;
    private readonly dbPath;
    constructor(dbPath: string);
    /**
     * Get the path to the database file.
     */
    getPath(): string;
    /**
     * Insert or update a session's metadata.
     */
    upsertSession(session: SessionRow): void;
    /**
     * Insert a conversation turn and index it for full-text search.
     */
    insertTurn(turn: TurnRow): void;
    /**
     * Insert a compaction checkpoint and index its sections for full-text search.
     */
    insertCheckpoint(checkpoint: CheckpointRow): void;
    /**
     * Record a file touched during a session.
     * Uses INSERT OR IGNORE so the first occurrence wins.
     */
    insertFile(file: FileRow): void;
    /**
     * Record a reference (commit, PR, issue) for a session.
     */
    insertRef(ref: RefRow): void;
    /**
     * Record a Forge trajectory event derived from session tool activity.
     */
    insertForgeTrajectoryEvent(event: ForgeTrajectoryEventRow): void;
    /**
     * Record privacy-minimal usage data for one assistant API call.
     */
    insertAssistantUsageEvent(event: AssistantUsageEventRow): Promise<void>;
    /**
     * Get Forge trajectory events for a session in insertion order.
     */
    getForgeTrajectoryEvents(sessionId: string): Promise<ForgeTrajectoryEventRow[]>;
    /**
     * Get Forge trajectory events across recent sessions matching the provided repository/branch scope.
     */
    getForgeTrajectoryEventsForScope(scope?: ForgeTrajectoryScope): Promise<ForgeTrajectoryEventRow[]>;
    private forgeProposalScopeInput;
    private parseForgeProposalManifest;
    private parseForgeProposalSummary;
    private toForgeProposalRecord;
    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;
    /**
     * Get the dynamic context board for a repository+branch (projection without content).
     */
    getDynamicContextBoard(repository: string, branch: string): Promise<DynamicContextBoardEntry[]>;
    /**
     * Get a single dynamic context item including its full content.
     */
    getDynamicContextItem(repository: string, branch: string, src: string, name: string): DynamicContextItemRow | undefined;
    /**
     * Atomically increment read_count for a specific dynamic context item.
     * Returns true if the item existed and was updated.
     */
    incrementDynamicContextReadCount(repository: string, branch: string, src: string, name: string): boolean;
    /**
     * Atomically increment count for all dynamic context items matching a repository+branch.
     * Called at session start to track how many sessions have loaded this board.
     */
    incrementDynamicContextCount(repository: string, branch: string): void;
    /**
     * Insert a dynamic context item. Returns false if an item with the same
     * (repository, branch, src, name) already exists (no overwrite).
     */
    insertDynamicContextItem(item: DynamicContextItemRow): boolean;
    /**
     * Insert or update a dynamic context item.
     */
    upsertDynamicContextItem(item: DynamicContextItemRow): void;
    /**
     * Delete a dynamic context item. Returns true if an item was deleted, false if not found.
     */
    deleteDynamicContextItem(repository: string, branch: string, src: string, name: string): boolean;
    /**
     * Index a workspace artifact (e.g. plan.md, context files) for full-text search.
     * Content is upserted: subsequent writes to the same file replace the previous index entry.
     */
    indexWorkspaceArtifact(sessionId: string, filePath: string, content: string): Promise<void>;
    /**
     * Full-text search across all indexed content (turns, checkpoint sections, and workspace artifacts).
     * Uses FTS5 MATCH with BM25 ranking.
     *
     * @param query FTS5 query string (supports AND, OR, NOT, phrase "..." etc.)
     * @param limit Maximum results to return (default 20)
     */
    search(query: string, limit?: number): Promise<SearchResult[]>;
    /**
     * Get a session by ID.
     */
    getSession(sessionId: string): SessionRow | undefined;
    /**
     * Get all turns for a session, ordered by turn index.
     */
    getTurns(sessionId: string): TurnRow[];
    /**
     * Get all checkpoints for a session, ordered by checkpoint number.
     */
    getCheckpoints(sessionId: string): CheckpointRow[];
    /**
     * Get all files touched in a session.
     */
    getFiles(sessionId: string): FileRow[];
    /**
     * Get all refs for a session.
     */
    getRefs(sessionId: string): RefRow[];
    /**
     * Execute a raw read-only SQL query against the store.
     * Uses SQLite's authorizer API to enforce read-only access at the engine level,
     * blocking INSERT, UPDATE, DELETE, DROP, CREATE, ATTACH, PRAGMA, etc.
     */
    executeReadOnly<T = Record<string, unknown>>(sql: string): T[];
    /**
     * Async variant of executeReadOnly() that runs the native SQLite query on a
     * blocking thread to avoid stalling the Node main thread during heavier reads.
     */
    executeReadOnlyAsync<T = Record<string, unknown>>(sql: string): Promise<T[]>;
    executeReadOnlyRaw(sql: string): string;
    executeReadOnlyWithCap(sql: string, limit: number): Promise<LocalQueryResult>;
    executeReadOnlyWithCapRaw(sql: string, limit: number): Promise<LocalQueryResultRaw>;
    /**
     * Get the highest turn_index for a session, or -1 if no turns exist.
     */
    getMaxTurnIndex(sessionId: string): number;
    /**
     * Get basic stats about the store.
     */
    getStats(): StoreStats;
    /**
     * Re-index every local session transcript and checkpoint under
     * {@link sessionStatePath} into this store. The walk, parsing, and inserts
     * run entirely in native code over the existing connection as a single
     * transaction; `nowIso` supplies the timestamp for rows the source data
     * leaves unset. Returns the store's aggregate stats.
     *
     * The native call is async: the heavy walk/parse/insert work runs on a
     * blocking thread so the Node main thread (and the CLI render loop) stays
     * responsive for the duration of the reindex.
     */
    reindexLocal(sessionStatePath: string, nowIso: string): Promise<StoreStats>;
    /**
     * Execute a raw SQL statement (e.g., BEGIN, COMMIT, ROLLBACK).
     */
    exec(sql: string): void;
    /**
     * Run a function inside a SQLite transaction (BEGIN/COMMIT/ROLLBACK).
     * All writes are batched into a single atomic commit, which is significantly
     * faster than auto-committing each individual INSERT.
     */
    runInTransaction(fn: () => void): void;
    /**
     * Close the database connection.
     *
     * When `checkpoint` is `true` (the default), runs a WAL checkpoint before
     * closing so that all pending writes are flushed to the main database file
     * and the WAL file is truncated. This is important on Windows where the OS
     * may not release file handles for the `.db-wal` / `.db-shm` files until all
     * dirty pages are written, which can otherwise cause `EPERM` errors when
     * callers delete the database directory immediately after close().
     *
     * Pass `checkpoint: false` on the process-exit / restart path: the checkpoint
     * can take seconds after startup indexing writes a large WAL, and on exit
     * nothing deletes the database directory so it is pure overhead. Committed
     * writes are already recorded as transactions in the WAL (WAL mode); on the
     * next open SQLite recovers and reads them from the WAL (fold-back into the
     * main db happens on a later checkpoint, not on open), so skipping it cannot
     * lose data.
     */
    close(options?: {
        checkpoint?: boolean;
    }): void;
    private ensureHandle;
    private ensureSession;
}

/**
 * Shared identifier for the read-only session-store SQL tool. The tool itself is
 * served from the Rust builtin catalog and surfaced through
 * `createCloudSessionStoreSqlTool` (cloud backend) or `createSqlTool`'s local
 * `session_store` routing. The constant lives here, with the tool that registers
 * under it, and is also consumed by the CLI timeline renderer so they all agree
 * on the tool name.
 */
declare const SessionStoreSqlToolName = "session_store_sql";

/** 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;
}

export declare type SessionTaskCompleteEvent = WireTypes.SessionTaskCompleteEvent;

declare type SessionTasksApi = SessionApi["tasks"];

/**
 * Per-session telemetry service that subscribes to session events and sends telemetry.
 * Each session gets its own SessionTelemetry instance.
 */
declare class SessionTelemetry implements DisposableTelemetrySender {
    private readonly telemetryService;
    private readonly session;
    private readonly unsubscribeEvents;
    private readonly unsubscribeTools;
    private readonly legacyHandler;
    private readonly featureFlagService;
    private readonly stateHandle;
    private disposed;
    private engagementId;
    private tools;
    /** Current working directory context, enriched into all restricted telemetry events */
    private workingDirectoryContext;
    /** Idle timeout after which the engagement ID is rotated (1 hour) */
    static readonly ENGAGEMENT_IDLE_TIMEOUT_MS: number;
    private readonly enableRestrictedTelemetry;
    /** User config for tracking config-file feature toggles */
    private readonly config;
    /** Whether remote was enabled by config settings (not explicit --remote flag) */
    private readonly remoteDefaultedOn;
    /** Whether remote exporting is enabled */
    private readonly remoteExporting;
    /** First launch timestamp, from GlobalState */
    private readonly firstLaunchAt;
    private telemetryFeatureOverrides;
    private sessionCorrelationProperties;
    constructor(telemetryService: TelemetryService, session: LocalSession, options: SessionTelemetryOptions | undefined, featureFlagService: IFeatureFlagService);
    dispose(): void;
    setExtraFeatures(features: Record<string, string>): void;
    setInternalCorrelationIds(internalCorrelationIds: SessionCorrelationIds | undefined): void;
    /** Whether restricted telemetry should be emitted */
    private shouldEmitRestricted;
    /**
     * Send a telemetry event with a simplified interface.
     * This is the preferred way to send telemetry events.
     *
     * When the event has `awaitExpBeforeSend` set, sending is deferred until the
     * ExP response arrives so the event is enriched with experiment assignment
     * context.
     *
     * @param event - The telemetry event to send
     */
    sendTelemetry(event: TelemetryEvent): void;
    /**
     * Defers sending a telemetry event until the ExP response is available.
     */
    private sendTelemetryAfterExp;
    /**
     * Sends a telemetry event immediately without waiting for ExP context.
     */
    private sendTelemetryImmediate;
    /** Options to pass through to the telemetry service with each hydro event */
    private get hydroOptions();
    private getRestrictedRepositoryContext;
    /**
     * Returns the current engagement ID. Used by the parent CLI to
     * forward its engagement to a detached child (rem-agent on shutdown)
     * so the two processes' telemetry rolls up under the same engagement.
     */
    getEngagementId(): string;
    private handleEvent;
    private emitCopilotUserInfoForSessionLifecycle;
    private createPlannerSnapshot;
    private createMemorySnapshot;
}

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 interface SessionTelemetryOptions {
    /** When true, restricted telemetry (model calls, tool calls with PII) is emitted. Defaults to true. */
    enableRestrictedTelemetry?: boolean;
    /** User config file contents, used to track config-file feature toggles in telemetry */
    config?: UserSettings;
    /** Whether remote steering was enabled by default via config settings rather than an explicit --remote flag. */
    remoteDefaultedOn?: boolean;
    /** Whether remote exporting (with or without steering) is enabled for this session. */
    remoteExporting?: boolean;
    /** First launch timestamp, from GlobalState */
    firstLaunchAt?: Date;
    /**
     * Optional engagement ID inherited from a parent session. When set, this
     * SessionTelemetry adopts it instead of generating a fresh UUID, so a
     * detached child run (e.g. shutdown rem-agent) groups under the same
     * engagement as the parent for analytics. Caller is responsible for
     * UUID validation; the value is trusted and used as-is. Mirrors the
     * `detachedFromSpawningParentSessionId` rollup pattern.
     */
    detachedFromSpawningParentEngagementId?: string;
    /** Pre-resolved working directory context to use before lifecycle context events are emitted. */
    initialWorkingDirectoryContext?: WorkingDirectoryContext_2;
}

export declare type SessionTitleChangedEvent = WireTypes.SessionTitleChangedEvent;

export declare type SessionTodosChangedEvent = WireTypes.SessionTodosChangedEvent;

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.
 */
export 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;
}

export declare type SessionToolsUpdatedEvent = WireTypes.SessionToolsUpdatedEvent;

export declare type SessionTruncationEvent = WireTypes.SessionTruncationEvent;

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_2;
    /** 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` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. */
    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;
    /** 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;
    /** 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 (model-defined enum). */
    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;
    /** Shell init profile (`None` or `NonInteractive`). */
    shellInitProfile?: string;
    /** Per-shell process flags (e.g., `pwsh` arguments). */
    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_2;
    /** 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"];

export declare type SessionUsageCheckpointEvent = WireTypes.SessionUsageCheckpointEvent;

export declare type SessionUsageInfoEvent = WireTypes.SessionUsageInfoEvent;

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";

export declare type SessionWarningEvent = WireTypes.SessionWarningEvent;

/** 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"];

export declare type SessionWorkspaceFileChangedEvent = WireTypes.SessionWorkspaceFileChangedEvent;

declare type Settings = {
    api?: {
        copilot?: {
            traceParent?: string;
        };
    };
    github?: {
        serverUrl?: string;
        owner?: {
            name?: string;
        };
        repo?: {
            name?: string;
        };
    };
    job?: {
        nonce?: string;
    };
};

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"];

/**
 * How a tracked shell command is managed.
 * - `"attached"`: The command runs inside a managed PTY shell session. The CLI
 *   owns the process lifetime and can cancel it directly via the session.
 * - `"detached"`: The command was launched as an independent background process
 *   (e.g. with `detach: true`). It survives session shutdown and can only be
 *   killed by PID, which may not be immediately available.
 */
export declare type ShellAttachmentMode = "attached" | "detached";

/** 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 bridge around native immutable shell configuration. Only the
 * script-safety callback stays in TypeScript because it is a live host hook.
 */
declare class ShellConfig {
    private readonly nativeConfig;
    readonly assessScriptSafety: (script: string, cwd: string, onWarning?: (message: string) => void) => Promise<SafetyAssessment>;
    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;
    readonly processFlags: readonly string[];
    static get bash(): ShellConfig;
    static get powerShell(): ShellConfig;
    withScriptSafetyAssessor(assessor: ShellSafetyAssessor): ShellConfig;
    withSandbox(sandbox: SandboxConfig_2): ShellConfig;
    withInitProfile(initProfile: ShellInitProfile): 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?;
    get value(): T | undefined;
    set value(value: T | undefined);
    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;
}

/**
 * Whether a tracked shell command is currently sync-waited or background-managed.
 */
export declare type ShellExecutionMode = "sync" | "background";

export declare type ShellExitContent = WireTypes.ShellExitContent;

/** 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;
}

declare const ShellInitProfile: {
    readonly None: "none";
    readonly NonInteractive: "non-interactive";
};

declare type ShellInitProfile = (typeof ShellInitProfile)[keyof typeof ShellInitProfile];

/** 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;
}

/** 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>;
    /**
     * 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;
};

declare type ShellSafetyAssessor = (shellType: ShellType, script: string, cwd: string, onWarning?: (message: string) => void) => Promise<SafetyAssessment>;

/**
 * A tracked shell command, either attached to a live shell session or detached
 * into an independent background process.
 */
export declare type ShellTask = {
    type: "shell";
    id: string;
    description: string;
    status: BackgroundTaskStatus;
    startedAt: number;
    completedAt?: number;
    command: string;
    attachmentMode: ShellAttachmentMode;
    executionMode: ShellExecutionMode;
    /** Whether the shell is currently in the original sync wait and can be moved to background mode. */
    canPromoteToBackground?: boolean;
    /** Path to the detached shell log, when available. */
    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;
}

/**
 * Progress for a tracked shell command, derived from either live session output
 * (attached shells) or the detached shell log.
 */
export declare type ShellTaskProgress = {
    type: "shell";
    /** Last 10 lines of log file output. */
    recentOutput: string;
    /** Process ID when available. */
    pid?: number;
};

declare type ShellType = NativeShellConfig["shellType"];

declare const shouldWriteToFile: (result: ToolResultExpanded, options?: LargeOutputOptions) => boolean;

/** Aggregate code change metrics for the session */
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;
}

/** 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";
}

/** Per-model shutdown metrics with request counts, token usage, nano-AI units, and token details. */
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 */
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. */
declare interface ShutdownModelMetricTokenDetail {
    /** Accumulated token count for this token type */
    tokenCount: number;
}

/** Token usage breakdown */
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;
}

/** Parameters for the session `shutdown` method (Rust wire contract). Used as
 *  the parameter type on the impl method `Session.shutdownForSchema`. */
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. */
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") */
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 {
    readonly inbox: Inbox;
    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;
    /** Queued main-agent events per sidekick agent name, in occurrence order. */
    private readonly queuedEvents;
    private nextQueuedEventId;
    /**
     * Returns whether any sidekick agents registered during initialization.
     * Awaits initialization so the answer is final.
     */
    hasSidekickAgents(): Promise<boolean>;
    configureInboxPersistence(dbProvider: () => SessionDatabase | undefined): void;
    /** Lists all entries in the sidekick task registry. */
    listTasks(): TaskEntry[];
    /** 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 shouldHandleEvent;
    private queueEvent;
    private buildPromptForQueuedEvents;
    private clearEventsThrough;
    /** Send notification for an inbox entry. */
    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 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: RunnerLogger;
    getDynamicContextConfig?(): LaunchCheckDynamicContextConfig | null;
    getExecutorSettings(): SidekickExecutorSettings | undefined;
    getResponseLimitsStatus?(): ResponseLimitsStatus | undefined;
    getCachedTools(): Tool[];
    getToolConfig(): ToolConfig | undefined;
    isProcessing(): boolean;
    sendSystemNotification(message: string, kind: SystemNotificationKind, options?: {
        passive?: PassivePolicy;
    }): void;
    sendTelemetry(event: TelemetryEvent): void;
    on(eventType: string, handler: (event: SessionEvent) => void): () => void;
    createAgentCallbackBridge(options: {
        agentId: string;
        agentType: "sidekick";
        taskRegistry: TaskRegistry;
    }): IAgentCallback;
    /** Creates a child session for session-based sidekick execution. */
    createSubagentSession?: (agentId: string, options: SubagentSessionOptions) => LocalSession;
};

declare type SidekickExecutorSettings = RuntimeSettings;

/** 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;
    /** 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;
    /** 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 */
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;
}

export declare type SkillInvokedEvent = WireTypes.SkillInvokedEvent;

/** Session event "skill.invoked". Skill invocation details including content, allowed tools, and plugin metadata */
declare interface SkillInvokedEvent_2 {
    /** 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) */
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. */
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";
}

/** A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. */
declare interface SkillsLoadedSkill {
    /** Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field */
    argumentHint?: 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) */
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 */
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";
}

declare type SqlInput = {
    description: string;
    query: string;
    database?: "session" | "session_store";
};

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";

/**
 * Result of a SQL query execution.
 */
declare type SqlResult = SessionFsSqliteResult;

declare const SqlToolName = "sql";

/**
 * The standard (non-`extension_context`) attachment variants. Exported so the
 * extensions push API can compose a *flat* `z.discriminatedUnion` that swaps in
 * a slim `extension_context` input shape. Keeping that union flat (rather than
 * nesting the full attachment union inside another union) ensures the emitted
 * JSON Schema is a single tagged union, which SDK codegen can map to an
 * idiomatic type instead of failing on an unmappable nested `anyOf`.
 */
export declare const standardAttachmentSchemas: readonly [z_2.ZodObject<{
    type: z_2.ZodLiteral<"file">;
    path: z_2.ZodString;
    displayName: z_2.ZodString;
    assetId: z_2.ZodOptional<z_2.ZodString>;
    byteLength: z_2.ZodOptional<z_2.ZodNumber>;
    mimeType: z_2.ZodOptional<z_2.ZodString>;
    omittedReason: z_2.ZodOptional<z_2.ZodEnum<["too_large", "asset_unavailable"]>>;
    taggedFilesEntry: z_2.ZodOptional<z_2.ZodString>;
    lineRange: z_2.ZodOptional<z_2.ZodObject<{
        start: z_2.ZodNumber;
        end: z_2.ZodNumber;
    }, "strip", z_2.ZodTypeAny, {
        end: number;
        start: number;
    }, {
        end: number;
        start: number;
    }>>;
}, "strip", z_2.ZodTypeAny, {
    type: "file";
    path: string;
    displayName: string;
    assetId?: string | undefined;
    byteLength?: number | undefined;
    mimeType?: string | undefined;
    omittedReason?: "too_large" | "asset_unavailable" | undefined;
    taggedFilesEntry?: string | undefined;
    lineRange?: {
        end: number;
        start: number;
    } | undefined;
}, {
    type: "file";
    path: string;
    displayName: string;
    assetId?: string | undefined;
    byteLength?: number | undefined;
    mimeType?: string | undefined;
    omittedReason?: "too_large" | "asset_unavailable" | undefined;
    taggedFilesEntry?: string | undefined;
    lineRange?: {
        end: number;
        start: number;
    } | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"directory">;
    path: z_2.ZodString;
    displayName: z_2.ZodString;
    taggedFilesEntry: z_2.ZodOptional<z_2.ZodString>;
}, "strip", z_2.ZodTypeAny, {
    type: "directory";
    path: string;
    displayName: string;
    taggedFilesEntry?: string | undefined;
}, {
    type: "directory";
    path: string;
    displayName: string;
    taggedFilesEntry?: string | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"selection">;
    filePath: z_2.ZodString;
    displayName: z_2.ZodString;
    text: z_2.ZodString;
    selection: z_2.ZodObject<{
        start: z_2.ZodObject<{
            line: z_2.ZodNumber;
            character: z_2.ZodNumber;
        }, "strip", z_2.ZodTypeAny, {
            line: number;
            character: number;
        }, {
            line: number;
            character: number;
        }>;
        end: z_2.ZodObject<{
            line: z_2.ZodNumber;
            character: z_2.ZodNumber;
        }, "strip", z_2.ZodTypeAny, {
            line: number;
            character: number;
        }, {
            line: number;
            character: number;
        }>;
    }, "strip", z_2.ZodTypeAny, {
        end: {
            line: number;
            character: number;
        };
        start: {
            line: number;
            character: number;
        };
    }, {
        end: {
            line: number;
            character: number;
        };
        start: {
            line: number;
            character: number;
        };
    }>;
}, "strip", z_2.ZodTypeAny, {
    type: "selection";
    text: string;
    filePath: string;
    selection: {
        end: {
            line: number;
            character: number;
        };
        start: {
            line: number;
            character: number;
        };
    };
    displayName: string;
}, {
    type: "selection";
    text: string;
    filePath: string;
    selection: {
        end: {
            line: number;
            character: number;
        };
        start: {
            line: number;
            character: number;
        };
    };
    displayName: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_reference">;
    number: z_2.ZodNumber;
    title: z_2.ZodString;
    referenceType: z_2.ZodEnum<["issue", "pr", "discussion"]>;
    state: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    number: number;
    type: "github_reference";
    url: string;
    title: string;
    referenceType: "issue" | "pr" | "discussion";
    state: string;
}, {
    number: number;
    type: "github_reference";
    url: string;
    title: string;
    referenceType: "issue" | "pr" | "discussion";
    state: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"blob">;
    assetId: z_2.ZodOptional<z_2.ZodString>;
    byteLength: z_2.ZodOptional<z_2.ZodNumber>;
    data: z_2.ZodOptional<z_2.ZodString>;
    mimeType: z_2.ZodString;
    displayName: z_2.ZodOptional<z_2.ZodString>;
    omittedReason: z_2.ZodOptional<z_2.ZodEnum<["too_large", "asset_unavailable"]>>;
}, "strip", z_2.ZodTypeAny, {
    type: "blob";
    mimeType: string;
    data?: string | undefined;
    displayName?: string | undefined;
    assetId?: string | undefined;
    byteLength?: number | undefined;
    omittedReason?: "too_large" | "asset_unavailable" | undefined;
}, {
    type: "blob";
    mimeType: string;
    data?: string | undefined;
    displayName?: string | undefined;
    assetId?: string | undefined;
    byteLength?: number | undefined;
    omittedReason?: "too_large" | "asset_unavailable" | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_commit">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    oid: z_2.ZodString;
    message: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    type: "github_commit";
    message: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    oid: string;
}, {
    type: "github_commit";
    message: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    oid: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_release">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    tagName: z_2.ZodString;
    name: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    name: string;
    type: "github_release";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    tagName: string;
}, {
    name: string;
    type: "github_release";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    tagName: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_actions_job">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    jobId: z_2.ZodNumber;
    jobName: z_2.ZodString;
    workflowName: z_2.ZodString;
    url: z_2.ZodString;
    conclusion: z_2.ZodOptional<z_2.ZodString>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_actions_job";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    jobId: number;
    jobName: string;
    workflowName: string;
    conclusion?: string | undefined;
}, {
    type: "github_actions_job";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    jobId: number;
    jobName: string;
    workflowName: string;
    conclusion?: string | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_repository">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    url: z_2.ZodString;
    description: z_2.ZodOptional<z_2.ZodString>;
    ref: z_2.ZodOptional<z_2.ZodString>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_repository";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    description?: string | undefined;
    ref?: string | undefined;
}, {
    type: "github_repository";
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    description?: string | undefined;
    ref?: string | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_file_diff">;
    url: z_2.ZodString;
    head: z_2.ZodOptional<z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        ref: z_2.ZodString;
        path: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }>>;
    base: z_2.ZodOptional<z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        ref: z_2.ZodString;
        path: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }, {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    }>>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_file_diff";
    url: string;
    head?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
    base?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
}, {
    type: "github_file_diff";
    url: string;
    head?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
    base?: {
        path: string;
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        ref: string;
    } | undefined;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_tree_comparison">;
    url: z_2.ZodString;
    base: z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        revision: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }>;
    head: z_2.ZodObject<{
        repo: z_2.ZodObject<{
            id: z_2.ZodOptional<z_2.ZodNumber>;
            name: z_2.ZodString;
            owner: z_2.ZodString;
        }, "strip", z_2.ZodTypeAny, {
            name: string;
            owner: string;
            id?: number | undefined;
        }, {
            name: string;
            owner: string;
            id?: number | undefined;
        }>;
        revision: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }, {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    }>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_tree_comparison";
    url: string;
    head: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
    base: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
}, {
    type: "github_tree_comparison";
    url: string;
    head: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
    base: {
        repo: {
            name: string;
            owner: string;
            id?: number | undefined;
        };
        revision: string;
    };
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_url">;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    type: "github_url";
    url: string;
}, {
    type: "github_url";
    url: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_file">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    ref: z_2.ZodString;
    path: z_2.ZodString;
    url: z_2.ZodString;
}, "strip", z_2.ZodTypeAny, {
    type: "github_file";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    ref: string;
}, {
    type: "github_file";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    ref: string;
}>, z_2.ZodObject<{
    type: z_2.ZodLiteral<"github_snippet">;
    repo: z_2.ZodObject<{
        id: z_2.ZodOptional<z_2.ZodNumber>;
        name: z_2.ZodString;
        owner: z_2.ZodString;
    }, "strip", z_2.ZodTypeAny, {
        name: string;
        owner: string;
        id?: number | undefined;
    }, {
        name: string;
        owner: string;
        id?: number | undefined;
    }>;
    ref: z_2.ZodString;
    path: z_2.ZodString;
    url: z_2.ZodString;
    lineRange: z_2.ZodObject<{
        start: z_2.ZodNumber;
        end: z_2.ZodNumber;
    }, "strip", z_2.ZodTypeAny, {
        end: number;
        start: number;
    }, {
        end: number;
        start: number;
    }>;
}, "strip", z_2.ZodTypeAny, {
    type: "github_snippet";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    lineRange: {
        end: number;
        start: number;
    };
    ref: string;
}, {
    type: "github_snippet";
    path: string;
    repo: {
        name: string;
        owner: string;
        id?: number | undefined;
    };
    url: string;
    lineRange: {
        end: number;
        start: number;
    };
    ref: string;
}>];

/** Session initialization metadata including context and configuration */
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;
    /** 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";
}

/**
 * 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;
}

/**
 * Sandbox configuration, inferred from the config schema.
 * `enabled` is required at the usage boundary (defaults to false when loading).
 */
declare type StoredSandboxConfig = NonNullable<UserSettings["sandbox"]>;

declare type StoredSandboxUserPolicy = NonNullable<StoredSandboxConfig["userPolicy"]>;

declare type StoreItem = {
    id?: string;
};

declare type StoreStats = {
    sessions: number;
    turns: number;
    checkpoints: number;
    files: number;
    refs: number;
};

declare const str_replace_editor: (config: ToolConfig, logger: RunnerLogger, _settings?: object) => {
    shutdown: () => Promise<TelemetryEvent_2>;
    summariseIntention: (input: unknown) => string;
    callback: (args: unknown, options?: Options_2) => Promise<ToolResultExpanded>;
    safeForTelemetry: boolean;
    name: string;
    namespacedName?: string;
    mcpServerName?: string;
    mcpToolName?: string;
    source: "builtin" | "mcp" | "external";
    title?: string;
    description: string;
    instructions?: string;
    deferLoading?: boolean;
    defer?: "auto" | "never";
    toolType?: "function" | "custom";
    isTerminal?: boolean;
    readOnly?: boolean;
    input_schema?: ToolInputSchema;
    format?: CustomToolInputFormat;
    type?: string;
    _meta?: Record<string, unknown> & {
        ui?: McpUiToolMeta;
    };
};

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;
};

/**
 * Strip model-specific reasoning/encrypted fields from assistant messages.
 * These fields are tied to the originating model and become invalid after
 * a model change, abort, or session resume.
 */
export declare function stripReasoningFields(messages: ChatCompletionMessageParam[]): void;

declare type StrReplaceEditorArgs = PreparedStrReplaceEditorInput;

declare type StrReplaceEditorOptions = {
    truncateBasedOn?: "strLen" | "tokenCount";
    truncateStyle?: "end" | "middle";
};

declare type StrReplaceEditorResult = ToolResultExpanded;

declare const stubAssessScriptSafety: () => Promise<SafetyAssessment>;

/**
 * Runtime-supported models reserved exclusively for trusted built-in subagent integrations
 * (currently the built-in search subagent). They stay in {@link SUPPORTED_MODELS} for normal
 * metadata/capability/request/provider handling, but are **never** user-selectable:
 * - Excluded from the `/model` picker regardless of CAPI's `model_picker_enabled` flag or staff status
 * - Excluded from help text and CLI `--model` choices (see {@link HELP_VISIBLE_MODELS})
 * - Excluded from every externally-returned model list, including the HMAC/non-picker list and the
 *   `models.list` / `session.model.list` / ACP surfaces (`retrieveAvailableModels` filters them from
 *   `models`; they remain in `unfilteredModels` for internal entitlement capture only)
 * - Rejected by top-level model validation/resolution (`--model`, `/model`, config, SDK) in
 *   `validateModelForAuth`
 *
 * TODO: this list is not yet enforced in the `task` tool's custom-agent model selection
 * (`resolveCustomAgentModel`). The built-in search subagent runs as a bespoke search-only agent
 * and does not go through the `task` tool, so nothing currently plumbs `SUBAGENT_ONLY_MODELS`
 * into that path — a custom agent launched via `task` with an explicit `model` set to a
 * subagent-only id would not be rejected today. Wire this list into `resolveCustomAgentModel`
 * if/when subagents can select these models through the `task` tool.
 *
 * Keep in sync with `SUBAGENT_ONLY_MODELS_LIST` in `src/runtime/src/model/catalog.rs`.
 */
export declare const SUBAGENT_ONLY_MODELS: ReadonlySet<string>;

/** Sub-agent completion details for successful execution */
declare interface SubagentCompletedData {
    /** 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;
    /** 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;
}

export declare type SubagentCompletedEvent = WireTypes.SubagentCompletedEvent;

/** Session event "subagent.completed". Sub-agent completion details for successful execution */
declare interface SubagentCompletedEvent_2 {
    /** 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 */
declare interface SubagentDeselectedData {
}

export declare type SubagentDeselectedEvent = WireTypes.SubagentDeselectedEvent;

/** Session event "subagent.deselected". Empty payload; the event signals that the custom agent was deselected, returning to the default agent */
declare interface SubagentDeselectedEvent_2 {
    /** 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 */
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;
}

export declare type SubagentFailedEvent = WireTypes.SubagentFailedEvent;

/** Session event "subagent.failed". Sub-agent failure details including error message and agent information */
declare interface SubagentFailedEvent_2 {
    /** 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 */
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;
}

export declare type SubagentSelectedEvent = WireTypes.SubagentSelectedEvent;

/** Session event "subagent.selected". Custom agent selection details including name and available tools */
declare interface SubagentSelectedEvent_2 {
    /** 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_2>;
    /** 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 and the `ON_DEMAND_INSTRUCTIONS`
     * feature flag to be granted (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;
    /**
     * 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;
    /**
     * 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 */
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;
}

export declare type SubagentStartedEvent = WireTypes.SubagentStartedEvent;

/** Session event "subagent.started". Sub-agent startup details including parent tool call and agent information */
declare interface SubagentStartedEvent_2 {
    /** 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";
}

/**
 * A single entry in a subagent's timeline, derived from bridged events stamped
 * with `agentId == subagent toolCallId` on the parent session. Tool start/complete
 * pairs are collapsed into a single `tool_done` (or `tool_inflight` if no
 * completion has arrived yet).
 */
export declare type SubagentTimelineEntry = {
    /** Discriminator for rendering. */
    kind: SubagentTimelineEntryKind;
    /** Event timestamp in ms since epoch. */
    timestamp: number;
    /** One-line summary for list rendering. */
    summary: string;
    /** Tool name for tool_inflight / tool_done entries. */
    toolName?: string;
    /** Success flag for tool_done entries. */
    success?: boolean;
};

/**
 * Discriminator for {@link SubagentTimelineEntry} render variants.
 */
export declare type SubagentTimelineEntryKind = "assistant" | "tool_inflight" | "tool_done" | "skill" | "lifecycle";

/**
 * Identity-correlation overrides that subagents pass when requesting tools
 * for their own children. The request context carries stable parent ancestry
 * and agent-invocation correlation to provider calls, while the callback attributes
 * nested lifecycle and bridged session events to the child's stable trajectory.
 */
declare type SubAgentToolConfigOverrides = Pick<ToolConfig, "capiRequestContext" | "createSubAgentCallback">;

/**
 * The supplied summariser is a live host callback. Native code owns every
 * deterministic fallback after that callback declines to produce a summary.
 */
declare function summarizeToolCall(toolName: string, args: unknown, tools?: readonly {
    name: string;
    summariseIntention?: (input: unknown) => string;
}[]): string | null;

/**
 * Information about a compaction summary for the index.
 */
declare interface SummaryIndexEntry {
    /** Summary number (1, 2, 3, ...) */
    number: number;
    /** Short title extracted from summary */
    title: string;
    /** Filename (e.g., "001-abc12345.md") */
    filename: string;
}

/**
 * Static list of all supported model IDs.
 *
 * Keep this in sync with `src/runtime/src/model/catalog.rs`. The TypeScript
 * literal is preserved as `as const` so other modules can keep narrowing
 * values to the {@link SupportedModel} union at compile time without loading
 * the native runtime addon at import time.
 *
 * When adding a new model here, also add it to `models_catalog.rs` and
 * consider whether it should be publicly visible. If not (e.g. internal-only
 * or pre-announcement), add it to {@link HIDDEN_MODELS}. If it is reserved
 * exclusively for a trusted built-in subagent and must never be user-selectable,
 * add it to {@link SUBAGENT_ONLY_MODELS} instead.
 */
export declare const SUPPORTED_MODELS: readonly ["claude-sonnet-5", "claude-sonnet-4.6", "claude-sonnet-4.5", "claude-haiku-4.5", "claude-fable-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", "gemini-3.1-pro-preview", "gemini-3.5-flash", "kimi-k2.7-code", "copilot-search-a", "copilot-search-b", "copilot-search-c"];

export declare type SupportedModel = (typeof SUPPORTED_MODELS)[number];

/**
 * Subset of src/types/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 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) => 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 appended after SDK-managed sections.
     */
    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 appended after all sections.
     * Equivalent to append mode's content field — provided for convenience.
     */
    content?: string;
}

/** System/developer instruction content with role and optional template metadata */
declare interface SystemMessageData {
    /** The system or developer prompt text sent as model input */
    content: 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;
}

export declare type SystemMessageEvent = WireTypes.SystemMessageEvent;

/** Session event "system.message". System/developer instruction content with role and optional template metadata */
declare interface SystemMessageEvent_2 {
    /** 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 */
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 */
declare type SystemMessageRole = "system" | "developer";

/** Structured metadata identifying what triggered this notification */
declare type SystemNotification = SystemNotificationAgentCompleted | SystemNotificationAgentIdle | SystemNotificationNewInboxMessage | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted | SystemNotificationInstructionDiscovered;

/** System notification metadata for a background agent that completed or failed, including agent ID, type, status, description, and prompt. */
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 */
declare type SystemNotificationAgentCompletedStatus = "completed" | "failed";

/** System notification metadata for a background agent that became idle, including agent ID, type, and description. */
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 */
declare interface SystemNotificationData {
    /** The notification text, typically wrapped in <system_notification> XML tags */
    content: string;
    /** Structured metadata identifying what triggered this notification */
    kind: SystemNotification;
}

export declare type SystemNotificationEvent = WireTypes.SystemNotificationEvent;

/** Session event "system.notification". System-generated notification for runtime events like background task completion */
declare interface SystemNotificationEvent_2 {
    /** 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 an instruction file discovered during tool access, including source, trigger file, and tool. */
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";
}

export declare type SystemNotificationKind = WireTypes.SystemNotificationKind;

/** System notification metadata for a new inbox message, including entry ID, sender details, and summary. */
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. */
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. */
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";
}

/**
 * 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;
    /** 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 */
declare interface TaskCompleteData {
    /** Whether the tool call succeeded. False when validation failed (e.g., invalid arguments) */
    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";
}

declare const TaskCompleteToolName = "task_complete";

/**
 * Callback invoked when any task completes, fails, or is cancelled.
 */
declare type TaskCompletionCallback = (task: TaskEntry) => void;

/**
 * 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_2;
    /** 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;
    private readonly liveHandles;
    private parentRegistry?;
    private parentAgentId?;
    private readonly childRegistries;
    private readonly pendingPromises;
    /** 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 subAgentLimiter?;
    private readonly agentLimiterSlots;
    constructor();
    private disposed;
    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;
    /** 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;
    /**
     * 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_2 | 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[];
    getServiceTasks(): ServiceTask[];
    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.waitForActiveCommands()` to wait for in-progress
     * shell commands.
     *
     * Resolves immediately if nothing is running.
     */
    waitForAgents(): Promise<void>;
    /**
     * 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;
    }): 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_2;
        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): 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 we also mirror it
     * into `progress.latestIntent` so existing TUI surfaces (which consume the
     * generic intent line) light up without needing MCP-specific awareness.
     */
    updateMcpTask(agentId: string, update: Partial<McpTaskInfo>): 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_2;
        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;
    /**
     * 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;
    /** 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;
}

/** Current lifecycle status of the task */
declare type TaskStatus = "running" | "idle" | "completed" | "failed" | "cancelled";

/**
 * Lifecycle status for a tracked 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>;
};

/** Telemetry emitter function type */
declare type TelemetryEmitter = (event: TelemetryEvent_2) => void;

/**
 * End user wrapper for telemetry events.
 * Used by application code that doesn't need to care which hydro table what information is sent to.
 */
declare interface TelemetryEvent {
    /** 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;
    /**
     * 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;
}

/**
 * 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_2<EventT = string, TelemetryT extends Telemetry = Telemetry> = {
    kind: "telemetry";
    telemetry: EventTelemetry<EventT, TelemetryT>;
};

declare type TelemetryMeasurements = {
    [key: string]: number | undefined;
};

declare type TelemetryProperties = {
    [key: string]: string | undefined;
};

/**
 * Minimal interface for sending telemetry events.
 * Used by components that only need to emit events without depending on the full SessionTelemetry class.
 */
declare interface TelemetrySender {
    sendTelemetry(event: TelemetryEvent): void;
}

declare abstract class TelemetryService {
    readonly authManager?: AuthManager | undefined;
    constructor(authManager?: AuthManager | undefined);
    abstract sendTelemetryEvent(eventName: string, properties?: TelemetryProperties, measurements?: TelemetryMeasurements, tags?: TelemetryTags): void;
    abstract sendHydroEvent(event: HydroEvent, options?: HydroTelemetryOptions): void;
    /** Whether restricted telemetry should be sent for eligible users who have not opted out. */
    abstract shouldSendRestrictedTelemetry(): boolean;
    abstract dispose(): Promise<void> | void;
    /**
     * Override the host-editor attribution (`common_extname` + `editor_version`)
     * applied to legacy `copilot_v0` usage events. Pass `undefined` to clear the
     * override and fall back to the default CLI attribution. Default no-op;
     * implemented by {@link AppInsightsTelemetryService}.
     */
    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.
     *
     * @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, feature flags, and restricted telemetry gate for routing
     */
    sendBagTelemetryEvent(event: TelemetryEvent, hydroFields?: {
        session_id?: string;
        features?: Record<string, string>;
    }, options?: HydroTelemetryOptions): 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;
};

export declare type TerminalContent = WireTypes.TerminalContent;

export declare type TextContent = WireTypes.TextContent;

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 */
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";
}

declare interface TodoEntry {
    content: string;
    status: TodoEntryStatus;
}

declare type TodoEntryStatus = "completed" | "pending" | "in_progress";

/** 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 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";
}

/** 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_2;
    /** 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";
}

/**
 * Token count details for a specific token type.
 */
export declare interface TokenDetails {
    tokenCount: number;
}

/** 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 function toNativeUsageMetrics(metrics: UsageMetrics): {
    nanoAiu: 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_2;
    client?: Client;
    toolOptions?: OptionsT;
    abortSignal?: AbortSignal;
    largeOutputOptions?: LargeOutputOptions;
    repoChangeSet?: RepoChangeSet;
    multiTurnConfig?: {
        registry: TaskRegistry;
        agentId: string;
        onTurnStart?: (message: AgentMessage) => void | Promise<void>;
        formatContinuationPrompt?: (message: AgentMessage) => string;
    };
    taskRegistryAgentId?: string;
    rawArgumentsJson?: string;
};

declare interface ToolChoice {
    mode?: "required" | "auto" | "none";
}

declare type ToolConfig = NativeToolConfig & ToolHostCallbacks & {
    permissions: PermissionsConfig;
    shellConfig?: ShellConfig;
    sandboxConfig?: SandboxConfig_2;
};

declare const toolDeniedWithoutUserRequest: Readonly<DeniedToolResult_2>;

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;

/** 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";
}

/** 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";
}

/** 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";
}

/** The embedded resource contents, either text or base64-encoded binary */
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;
}

/** Icon image for a resource */
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 */
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";
}

/**
 * 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";
}

/** Plain text content block */
declare interface ToolExecutionCompleteContentText {
    /** The text content */
    text: string;
    /** Content block type discriminator */
    type: "text";
}

/** Tool execution completion results including success status, detailed output, and error information */
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;
    /** 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 */
declare interface ToolExecutionCompleteError {
    /** Machine-readable error code */
    code?: string;
    /** Human-readable error message */
    message: string;
}

export declare type ToolExecutionCompleteEvent = WireTypes.ToolExecutionCompleteEvent;

/** Session event "tool.execution_complete". Tool execution completion results including success status, detailed output, and error information */
declare interface ToolExecutionCompleteEvent_2 {
    /** 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 */
declare interface ToolExecutionCompleteResult {
    /** Model-facing binary results (base64 inline or size-omitted markers) sent to the LLM for this tool call */
    binaryResultsForLlm?: PersistedBinaryResult_2[];
    /** 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 */
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 */
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`. */
declare interface ToolExecutionCompleteToolDescriptionMetaUI {
    /** URI of the UI resource */
    resourceUri?: string;
    /** Who can access this tool */
    visibility?: ToolExecutionCompleteToolDescriptionMetaUIVisibility[];
}

/** Allowed values for the `ToolExecutionCompleteToolDescriptionMetaUIVisibility` enumeration. */
declare type ToolExecutionCompleteToolDescriptionMetaUIVisibility = "model" | "app";

/** MCP Apps UI resource content for rendering in a sandboxed iframe */
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) */
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. */
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. */
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. */
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. */
declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsCamera {
    [key: string]: unknown;
}

/** Marker object for clipboard-write permission on an MCP Apps UI resource. */
declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite {
    [key: string]: unknown;
}

/** Marker object for geolocation permission on an MCP Apps UI resource. */
declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation {
    [key: string]: unknown;
}

/** Marker object for microphone permission on an MCP Apps UI resource. */
declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone {
    [key: string]: unknown;
}

declare type ToolExecutionEvent = {
    kind: "tool_execution";
    turn: number;
    callId?: string;
    toolCallId: string;
    toolResult: ToolResultExpanded;
    durationMs: number;
};

/** Streaming tool execution output for incremental result display */
declare interface ToolExecutionPartialData {
    /** Incremental output chunk from the running tool */
    partialOutput: string;
    /** Tool call ID this partial result belongs to */
    toolCallId: string;
}

export declare type ToolExecutionPartialResultEvent = WireTypes.ToolExecutionPartialResultEvent;

/** Session event "tool.execution_partial_result". Streaming tool execution output for incremental result display */
declare interface ToolExecutionPartialResultEvent_2 {
    /** 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 */
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;
}

export declare type ToolExecutionProgressEvent = WireTypes.ToolExecutionProgressEvent;

/** Session event "tool.execution_progress". Tool execution progress notification with status message */
declare interface ToolExecutionProgressEvent_2 {
    /** 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 */
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;
    /** 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;
}

export declare type ToolExecutionStartEvent = WireTypes.ToolExecutionStartEvent;

/** Session event "tool.execution_start". Tool execution startup details including MCP server information when applicable */
declare interface ToolExecutionStartEvent_2 {
    /** 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. */
declare interface ToolExecutionStartShellToolInfo {
    /** 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 */
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 */
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`. */
declare interface ToolExecutionStartToolDescriptionMetaUI {
    /** URI of the UI resource */
    resourceUri?: string;
    /** Who can access this tool */
    visibility?: ToolExecutionStartToolDescriptionMetaUIVisibility[];
}

/** Allowed values for the `ToolExecutionStartToolDescriptionMetaUIVisibility` enumeration. */
declare type ToolExecutionStartToolDescriptionMetaUIVisibility = "model" | "app";

/**
 * Controls how `availableTools` (allowlist) and `excludedTools` (denylist) combine when
 * both are set.
 *
 * - `"available"` (default): if `availableTools` is set, it is the only constraint
 *   that applies — `excludedTools` is ignored. If `availableTools` is unset, `excludedTools`
 *   acts as a denylist. This preserves the historic behaviour of the CLI
 *   `--available-tools` / `--excluded-tools` flags and pre-existing SDK / JSON-RPC clients.
 * - `"excluded"`: a tool is enabled iff it matches the allowlist (or the allowlist
 *   is unset) AND it does not match the denylist. This makes "all except X" expressible
 *   by combining the two lists, e.g. `availableTools=["builtin:*"]`, `excludedTools=["builtin:bash"]`.
 *
 * Callers opt into `"excluded"` explicitly via `SessionOptions.toolFilterPrecedence`;
 * everything else continues to use `"available"`.
 */
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 authoring through the extension host. */
    authorFactoryApi?: AuthorFactoryApi;
    skillDirectories?: string[];
    embeddingRetrievalIndexTypes?: Set<InstructionSource_3>;
    disabledSkills?: Set<string>;
    disabledInstructionSources?: ReadonlySet<string>;
    installedPlugins?: InstalledPlugin[];
    cwd?: string;
    remoteSkills?: Skill_2[];
    loadedSkills?: readonly Skill_2[];
    includedBuiltinAgents?: readonly string[];
    excludedBuiltinAgents?: readonly string[];
    getBuiltinAgentPolicy?: () => {
        includedBuiltinAgents?: readonly string[];
        excludedBuiltinAgents?: readonly string[];
    };
    featureFlags?: FeatureFlags;
    cloudSessionStorageEnabled?: boolean;
    featureFlagService?: IFeatureFlagService;
    lspLanguages?: string[];
    contentExclusionService?: ContentExclusionService;
    getContentExclusionService?: () => ContentExclusionService | undefined;
    fileSnapshotCapture?: FileSnapshotCapture;
    inbox?: Inbox;
    hasSidekickAgents?: () => Promise<boolean>;
    sendInboxPublisher?: SendInboxPublisher;
    dynamicContext?: {
        store: SessionStore;
        repository: string;
        branch: string;
    };
    shellContextGeneration?: number;
    memoryApiCache?: MemoryApiCache;
    lspClientName?: string;
    agentContext?: AgentContext;
    subAgentDepth?: number;
    agentExecutors?: AgentExecutors;
    scheduleApi?: ScheduleApi;
    getLiveSandboxConfig?: () => SandboxConfig_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 `gitAuth`/`ghAuth` 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>;
    onSubagentStop?: (input: {
        sessionId: string;
        transcriptPath: string;
        agentName: string;
        agentDisplayName?: string;
    }) => Promise<{
        decision?: "block" | "allow";
        reason?: 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;
    /**
     * 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_2) => void;
    getSubagentSettings?: () => UserSettings["subagents"];
    getParentModel?: () => string | undefined;
    getParentReasoningEffort?: () => string | undefined;
    getParentContextTier?: () => ContextTier_3 | undefined;
    createSubagentSession?: (agentId: string, options?: SubagentSessionOptions) => LocalSession;
    acquireComplementaryAutoSession?: (parentSessionModel: string) => Promise<{
        model: string;
        sessionToken: string;
    } | undefined>;
    customAgents?: SweCustomAgent[];
    mcpTools?: Tool[];
    externalTools?: Tool[];
    models?: readonly Model[];
    shellContextHolder?: ShellContextHolder<InteractiveShellToolContext>;
    getMcpServerProviderForAgent?: (agentName: string, agentMcpServers: Record<string, MCPServerConfig>) => Promise<McpServerProvider | undefined>;
    sessionFs?: SessionFs;
    taskRegistry?: TaskRegistry;
    taskRegistryAgentId?: string;
    onFileAccessed?: (path: string, tool: string) => Promise<InstructionSource_2[] | undefined>;
    consumePendingSystemNotifications?: (predicate: (kind: SystemNotificationKind) => boolean) => void;
};

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?: BinaryResult[];
    toolTelemetry?: {
        properties?: _TelemetryT["properties"];
        restrictedProperties?: _TelemetryT["restrictedProperties"];
        metrics?: _TelemetryT["metrics"];
    };
    skipLargeOutputProcessing?: boolean;
    newMessages?: Array<{
        content: string;
        source: string;
    }>;
    contents?: ContentBlock[];
    toolReferences?: string[];
    citableSources?: CitableSource[];
    skillInvocation?: SkillInvocation;
    postToolUseFailureHooksProcessed?: boolean;
    uiResource?: McpUiResource;
    mcpMeta?: Record<string, unknown>;
    structuredContent?: unknown;
};

declare namespace tools {
    export {
        isToolResultExpanded,
        buildToolCallbackOptions,
        getGrepToolNameFromTools,
        liveSandboxFromConfig,
        summarizeToolCall,
        AvailableModelInfo,
        SkillInvocationTrigger,
        SkillInvocation,
        ToolResultExpanded,
        ToolResult,
        RejectedToolResult,
        DeniedToolResult,
        BinaryResult,
        RuntimeSettings_2 as RuntimeSettings,
        ToolCallbackOptions,
        ToolCallback,
        ToolShutdown,
        ToolPartialOutputCallback,
        ToolProgressCallback,
        ToolInputSchema,
        CustomToolInputFormat,
        ToolSource,
        ToolMetadata,
        Tool,
        CUSTOM_TOOL_NAMES,
        MemoryApiCache,
        ToolHostCallbacks,
        ToolConfig,
        SubAgentToolConfigOverrides,
        PossiblePath,
        PossibleUrl,
        AssessedCommand,
        SafetyAssessment,
        ShellInitProfile,
        ShellType,
        ShellConfig,
        stubAssessScriptSafety,
        localShellToolName,
        createToolSet,
        createAskUserTool,
        AskUserToolName,
        AUTOPILOT_ASK_USER_RESPONSE,
        AskUserRequest,
        AskUserResponse,
        RequestUserInputFn,
        createCanvasTools,
        isCcaUseTsAutofindEnabled,
        isCodeReviewFeatureEnabled,
        CODE_REVIEW_TOOL_NAME,
        CODE_REVIEW_FF_NAME,
        CODE_REVIEW_DISABLE_FF_NAME,
        CCA_USE_TS_AUTOFIND_FF_NAME,
        createPullRequestTool,
        CREATE_PULL_REQUEST_TOOL_NAME,
        FETCH_DOCUMENTATION_TOOL_NAME,
        fetch_copilot_cli_documentation,
        LargeOutputOptions,
        LARGE_OUTPUT_DISABLED_THRESHOLD_BYTES,
        DEFAULT_LARGE_OUTPUT_THRESHOLD,
        USER_REQUESTED_SHELL_OUTPUT_CONTEXT_MAX_INLINE_BYTES,
        VIEW_TOOL_LARGE_OUTPUT_THRESHOLD,
        VIEW_TOOL_SIZE_HINT,
        isLargeOutputEnabled,
        formatBytes,
        generateLargeOutputMessage,
        shouldWriteToFile,
        writeResultToFile,
        processLargeOutput,
        buildLargeOutputOptions,
        registerTempFile,
        getCreatedTempFiles,
        cleanupTempFiles,
        createLSPTool,
        createLSPRefactorTools,
        getToolDeniedWithoutUserRequest,
        handlePermissionResult,
        alwaysApproveRequestPermissionFn,
        llmToolRejectionMessage,
        toolDeniedWithoutUserRequest,
        PermissionResultMessages,
        HandlePermissionResultOptions,
        REPLY_TO_COMMENT_TOOL_NAME,
        reply_to_comment,
        REPORT_PROGRESS_TOOL_NAME,
        REPORT_PROGRESS_ONLY_PUSH_FEATURE_FLAG,
        reportProgressPushOnlyToolDescription,
        reportProgressLegacyToolDescription,
        report_progress,
        createRunFactoryTool,
        RUN_FACTORY_TOOL_NAME,
        RunFactoryApi,
        getOrCreateCurrent,
        HolderGenerationChangedError,
        HolderTerminatedError,
        ShellContextHolder,
        GenerationalHolder,
        createSqlTool,
        SqlToolName,
        SqlInput,
        createCloudSessionStoreSqlTool,
        SessionStoreSqlToolName,
        CloudSessionStoreSqlInput,
        VIEW_TOOL_NAME,
        INSTRUCTION_DISCOVERY_MESSAGE_SOURCE,
        StrReplaceEditorOptions,
        StrReplaceEditorArgs,
        StrReplaceEditorResult,
        isWriteToFileStrReplaceEditorCommand,
        doesStrReplaceEditorArgsWriteContentInclude,
        isStrReplaceEditorCall,
        getStrReplaceEditorArgsOrNull,
        fileDriverEffects,
        editingTools,
        str_replace_editor,
        isAutopilotContinuationMessage,
        createTaskCompleteTool,
        TaskCompleteToolName,
        AUTOPILOT_CONTINUATION_MESSAGE,
        LARK_AUTOPILOT_CONTINUATION_MESSAGE,
        createToolSearchTool,
        createGenericClientToolSearchTool,
        resolveIsToolSearchEnabled,
        resolveIsBuiltinToolSearchEnabled,
        resolveIsGenericClientToolSearchEnabled,
        markToolsAsDeferred,
        clearAllDeferral,
        visibleToolsForGenericClientSearch,
        toolsForGenericClientSearchHint,
        clearDeferralForAgentTools,
        ToolSearchToolName,
        DEFERRED_TOOLS_THRESHOLD,
        GenericClientToolSearchOptions,
        ToolSearchToolOptions,
        claudeModelSupportsToolSearch,
        gptModelSupportsToolSearch,
        parseTodoCounts,
        parseTodoEntries,
        UpdateTodoToolName,
        TodoEntryStatus,
        TodoEntry,
        updateTodo
    }
}

/** Persisted generic client-side tool activations restored when a session resumes. */
declare interface ToolSearchActivatedData {
    /** Tool-search strategy that activated the definitions. */
    strategy: string;
    /** Names of tool definitions activated by this search invocation. */
    toolNames: string[];
}

export declare type ToolSearchActivatedEvent = WireTypes.ToolSearchActivatedEvent;

/** Session event "tool_search.activated". Persisted generic client-side tool activations restored when a session resumes. */
declare interface ToolSearchActivatedEvent_2 {
    /** 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";
}

declare const ToolSearchToolName = "tool_search_tool";

/** Options accepted by {@link createToolSearchTool}. */
declare interface ToolSearchToolOptions {
    getAllTools: () => ReadonlyArray<ToolMetadata>;
    callback?: ToolCallback;
    /** Consumer metadata; the fixed `tool_search_tool` name is preserved, other fields honored. */
    definition?: {
        description?: string;
        title?: string;
        input_schema?: ToolInputSchema;
    };
}

declare function toolsForGenericClientSearchHint(tools: readonly Tool[], discoveredToolNames: ReadonlySet<string>, searchTool: Tool): Tool[];

/** 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_2 | void> | TelemetryEvent_2 | 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;
}

declare type ToolSource = NativeToolMetadata["source"];

/** Payload of `session.tools_updated` identifying the model whose resolved tools were updated. */
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";
}

/** 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 */
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;
}

export declare type ToolUserRequestedEvent = WireTypes.ToolUserRequestedEvent;

/** Session event "tool.user_requested". User-initiated tool invocation request with tool name and arguments */
declare interface ToolUserRequestedEvent_2 {
    /** 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 function toOptionalNativeLimitsConfig(limits: SessionLimitsConfig_3 | undefined): {
    maxAiCredits: number | undefined;
} | undefined;

/**
 * Converts full Tool objects to lightweight ToolMetadata.
 * Strips non-serializable callback properties (callback, shutdown, summariseIntention)
 * and ensures `source` is populated — defaulting to "builtin" for tools registered
 * without an explicit source. After this point, downstream code can read
 * `tool.source` directly instead of deriving it.
 */
export declare function toToolMetadata(tools: Tool[]): ToolMetadata[];

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 */
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";
}

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;
    /** 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;
}

/** Listener registration shape returned by `Session.on(...)`. */
declare type Unsubscribe = () => void;

export declare type UpdatableSessionOptions = Omit<SessionOptions, "sessionId" | "startTime" | "modifiedTime" | "summary" | "internalCorrelationIds" | "mcpTraceContextResolver" | "otelParentContextResolver" | "remoteDelegate" | "shellNotifier" | "telemetrySender" | "extensionController" | "featureFlagService" | "includedBuiltinAgents" | "hookSessionHandle" | "nativeHookProcessor" | "ownsHookSession"> & {
    /** 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` in this patch as an authoritative cwd change
     * (an explicit intent to rebind: `metadata.setWorkingDirectory` for
     * `/cd`,`/cwd`,`/worktree`, or an SDK resume carrying a caller-supplied
     * `workingDirectory`). Only an authoritative change may move the cwd once
     * one has been claimed; a later NON-authoritative snapshot patch whose
     * `workingDirectory` differs is refused, so a stale full-options snapshot
     * (e.g. the CLI options-sync effect echoing a lagging cwd) cannot silently
     * rewind the runtime working directory. Ignored when the patch carries no
     * `workingDirectory`.
     */
    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 const updateTodo: (_config: ToolConfig) => Tool | undefined;

declare const UpdateTodoToolName = "update_todo";

declare interface UrlManager {
    /**
     * Get all allowed URLs/domains
     */
    getUrls(): string[];
    /**
     * Check if a URL is allowed
     */
    isUrlAllowed(url: string): boolean;
    /**
     * Add a URL or domain to the allowed list
     */
    addUrl(url: string): Promise<void>;
    /**
     * Enable unrestricted mode where all URLs are allowed
     */
    setUnrestrictedMode(value: boolean): void;
    /**
     * Whether unrestricted mode is currently enabled (allows all URLs).
     */
    isUnrestrictedMode(): boolean;
}

/**
 * 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;
    /**
     * 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;
    readonly autoApproval?: AutoApproval;
};

/** Durable session usage checkpoint for reconstructing aggregate accounting on resume */
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";
}

/** Internal prompt-cache expiration state for one model */
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 */
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";
}

/**
 * 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;
};

/**
 * Aggregated usage metrics for a session
 */
export declare interface UsageMetrics {
    totalPremiumRequests: number;
    /** Raw count of user-initiated requests (not multiplied) */
    totalUserRequests: number;
    /** Session-wide accumulated nano-AI units cost. */
    totalNanoAiu: number;
    /** Session-wide token count details per type. */
    tokenDetails: Map<string, TokenDetails>;
    totalApiDurationMs: number;
    sessionStartTime: number;
    codeChanges: CodeChangeMetrics;
    modelMetrics: Map<string, ModelMetrics>;
    currentModel?: string;
    /** Input tokens from the most recent main-agent API call (not accumulated) */
    lastCallInputTokens: number;
    /** Output tokens from the most recent main-agent API call (not accumulated) */
    lastCallOutputTokens: number;
}

/**
 * Overrides for the host-editor fields of legacy `copilot_v0` usage events
 * (`common_extname`, `common_extversion`, and `editor_version`). Used to
 * attribute usage to the editor driving the CLI (e.g. a JetBrains IDE over ACP)
 * instead of the CLI itself in the public Copilot usage-metrics product.
 */
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;
}

/**
 * UsageMetricsTracker maintains usage metrics state and processes session events.
 * This is the core logic used by both the Session class and React hooks.
 */
export declare class UsageMetricsTracker {
    private _metrics;
    private fileEditingToolCallIds;
    private _lastUsageCheckpointTotalNanoAiu;
    constructor(sessionStartTime: Date);
    /**
     * Get the current usage metrics.
     * Returns a shallow copy to prevent external mutation.
     */
    get metrics(): UsageMetrics;
    get lastUsageCheckpointTotalNanoAiu(): number | undefined;
    get modelCacheState(): ModelCacheState[];
    applyCacheActivity(activity: ModelCacheActivity): string | undefined;
    /**
     * Process a session event and update metrics accordingly.
     * Call this for each event emitted by the session.
     */
    processEvent(event: SessionEvent): void;
    private processUsageEvent;
    private accumulateTokenDetails;
    private accumulateCopilotUsage;
    processCompactionTokensUsed(compactionTokensUsed: SessionCompactionCompleteData["compactionTokensUsed"]): void;
    private processCompactionComplete;
    private processShutdown;
    private processUsageCheckpoint;
    private processAssistantMessage;
    /**
     * Overwrite the code-change line/file counts with absolute values.
     *
     * Unlike {@link processToolComplete}, which ACCUMULATES per-edit deltas from
     * local tool telemetry, this SETS the metrics to host-reported absolutes. It
     * exists for relay sessions, where the footer's `+N -N` is sourced from the
     * host's net `SessionSummary.changes` (session-scoped changeset rollup)
     * rather than per-edit telemetry that never round-trips over the relay.
     *
     * Over the relay the bridge is the effective sole writer of `codeChanges`:
     * {@link processToolComplete} can still run because projected
     * `assistant.message` tool requests populate the `fileEditingToolCallIds`
     * gate via {@link processAssistantMessage}. It contributes zero because
     * relay `tool.execution_complete` events carry no `toolTelemetry`, so there
     * is no double-counting.
     *
     * Note: these are NET session-scope counts (matching `/diff`), which diverge
     * from the LOCAL footer's cumulative edit ACTIVITY. This is intentional; see the
     * relay bridge in `relaySession.ts`.
     */
    setCodeChanges(changes: {
        linesAdded: number;
        linesRemoved: number;
        filesCount?: number;
    }): void;
    private processToolComplete;
    /**
     * Reconstruct metrics from a full array of events.
     * Used when initializing from an existing session (e.g., resume).
     */
    static fromEvents(events: readonly SessionEvent[], sessionStartTime: Date): UsageMetricsTracker;
}

declare const USER_REQUESTED_SHELL_OUTPUT_CONTEXT_MAX_INLINE_BYTES: 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_2;
    /** 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;
    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;
};

/** User input request completion with the user's response */
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;
}

export declare type UserInputCompletedEvent = WireTypes.UserInputCompletedEvent;

/** Session event "user_input.completed". User input request completion with the user's response */
declare interface UserInputCompletedEvent_2 {
    /** 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 */
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;
}

export declare type UserInputRequestedEvent = WireTypes.UserInputRequestedEvent;

/** Session event "user_input.requested". User input request notification with question and optional predefined choices */
declare interface UserInputRequestedEvent_2 {
    /** 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";

/** Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. */
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_2[];
    /** 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_2;
    /** 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 (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) */
    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;
}

export declare type UserMessageDelivery = WireTypes.UserMessageDelivery;

/** 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. */
declare type UserMessageDelivery_2 = "idle" | "steering" | "queued";

export declare type UserMessageEvent = WireTypes.UserMessageEvent;

/** Session event "user.message". Payload of `user.message` with displayed and model-transformed content, attachments, source/delivery metadata, mode, and telemetry IDs. */
declare interface UserMessageEvent_2 {
    /** 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_3 = {
    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
     * - `string`: Some other source
     */
    source?: string;
};

declare class UserMessageSentimentTelemetry implements Disposable_2 {
    private readonly session;
    private previousUserMessage;
    private unsubscribe;
    constructor(session: Session);
    private isEnabled;
    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 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;
    readonly autoApproval?: AutoApproval;
};

/**
 * Options accepted by `Session.executeUserRequestedShellCommand`.
 *
 * Lives in its own module (rather than `src/core/session`) so CLI consumers
 * can import the type without violating the
 * `internal/no-direct-session-import-cli` ESLint boundary rule.
 */
declare interface UserRequestedShellCommandOptions {
    abortSignal?: AbortSignal;
}

/** Result of a user-requested shell command. */
declare interface UserRequestedShellCommandResult {
    /** 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;
}

/**
 * Result returned by `Session.executeUserRequestedShellCommand`.
 *
 * Lives in its own module (rather than `src/core/session`) so CLI consumers
 * can import the type without violating the
 * `internal/no-direct-session-import-cli` ESLint boundary rule.
 */
declare interface UserRequestedShellCommandResult_2 {
    toolCallId: string;
    success: boolean;
    output: string;
    exitCode?: number | null;
    error?: string;
}

/**
 * Normalized outcome of *running* a user-requested shell command, before the
 * tool-event envelope wraps it into a {@link UserRequestedShellCommandResult}.
 *
 * Returned by `Session.runUserRequestedShellExecution` (the overridable
 * execution seam) and consumed by `Session.executeUserRequestedShellCommand`,
 * which owns the `tool.user_requested` → `tool.execution_partial_result` →
 * `tool.execution_complete` envelope. Overrides (e.g. the relay's host-terminal
 * driver) supply only this outcome and inherit the shared envelope.
 */
declare interface UserRequestedShellExecution {
    /** Whether the command completed with a success (zero) exit status. */
    success: boolean;
    /** Cleaned command output as surfaced to the user. */
    output: string;
    /** Exit code when the command actually ran (number, including non-zero), or null when it never ran. */
    exitCode: number | null;
    /** Failure message; present when {@link success} is false. */
    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;
    respectGitignore?: boolean;
    proxyKerberosServicePrincipal?: string;
    builtInAgents?: {
        rubberDuck?: boolean;
        rubberDuckAutoInvoke?: boolean;
        [key: string]: unknown;
    };
    memory?: boolean;
    toolSearch?: boolean;
    model?: string;
    effortLevel?: string;
    contextTier?: "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 false.
     */
    stayInAutopilot?: boolean;
    /**
     * When true, typing a lone `$` at the prompt hands the terminal to an
     * interactive shell rooted at the session working directory (a shell-out,
     * restored on `exit`). Only ever activates for a local, trusted, idle
     * session on a real TTY. User/managed-scoped only (not repo-overridable).
     * Defaults to false.
     */
    shellShortcut?: 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.
     * Defaults to true.
     */
    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;
    };
    remoteExport?: boolean;
    statusLine?: {
        type?: "command";
        command?: string;
        padding?: 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;
        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;
        gitAuth?: boolean;
        ghAuth?: 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?: {
        disableBypassPermissionsMode?: string;
        [key: string]: unknown;
    };
    /** 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;
    disableAllHooks?: boolean;
    hooks?: Record<string, unknown>;
    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 (`writeRawAtomic`):
     *   - 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 | 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 */
declare type UserToolSessionApproval = UserToolSessionApprovalCommands | UserToolSessionApprovalRead | UserToolSessionApprovalWrite | UserToolSessionApprovalMcp | UserToolSessionApprovalMemory | UserToolSessionApprovalCustomTool | UserToolSessionApprovalExtensionManagement | 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 | UserToolSessionApprovalExtensionPermissionAccess_2;

/** Session-scoped tool-approval rule for specific shell command identifiers. */
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. */
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. */
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. */
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 tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null. */
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. */
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. */
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. */
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;
    /** 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";
} | {
    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") */
declare type Verbosity = "low" | "medium" | "high";

/** Output verbosity level for supported models */
declare type Verbosity_2 = "low" | "medium" | "high";

/**
 * Output verbosity level for supported models.
 */
declare type Verbosity_3 = (typeof VERBOSITY_LEVELS)[number];

/**
 * Output verbosity level for supported models.
 * Controls answer detail/length independently from reasoning effort.
 */
declare const VERBOSITY_LEVELS: readonly ["low", "medium", "high"];

declare const VIEW_TOOL_LARGE_OUTPUT_THRESHOLD: number;

declare const VIEW_TOOL_NAME = "view";

declare const VIEW_TOOL_SIZE_HINT: string;

/** 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;
}

declare function visibleToolsForGenericClientSearch(tools: readonly Tool[], discoveredToolNames: ReadonlySet<string>, searchTool: Tool): Tool[];

/** Warning message for timeline display with categorization */
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";
}

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];

declare namespace WireTypes {
    export {
        SessionEventType_2 as SessionEventType,
        ExternalToolCompletion_2 as ExternalToolCompletion,
        AbortEvent_2 as AbortEvent,
        AbortReason_3 as AbortReason,
        UserMessageAgentMode as AgentMode,
        AssistantIdleEvent_2 as AssistantIdleEvent,
        AssistantIntentEvent_2 as AssistantIntentEvent,
        AssistantMessageDeltaEvent_2 as AssistantMessageDeltaEvent,
        AssistantMessageEvent_2 as AssistantMessageEvent,
        AssistantMessageStartEvent_2 as AssistantMessageStartEvent,
        AssistantReasoningDeltaEvent_2 as AssistantReasoningDeltaEvent,
        AssistantReasoningEvent_2 as AssistantReasoningEvent,
        AssistantServerToolProgressEvent_2 as AssistantServerToolProgressEvent,
        AssistantStreamingDeltaEvent_2 as AssistantStreamingDeltaEvent,
        AssistantToolCallDeltaEvent_2 as AssistantToolCallDeltaEvent,
        AssistantTurnEndEvent_2 as AssistantTurnEndEvent,
        AssistantTurnRetryEvent,
        AssistantTurnStartEvent_2 as AssistantTurnStartEvent,
        AssistantUsageEvent_2 as AssistantUsageEvent,
        Attachment_2 as Attachment,
        ModelCallStartEvent,
        ToolExecutionCompleteContentAudio as AudioContent,
        AutoModeResolvedEvent_2 as AutoModeResolvedEvent,
        AutoModeResolvedData_2 as AutoModeResolvedData,
        AutoModeSwitchCompletedEvent_2 as AutoModeSwitchCompletedEvent,
        AutoModeSwitchRequestedEvent_2 as AutoModeSwitchRequestedEvent,
        BinaryAssetReference_2 as BinaryAssetReference,
        AttachmentBlob as BlobAttachment,
        CapabilitiesChangedEvent_2 as CapabilitiesChangedEvent,
        CommandCompletedEvent_2 as CommandCompletedEvent,
        CommandExecuteEvent_2 as CommandExecuteEvent,
        CommandQueuedEvent_2 as CommandQueuedEvent,
        ToolExecutionCompleteContent as ContentBlock,
        CustomNotificationData_2 as CustomNotificationData,
        CustomNotificationEvent_2 as CustomNotificationEvent,
        AttachmentDirectory as DirectoryAttachment,
        ElicitationCompletedEvent_2 as ElicitationCompletedEvent,
        ElicitationRequestedEvent_2 as ElicitationRequestedEvent,
        ToolExecutionCompleteContentResource as EmbeddedResource,
        ExitPlanModeCompletedEvent_2 as ExitPlanModeCompletedEvent,
        ExitPlanModeRequestedEvent_2 as ExitPlanModeRequestedEvent,
        AttachmentExtensionContext as ExtensionContextAttachment,
        ExternalToolCompletedEvent_2 as ExternalToolCompletedEvent,
        ExternalToolRequestedEvent_2 as ExternalToolRequestedEvent,
        AttachmentFile as FileAttachment,
        AttachmentGitHubActionsJob as GitHubActionsJobAttachment,
        AttachmentGitHubCommit as GitHubCommitAttachment,
        AttachmentGitHubFile as GitHubFileAttachment,
        AttachmentGitHubFileDiff as GitHubFileDiffAttachment,
        AttachmentGitHubReference as GitHubReferenceAttachment,
        AttachmentGitHubRelease as GitHubReleaseAttachment,
        AttachmentGitHubRepository as GitHubRepositoryAttachment,
        AttachmentGitHubSnippet as GitHubSnippetAttachment,
        AttachmentGitHubTreeComparison as GitHubTreeComparisonAttachment,
        AttachmentGitHubUrl as GitHubUrlAttachment,
        HookEndEvent_2 as HookEndEvent,
        HookProgressEvent_2 as HookProgressEvent,
        HookStartEvent_2 as HookStartEvent,
        ToolExecutionCompleteContentImage as ImageContent,
        ManagedSettingsEnforcedEvent_2 as ManagedSettingsEnforcedEvent,
        ManagedSettingsEnforcedData_2 as ManagedSettingsEnforcedData,
        ManagedSettingsEnforcedAction_2 as ManagedSettingsEnforcedAction,
        ManagedSettingsEnforcedEscalation_2 as ManagedSettingsEnforcedEscalation,
        ManagedSettingsResolvedEvent_2 as ManagedSettingsResolvedEvent,
        ManagedSettingsResolvedData_2 as ManagedSettingsResolvedData,
        ManagedSettingsResolvedSource_2 as ManagedSettingsResolvedSource,
        McpAppToolCallCompleteEvent_2 as McpAppToolCallCompleteEvent,
        McpHeadersRefreshCompletedEvent_2 as McpHeadersRefreshCompletedEvent,
        McpHeadersRefreshRequiredEvent_2 as McpHeadersRefreshRequiredEvent,
        McpOauthCompletedEvent as McpOAuthCompletedEvent,
        McpOauthRequiredEvent as McpOAuthRequestedEvent,
        McpPromptsListChangedEvent_2 as McpPromptsListChangedEvent,
        McpResourcesListChangedEvent_2 as McpResourcesListChangedEvent,
        McpToolsListChangedEvent_2 as McpToolsListChangedEvent,
        ModelCallFailureEvent as ModelCallFailureSessionEvent,
        ModelCallFailureSource_2 as ModelCallFailureSource,
        OmittedBinaryResult_2 as OmittedBinaryResult,
        PendingMessagesModifiedEvent_2 as PendingMessagesModifiedEvent,
        PermissionCompletedEvent_2 as PermissionCompletedEvent,
        PermissionRequestedEvent_2 as PermissionRequestedEvent,
        PersistedBinaryResult_2 as PersistedBinaryResult,
        ToolExecutionCompleteContentResourceLink as ResourceLink,
        ToolExecutionCompleteContentShellExit as ShellExitContent,
        SamplingCompletedEvent_2 as SamplingCompletedEvent,
        SamplingRequestedEvent_2 as SamplingRequestedEvent,
        CommandsChangedEvent as SdkCommandsChangedEvent,
        AttachmentSelection as SelectionAttachment,
        AutopilotObjectiveChangedEvent as SessionAutopilotObjectiveChangedEvent,
        BackgroundTasksChangedEvent as SessionBackgroundTasksChangedEvent,
        BinaryAssetEvent as SessionBinaryAssetEvent,
        CanvasClosedEvent as SessionCanvasClosedEvent,
        CanvasOpenedEvent as SessionCanvasOpenedEvent,
        CanvasRegistryChangedEvent as SessionCanvasRegistryChangedEvent,
        CompactionCompleteData as SessionCompactionCompleteData,
        CompactionCompleteEvent as SessionCompactionCompleteEvent,
        CompactionStartEvent as SessionCompactionStartEvent,
        ContextChangedEvent as SessionContextChangedEvent,
        CustomAgentsUpdatedEvent as SessionCustomAgentsUpdatedEvent,
        ErrorEvent_2 as SessionErrorEvent,
        SessionEvent_2 as SessionEvent,
        ExtensionsAttachmentsPushedEvent as SessionExtensionsAttachmentsPushedEvent,
        ExtensionsLoadedEvent as SessionExtensionsLoadedEvent,
        HandoffEvent as SessionHandoffEvent,
        IdleEvent as SessionIdleEvent,
        InfoEvent as SessionInfoEvent,
        McpServersLoadedEvent as SessionMcpServersResolvedEvent,
        McpServerStatusChangedEvent as SessionMcpServerStatusChangedEvent,
        MemoryChangedEvent as SessionMemoryChangedEvent,
        SessionMode_3 as SessionMode,
        ModeChangedEvent as SessionModeChangedEvent,
        ModelChangeEvent as SessionModelChangeEvent,
        PermissionsChangedEvent as SessionPermissionsChangedEvent,
        PlanChangedEvent as SessionPlanChangedEvent,
        RemoteSteerableChangedEvent as SessionRemoteSteerableChangedEvent,
        ResumeEvent as SessionResumeEvent,
        ScheduleCancelledEvent as SessionScheduleCancelledEvent,
        ScheduleCreatedEvent as SessionScheduleCreatedEvent,
        ScheduleRearmedEvent as SessionScheduleRearmedEvent,
        ShutdownData as SessionShutdownData,
        ShutdownEvent as SessionShutdownEvent,
        SkillsLoadedEvent as SessionSkillsResolvedEvent,
        SnapshotRewindEvent as SessionSnapshotRewindEvent,
        StartEvent as SessionStartEvent,
        TaskCompleteEvent as SessionTaskCompleteEvent,
        TitleChangedEvent as SessionTitleChangedEvent,
        TodosChangedEvent as SessionTodosChangedEvent,
        ToolsUpdatedEvent as SessionToolsUpdatedEvent,
        TruncationEvent as SessionTruncationEvent,
        UsageCheckpointEvent as SessionUsageCheckpointEvent,
        UsageInfoEvent as SessionUsageInfoEvent,
        WarningEvent as SessionWarningEvent,
        WorkspaceFileChangedEvent as SessionWorkspaceFileChangedEvent,
        SkillInvokedEvent_2 as SkillInvokedEvent,
        SubagentCompletedEvent_2 as SubagentCompletedEvent,
        SubagentDeselectedEvent_2 as SubagentDeselectedEvent,
        SubagentFailedEvent_2 as SubagentFailedEvent,
        SubagentSelectedEvent_2 as SubagentSelectedEvent,
        SubagentStartedEvent_2 as SubagentStartedEvent,
        SystemMessageEvent_2 as SystemMessageEvent,
        SystemNotificationEvent_2 as SystemNotificationEvent,
        SystemNotification as SystemNotificationKind,
        ToolExecutionCompleteContentTerminal as TerminalContent,
        ToolExecutionCompleteContentText as TextContent,
        ToolExecutionCompleteEvent_2 as ToolExecutionCompleteEvent,
        ToolSearchActivatedEvent_2 as ToolSearchActivatedEvent,
        ToolExecutionPartialResultEvent_2 as ToolExecutionPartialResultEvent,
        ToolExecutionProgressEvent_2 as ToolExecutionProgressEvent,
        ToolExecutionStartEvent_2 as ToolExecutionStartEvent,
        ToolUserRequestedEvent_2 as ToolUserRequestedEvent,
        UserInputCompletedEvent_2 as UserInputCompletedEvent,
        UserInputRequestedEvent_2 as UserInputRequestedEvent,
        UserMessageEvent_2 as UserMessageEvent,
        UserMessageDelivery_2 as UserMessageDelivery,
        ExternalToolTextResultForLlmBinaryResultsForLlm as BinaryResult,
        ExternalToolResult_2 as ExternalToolResult
    }
}

/** Working directory and git context at session start */
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;
    /** 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;
}

declare type WorkingDirectoryContext_2 = RuntimeNative.GitWorkingDirectoryContext;

/** Hosting platform type of the repository (github or ado) */
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;
}

/**
 * Log message prefix emitted when a session workspace is initialized.
 * Debug log collection uses this marker to identify which process log files
 * belong to a given session, so changes here must stay in sync with the
 * runtime collector.
 */
export declare const WORKSPACE_INITIALIZED_LOG_PREFIX = "Workspace initialized:";

/**
 * Working directory context for workspace creation/update.
 *
 * Mirrors the Rust `WorkspaceContextInput` struct used by the native
 * orchestration layer; the TS shim sends this via `JSON.stringify`.
 */
declare interface WorkspaceContext {
    cwd?: string;
    gitRoot?: string;
    repository?: string;
    hostType?: "github" | "ado";
    branch?: string;
    clientName?: string;
}

/**
 * Information about the current workspace for context injection into prompts.
 */
declare interface WorkspaceContextInfo {
    /** Name of the workspace (for display) */
    name?: string;
    /** Path to the workspace directory */
    workspacePath: string;
    /** Number of prior session summaries */
    summaryCount: number;
    /** Whether a plan.md file exists */
    hasPlan: boolean;
    /** List of files in the files/ directory (if any) */
    filesInWorkspace?: string[];
    /** List of checkpoints with their titles */
    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. */
    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 a requested branch diff fell back to unstaged changes because branch diff failed. */
    isFallback: boolean;
    /** Effective mode used for the returned changes. */
    mode: WorkspaceDiffMode;
    /** Diff mode requested by the client. */
    requestedMode: WorkspaceDiffMode;
}

/** Workspace file change details including path and operation type */
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";
}

/** Whether the file was newly created or updated */
declare type WorkspaceFileChangedOperation = "create" | "update";

/**
 * Per-session workspace manager backed by SessionFs.
 *
 * This class is a thin TypeScript shim over the Rust workspace manager
 * implementation in `src/runtime/src/workspace/manager.rs`. Every async
 * method forwards to a `nativeRuntime.workspaceManager*` napi binding,
 * which performs all filesystem orchestration through a Rust-side
 * `SessionFsDispatch` (either tokio::fs for `LocalSessionFs` or a reverse
 * call into the JS handler for `RpcSessionFs`). Per-session creation
 * mutexes also live in Rust, so this class holds no state beyond the
 * `sessionId` / `sessionFs` pair it was constructed with.
 *
 * Cross-session operations (listing, deleting, pruning workspaces) belong
 * in {@link LocalWorkspaceStore}, not here — SessionFs is scoped to one
 * session and cannot access other sessions' storage.
 *
 * Storage layout (relative to sessionStatePath):
 * ├── workspace.yaml             # Metadata: id, owner, repo, name, summary_count
 * ├── plan.md                    # Optional implementation plan
 * ├── autopilot-objective.json   # Optional machine-managed autopilot objective state
 * ├── checkpoints/
 * │   ├── index.md               # Checkpoint listing/index
 * │   ├── 001-{short-title}.md   # Compaction checkpoints
 * │   └── ...
 * └── files/                     # User-specified persistent files
 */
declare class WorkspaceManager {
    readonly sessionId: string;
    private readonly sessionFs;
    constructor(sessionId: string, sessionFs: SessionFs);
    /** Root directory for this session's workspace (same as sessionStatePath). */
    getWorkspacePath(): string;
    /** Path to plan.md file. */
    getPlanPath(): string;
    /** Path to the machine-managed autopilot objective state file. */
    getAutopilotObjectivePath(): string;
    /** Path to workspace database file. */
    getDatabasePath(): string;
    private get sessionStatePath();
    private get convention();
    private get handler();
    /** Check if a workspace exists. */
    workspaceExists(): Promise<boolean>;
    /**
     * Load workspace metadata from storage. Returns null if the workspace
     * doesn't exist.
     */
    loadWorkspace(): Promise<Workspace | null>;
    /**
     * Save workspace metadata to storage. Creates parent directories if they
     * don't exist.
     */
    saveWorkspace(workspace: Workspace): Promise<void>;
    /**
     * Create a new workspace for this session.
     * The workspace ID equals the session ID (1:1 mapping).
     */
    createWorkspace(context: WorkspaceContext | undefined, name: string | undefined): Promise<Workspace>;
    /**
     * Get or create a workspace for this session. Uses a Rust-side per-session
     * mutex to prevent race conditions when multiple callers try to create
     * simultaneously.
     *
     * Note: the load/create-or-return orchestration and per-session mutex
     * both live in Rust, so the TS facade only validates the returned shape.
     */
    getOrCreateWorkspace(context: WorkspaceContext | undefined, name: string | undefined): Promise<Workspace>;
    /**
     * Update the context for a workspace, creating it if it doesn't exist yet.
     * Called on session start/resume to update the cwd, repo, branch.
     * Fields not present in the new context are cleared (e.g., moving out of a git repo).
     */
    updateContext(context: WorkspaceContext, name?: string): Promise<void>;
    /**
     * Update the auto-generated name for an existing workspace.
     * Has no effect when the user has manually named the session (user_named=true).
     */
    updateSummary(summary: string): Promise<void>;
    /** Rename the session (set custom name). */
    renameSession(name: string): Promise<void>;
    /**
     * Update arbitrary fields on this session's workspace.
     * Creates the workspace if it doesn't exist yet.
     */
    updateWorkspaceFields(fields: Partial<Workspace>): Promise<void>;
    /** Delete the workspace and its directory. */
    deleteWorkspace(): Promise<void>;
    /**
     * Add a compaction summary to the workspace.
     * Called when CompactionProcessor completes.
     *
     * @returns The summary number assigned and the path to the checkpoint file
     */
    addSummary(summaryContent: string, title: string): Promise<{
        number: number;
        path: string;
    }>;
    /**
     * Truncate compaction summaries/checkpoints to a specific count.
     * Removes checkpoint files and updates index + workspace summary_count.
     */
    truncateSummaries(keepCount: number): Promise<void>;
    /** Load the checkpoint index entries from the index.md file. */
    listCheckpoints(): Promise<SummaryIndexEntry[]>;
    /** Read a specific checkpoint by number. */
    readCheckpoint(checkpointNumber: number): Promise<string | null>;
    /** Read the plan content for this workspace. */
    readPlan(): Promise<string | null>;
    /** Write plan content for this workspace. */
    writePlan(content: string): Promise<void>;
    /** Delete the plan file for this workspace. */
    deletePlan(): Promise<void>;
    /** Check if a plan exists for this workspace. */
    planExists(): Promise<boolean>;
    /** Read the machine-managed autopilot objective state for this workspace. */
    readAutopilotObjective(): Promise<string | null>;
    /** Atomically write machine-managed autopilot objective state for this workspace. */
    writeAutopilotObjective(content: string): Promise<"create" | "update">;
    /** Delete the machine-managed autopilot objective state for this workspace. */
    deleteAutopilotObjective(): Promise<boolean>;
    /** Check if an autopilot objective state file exists for this workspace. */
    autopilotObjectiveExists(): Promise<boolean>;
    /** List files in the workspace's files directory. */
    listFiles(): Promise<string[]>;
    /**
     * Read a file from the workspace files directory.
     * @param filePath - Relative path within the files directory
     */
    readWorkspaceFile(filePath: string): Promise<string>;
    /**
     * Write a file to the workspace files directory.
     * @param filePath - Relative path within the files directory
     * @param content - File content to write
     * @returns Whether the file already existed ("update") or is new ("create")
     */
    writeWorkspaceFile(filePath: string, content: string): Promise<"create" | "update">;
    /**
     * Save large paste content to a unique file in the files directory.
     * @returns The absolute file path within SessionFs, filename, and size
     */
    saveLargePaste(content: string): Promise<{
        filePath: string;
        filename: string;
        sizeBytes: number;
    }>;
}

/** 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;
}

/** 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;
}

/** 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[];
}

/** 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;
}

/** 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";

/** Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. */
declare type WorkspacesWorkspaceDetailsHostType = "github" | "ado";

/**
 * 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;
    readonly autoApproval?: AutoApproval;
};

declare const writeResultToFile: (result: ToolResultExpanded, options: LargeOutputOptions) => Promise<ToolResultExpanded>;

export { }
