import type { CreateMessageResultWithTools as CreateMessageResultWithTools_2 } from '@modelcontextprotocol/sdk/types.js'; import type { NativeProcessorHook } from './sharedApi/runtime-generated'; import type { NativeProcessorLogMessage } from './sharedApi/runtime-generated'; import type { NativeProcessorRunEnv } from './sharedApi/runtime-generated'; import type * as RuntimeNative from '../sharedApi/runtime-generated'; import type { SessionFsReverseCall } from '../sharedApi/runtime-generated'; import * as stream from 'stream'; import * as z from 'zod'; import { z 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; } /** Schema for the `AccountAllUsers` type. */ 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; } /** 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; } /** Schema for the `AccountQuotaSnapshot` type. */ 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; /** * Resolved Anthropic adaptive-thinking capability for a model. This is the * runtime's own abstraction over CAPI's single boolean wire field plus the * programmatic capability-default switch. */ declare type AdaptiveThinkingSupport = "unsupported" | "optional" | "required"; /** Resolved Anthropic adaptive-thinking capability for a model. */ declare type AdaptiveThinkingSupport_2 = "unsupported" | "optional" | "required"; declare type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise; declare type AgentAction = (typeof AgentActions)[number]; declare const AgentActions: readonly ["fix", "fix-pr-comment", "task"]; declare type AgentCallbackCheckQuotaEvent = Record; 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"; /** Schema for the `AgentDiscoveryPath` type. */ 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; }) => Promise; /** Shuts down all cached agent contexts. */ shutdown: () => Promise; } /** 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; } declare type AgentHook = IPreCommitHook | IPreEditsHook | IPostEditHook | IPostResultHook | IPrePRDescriptionHook; declare type AgentIdBag = { /** * The ID of the agent whose invocation generated the object this bag is attached to. */ agentId?: string; }; /** Schema for the `AgentInfo` type. */ 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; /** 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; restrictedProperties?: Record; metrics?: Record; }; /** * MCP-task-specific data when this agent represents an MCP task created * via `tools/call` with task augmentation. Absent for normal subagents. */ mcpTask?: McpTaskInfo; } /** 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[]; } export declare type AgentStopHook = Hook; /** * Agent stop hook types - fires when the agent naturally stops (no more tool calls) */ export declare interface AgentStopHookInput extends BaseHookInput { transcriptPath: string; /** * The reason the agent stopped. Currently only "end_turn" is supported. * Matches Claude Code terminology; extensible for future stop reasons. */ stopReason: "end_turn"; } export declare interface AgentStopHookOutput { /** If "block", the agent will continue with another turn using the reason. Undefined means "allow". */ decision?: HookBlockDecision; reason?: 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; /** 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; /** 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"; export declare function aggregateFailureContexts(contexts: string[]): string; /** * Aggregate `additionalContext` strings returned by successful-path postToolUse hooks. * Strings are joined with `\n\n` in registration order. The result is capped at * {@link MAX_POST_TOOL_USE_CONTEXT_LENGTH} characters; truncation is hard (slice + trimEnd). */ export declare function aggregatePostToolUseContexts(contexts: string[]): string; declare type AllModels = (string & {}) | ChatModel | "o1-pro" | "o1-pro-2025-03-19" | "o3-pro" | "o3-pro-2025-06-10" | "o3-deep-research" | "o3-deep-research-2025-06-26" | "o4-mini-deep-research" | "o4-mini-deep-research-2025-06-26" | "computer-use-preview" | "computer-use-preview-2025-03-11"; /** Indicates whether the operation succeeded and reports the post-mutation state. */ declare interface AllowAllPermissionSetResult { /** Authoritative allow-all state after the mutation */ enabled: boolean; /** Whether the operation succeeded */ success: boolean; } /** Current full allow-all permission state. */ declare interface AllowAllPermissionState { /** Whether full allow-all permissions are currently active */ enabled: boolean; } /** * 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; }; /** Schema for the `ApiKeyAuthInfo` type. */ 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"; } /** * Append a labelled block of `additionalContext` from postToolUse hooks onto the * tool's `textResultForLlm`. Mirrors {@link appendPostToolUseFailureContext} so the * LLM has a structural hint that the trailing text is hook-supplied guidance, * not part of the tool's own output. */ export declare function appendPostToolUseContext(baseContent: string, hookContext: string | undefined, toolName?: string): string; export declare function appendPostToolUseFailureContext(baseContent: string, failureHookContext: string | undefined, toolName?: string): string; /** 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; private updateCopilotUser; /** Creates new telemetry queues with the given endpoint URL and drains pending events. */ private updateQueues; private emitPendingBufferOverflowDiagnostic; private getTags; private createHostSnapshot; } /** * Request to ask the user a question. */ declare type AskUserRequest = { /** The question to ask the user */ question: string; /** Optional choices for multiple choice questions */ choices?: string[]; /** Whether to allow freeform text input (default: true) */ allowFreeform?: boolean; /** The LLM-assigned tool call ID, threaded from the tool execution context */ toolCallId?: string; }; /** * Response from the user to an ask_user request. */ declare type AskUserResponse = { /** The user's answer (selected choice or freeform text) */ answer: string; /** Whether the answer was freeform text vs a selected choice */ wasFreeform: boolean; /** Whether the user dismissed the prompt without answering */ dismissed?: boolean; }; declare const AskUserToolName = "ask_user"; /** * An assessed command, with its identifier and whether it is read-only. */ declare type AssessedCommand = { /** * The command identifier, e.g. "rm" or "git push". */ readonly identifier: string; /** * Whether the command is read-only (i.e. does not modify state). */ 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; /** 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 */ 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 */ 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; /** * 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; 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"; } /** 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"; } /** Turn completion metadata including the turn identifier */ declare interface AssistantTurnEndData { /** 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"; } /** Turn initialization metadata including identifier and interaction tracking */ declare interface AssistantTurnStartData { /** CAPI interaction ID for correlating this turn with upstream telemetry */ interactionId?: 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; /** 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 */ 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; /** 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"; } /** Schema for the `AssistantUsageQuotaSnapshot` type. */ 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 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 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 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 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 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 (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 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 (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; /** * 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 * (`Config.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 `Config.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; /** * 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; /** * 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; 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; /** * 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; /** * Switches to the specified authentication info. * @param auth The authentication method to switch to. */ switchToAuth(auth: AuthInfoWithToken): Promise; /** * Clears the current credentials. * @returns True if, after logging out a user, there are more users logged in. * False otherwise. */ logout(): Promise; /** * 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; /** * 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 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"; /** 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" /** 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}. */ export 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; }; /** 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; }; /** * 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 current?; /** Identity that acquired {@link current}; gates cross-identity discount reads via {@link isOwnedBy}. */ private currentAuthInfo?; private previousConcreteModel?; private inflight?; /** * True once Auto Intent has been attempted for the {@link current} session token. * Auto Intent runs at most once per token (first prompt); a new token from * acquire/refresh (e.g. after expiry or compaction) resets this so the next * first prompt re-runs intent, matching the integrator guidance. */ private intentResolved; private intentInflight?; /** * True once Auto Intent has finished for the {@link current} session token, * regardless of outcome (confident pick, fallback, or transport failure). * Distinct from {@link intentResolved}, which latches up front to suppress * retries; this only flips when a result (or failure) is in hand, so the UI * keeps showing a plain `Auto` until the model is actually decided. */ private intentSettled; 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; /** * Whether {@link current} was acquired by {@link authInfo}. The manager is server-scoped and shared across all * sessions (including ones authenticated with a per-session `gitHubToken`), so a discount read must confirm * ownership before trusting {@link getDiscountPercent} — otherwise one account could read another's discount. */ 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; /** * Resolve the auto-mode model id + session token, using cache when valid. * Writes `capiSessionToken` into {@link settings} on success; 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. Runs at most * once per session token (the first prompt); subsequent calls before a token * refresh are no-ops that return the already-resolved model. {@link resolve} * must have produced a session token first — when no session is cached this * returns `undefined`. * * On a confident, non-fallback prediction the cached selected model and * candidate list are updated (and listeners notified). On `fallback: true`, * an unsupported proxy (404), or any transport failure, the standard Auto * Mode selection is preserved. The latch is set regardless so a failed or * low-confidence attempt does not add the intent-hop latency to later prompts. */ resolveIntent(args: { authInfo: AuthInfo; integrationId: string; sessionId: string; logger: RunnerLogger; prompt: string; hasImage: boolean; }): Promise; private doResolveIntent; private doResolve; /** 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; private isFresh; /** True when the cached token exists and is at or past its `expires_at` claim. */ private isExpired; /** * 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; } export declare type AutoModeSessionResult = { sessionToken: string; selectedModel: string; availableModels: string[]; expiresAt?: number; discountedCosts?: Record; }; /** 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"; /** Auto-mode is not available in this environment (no CAPI URL, or BYOK). */ export declare class AutoModeUnavailableError extends Error { constructor(message: string); } /** 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 = "You have not yet marked the task as complete using the task_complete tool. If you were planning, stop planning and start implementing. You aren't done until you have fully completed the task.\n\nIMPORTANT: Do NOT call task_complete if:\n- You have open questions or ambiguities - make good decisions and keep working\n- You encountered an error - try to resolve it or find an alternative approach\n- There are remaining steps - complete them first\n\nKeep working autonomously until the task is truly finished, then call task_complete."; /** 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; flushPendingWrites(): Promise; isReady(): boolean; getState(): AutopilotObjectiveState | undefined; set(objectiveInput: string): Promise; pause(reason?: string): Promise; resume(): Promise; clear(): Promise; 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; 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. */ export declare type AvailableModel = Model & { capabilities: Model["capabilities"] & { supports: Model["capabilities"]["supports"] & { reasoningEffort?: boolean; }; }; supportedReasoningEfforts?: ReasoningEffortLevel[]; defaultReasoningEffort?: ReasoningEffortLevel; }; /** * Simplified model info for tools that need to validate/display available models. */ declare type AvailableModelInfo = { /** Model identifier (e.g., "claude-sonnet-4.5") */ id: string; /** Human-readable label (e.g., "Claude Sonnet 4.5") */ label: string; /** Brief description of the model's characteristics */ description?: string; /** Cost multiplier for the model (e.g., 0 for free, 1 for standard, 3 for premium) */ multiplier?: number; /** Model capability metadata when available from the model API. */ capabilities?: { supports?: { reasoning_effort?: string[]; }; }; /** Billing metadata when available from the model API. */ billing?: Model["billing"]; /** * 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; /** Schema for the `BackgroundTasksChangedData` type. */ declare interface BackgroundTasksChangedData { } /** Session event "session.background_tasks_changed". */ declare interface BackgroundTasksChangedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `BackgroundTasksChangedData` type. */ 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; } /** * Base interface for all hook inputs */ export declare interface BaseHookInput { sessionId: string; timestamp: number; cwd: string; } 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; } declare type BasicToolConfig = { serverName: string; name: string; namespacedName: string; mcpServerName?: string; mcpToolName?: string; title: string; description: string; input_schema: ToolInputSchema; readOnly?: boolean; /** When true, tool output should always be displayed expanded in the CLI timeline. */ displayVerbatim?: boolean; safeForTelemetry?: Tool_2["safeForTelemetry"] & Tool["safeForTelemetry"]; filterMode?: ContentFilterMode; disableSecretMasking?: boolean; /** Tool-search deferral policy inherited from the server's `deferTools` config. */ defer?: "auto" | "never"; /** MCP Apps (SEP-1865) tool metadata propagated from the server's tools/list response. */ _meta?: { ui?: McpUiToolMeta; }; /** MCP task support level declared by the tool via `execution.taskSupport`. */ taskSupport?: "required" | "optional" | "forbidden"; }; /** 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; /** 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; /** 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; 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; } declare const BLUEBIRD_MCP_SERVER_NAME = "bluebird"; /** * Builds the `providerAndModel` string for BYOM (custom provider) sessions, * encoding reasoning options when set so that `splitAgentModelSetting` can * parse them into client options. */ export declare function buildByomProviderAndModel(model: string, reasoningEffort: string | undefined, reasoningSummary: ReasoningSummary | undefined): string; /** * Builds LargeOutputOptions from an optional sessionFs and optional size settings. */ declare function buildLargeOutputOptions(sessionFs?: SessionFs, settings?: { enabled?: boolean; maxSizeBytes?: number; outputDir?: string; }, grepToolName?: string): LargeOutputOptions; declare function buildToolCallbackOptions(client: Client, settings: RuntimeSettings, tools: readonly Pick[], abortSignal?: AbortSignal, sessionFs?: SessionFs): Promise>; /** * A hook: its handler plus the metadata the runtime needs to order, attribute, * and fail-close it. * * Representing hooks as objects — rather than bare functions tagged via * process-global side tables — keeps provenance ({@link Hook.source}) and policy * status ({@link Hook.isPolicy}) intrinsic to the hook. The metadata therefore * cannot go stale, leak across unrelated hook graphs, or be lost when a hook is * wrapped (e.g. by a matcher). */ export declare interface CallbackHook { readonly kind?: "callback"; /** The function invoked when the hook runs. */ readonly handler: HookHandler; /** * Short, human-readable label identifying where the hook came from (e.g. the * plugin it was loaded from, like `dependabot@agency`). * * The label is config-derived (plugin name / configured command), never * influenced by tool arguments, so it is safe to surface in error messages — * unlike a hook's thrown error text, which can be attacker-influenced via * `toolArgs` and is therefore kept out of model-visible results. */ readonly source?: string; /** * Whether this is an admin-deployed policy hook (e.g. Defender, Purview). * Policy hooks run before non-policy hooks, may make terminal decisions that * skip later hooks, and fail closed when they throw for non-timeout reasons. * * Security: this flag grants elevated precedence, so it must only be set by * trusted construction (the policy loader in `policyHooks.ts`). Hooks loaded * from untrusted sources (repo config, plugins) flow through * {@link getHooksFromConfig}, which never sets it. */ readonly isPolicy?: boolean; } declare type CallbackRuntimeSessionsClientConfig = { transport: "progress"; callbackUrl: string; jobId: string; http?: { settingsJson: string; additionalRedactionSecrets?: string[]; userAgent?: string; }; } | { transport: "capi"; capiUrl: string; sessionId: string; headers?: { name: string; value: string; }[]; }; declare interface CallbackRuntimeSink extends IAgentCallback { addBufferedUserMessages?(messages: UserMessage[]): void; drainUserMessages?(): UserMessage[]; flush?(): Promise; } declare interface CallToolResult extends Record { content: CallToolResultContent[]; isError?: boolean; structuredContent?: Record; _meta?: Record; } 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; } /** Schema for the `CanvasClosedData` type. */ 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". */ declare interface CanvasClosedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `CanvasClosedData` type. */ 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; /** 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[]; } /** Schema for the `CanvasOpenedData` type. */ declare interface CanvasOpenedData { /** Provider-local canvas identifier */ canvasId: string; /** Owning provider identifier */ extensionId: string; /** Owning extension display name, when available */ extensionName?: 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". */ declare interface CanvasOpenedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `CanvasOpenedData` type. */ 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[0]): ReturnType; } 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"; } /** Schema for the `CanvasRegistryChangedCanvas` type. */ 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; /** JSON Schema for canvas open input */ inputSchema?: unknown; } /** Schema for the `CanvasRegistryChangedCanvasAction` type. */ declare interface CanvasRegistryChangedCanvasAction { /** Action description */ description?: string; /** JSON Schema for action input */ inputSchema?: unknown; /** Action name */ name: string; } /** Schema for the `CanvasRegistryChangedData` type. */ declare interface CanvasRegistryChangedData { /** Canvas declarations currently available */ canvases: CanvasRegistryChangedCanvas[]; } /** Session event "session.canvas.registry_changed". */ declare interface CanvasRegistryChangedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `CanvasRegistryChangedData` type. */ 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; } /** * Env var that, when set to "true", expands into enabling every flag marked * `capiSanity: true` in the availability map. Equivalent to listing all such * flags in `COPILOT_CLI_ENABLED_FEATURE_FLAGS` by hand. Used by the live-CAPI * smoke tests' "flags-stacked" matrix variant. */ export declare const CAPI_SANITY_FLAGS_ENV_VAR = "COPILOT_CLI_ENABLE_CAPI_SANITY_FLAGS"; /** * Typed context for CAPI-specific request headers. * Set at client creation time; mapped to HTTP headers in {@link CopilotOpenAIClient.prepareOptions}. */ declare type CAPIRequestContext = { /** The type of interaction — agent, subagent, sampling, background, compaction, or user-initiated. */ interactionType: InteractionType; /** A unique GUID for this agent instance, sent as X-Agent-Task-Id. */ agentTaskId: string; /** The parent agent's task ID, sent as X-Parent-Agent-Id. Only set for subagents. */ 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; } /** * 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"; /** * Represents a chat completion response returned by model, based on the provided * input. */ declare interface ChatCompletion { /** * A unique identifier for the chat completion. */ id: string; /** * A list of chat completion choices. Can be more than one if `n` is greater * than 1. */ choices: Array; /** * The Unix timestamp (in seconds) of when the chat completion was created. */ created: number; /** * The model used for the chat completion. */ model: string; /** * The object type, which is always `chat.completion`. */ object: "chat.completion"; /** * Specifies the processing type used for serving the request. * * - If set to 'auto', then the request will be processed with the service tier * configured in the Project settings. Unless otherwise configured, the Project * will use 'default'. * - If set to 'default', then the request will be processed with the standard * pricing and performance for the selected model. * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or * '[priority](https://openai.com/api-priority-processing/)', then the request * will be processed with the corresponding service tier. * - When not set, the default behavior is 'auto'. * * When the `service_tier` parameter is set, the response body will include the * `service_tier` value based on the processing mode actually used to serve the * request. This response value may be different from the value set in the * parameter. */ service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; /** * @deprecated This fingerprint represents the backend configuration that the model * runs with. * * Can be used in conjunction with the `seed` request parameter to understand when * backend changes have been made that might impact determinism. */ system_fingerprint?: string; /** * Usage statistics for the completion request. */ usage?: CompletionsAPI.CompletionUsage; } declare namespace ChatCompletion { interface Choice { /** * The reason the model stopped generating tokens. This will be `stop` if the model * hit a natural stop point or a provided stop sequence, `length` if the maximum * number of tokens specified in the request was reached, `content_filter` if * content was omitted due to a flag from our content filters, `tool_calls` if the * model called a tool, or `function_call` (deprecated) if the model called a * function. */ finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; /** * The index of the choice in the list of choices. */ index: number; /** * Log probability information for the choice. */ logprobs: Choice.Logprobs | null; /** * A chat completion message generated by the model. */ message: CompletionsCompletionsAPI.ChatCompletionMessage; } namespace Choice { /** * Log probability information for the choice. */ interface Logprobs { /** * A list of message content tokens with log probability information. */ content: Array | null; /** * A list of message refusal tokens with log probability information. */ refusal: Array | null; } } } /** * Constrains the tools available to the model to a pre-defined set. */ declare interface ChatCompletionAllowedToolChoice { /** * Constrains the tools available to the model to a pre-defined set. */ allowed_tools: ChatCompletionAllowedTools; /** * Allowed tool configuration type. Always `allowed_tools`. */ type: "allowed_tools"; } /** * Constrains the tools available to the model to a pre-defined set. */ declare interface ChatCompletionAllowedTools { /** * Constrains the tools available to the model to a pre-defined set. * * `auto` allows the model to pick from among the allowed tools and generate a * message. * * `required` requires the model to call one or more of the allowed tools. */ mode: "auto" | "required"; /** * A list of tool definitions that the model should be allowed to call. * * For the Chat Completions API, the list of tool definitions might look like: * * ```json * [ * { "type": "function", "function": { "name": "get_weather" } }, * { "type": "function", "function": { "name": "get_time" } } * ] * ``` */ tools: Array<{ [key: string]: unknown; }>; } /** * Messages sent by the model in response to user messages. */ declare interface ChatCompletionAssistantMessageParam { /** * The role of the messages author, in this case `assistant`. */ role: "assistant"; /** * Data about a previous audio response from the model. * [Learn more](https://platform.openai.com/docs/guides/audio). */ audio?: ChatCompletionAssistantMessageParam.Audio | null; /** * The contents of the assistant message. Required unless `tool_calls` or * `function_call` is specified. */ content?: string | Array | null; /** * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a * function that should be called, as generated by the model. */ function_call?: ChatCompletionAssistantMessageParam.FunctionCall | null; /** * An optional name for the participant. Provides the model information to * differentiate between participants of the same role. */ name?: string; /** * The refusal message by the assistant. */ refusal?: string | null; /** * The tool calls generated by the model, such as function calls. */ tool_calls?: Array; } declare namespace ChatCompletionAssistantMessageParam { /** * Data about a previous audio response from the model. * [Learn more](https://platform.openai.com/docs/guides/audio). */ interface Audio { /** * Unique identifier for a previous audio response from the model. */ id: string; } /** * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a * function that should be called, as generated by the model. */ interface FunctionCall { /** * The arguments to call the function with, as generated by the model in JSON * format. Note that the model does not always generate valid JSON, and may * hallucinate parameters not defined by your function schema. Validate the * arguments in your code before calling your function. */ arguments: string; /** * The name of the function to call. */ name: string; } } /** * If the audio output modality is requested, this object contains data about the * audio response from the model. * [Learn more](https://platform.openai.com/docs/guides/audio). */ declare interface ChatCompletionAudio { /** * Unique identifier for this audio response. */ id: string; /** * Base64 encoded audio bytes generated by the model, in the format specified in * the request. */ data: string; /** * The Unix timestamp (in seconds) for when this audio response will no longer be * accessible on the server for use in multi-turn conversations. */ expires_at: number; /** * Transcript of the audio generated by the model. */ transcript: string; } /** * Parameters for audio output. Required when audio output is requested with * `modalities: ["audio"]`. * [Learn more](https://platform.openai.com/docs/guides/audio). */ declare interface ChatCompletionAudioParam { /** * Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, * or `pcm16`. */ format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; /** * The voice the model uses to respond. Supported voices are `alloy`, `ash`, * `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`. */ voice: (string & {}) | "alloy" | "ash" | "ballad" | "coral" | "echo" | "sage" | "shimmer" | "verse" | "marin" | "cedar"; } /** * Represents a streamed chunk of a chat completion response returned by the model, * based on the provided input. * [Learn more](https://platform.openai.com/docs/guides/streaming-responses). */ declare interface ChatCompletionChunk { /** * A unique identifier for the chat completion. Each chunk has the same ID. */ id: string; /** * A list of chat completion choices. Can contain more than one elements if `n` is * greater than 1. Can also be empty for the last chunk if you set * `stream_options: {"include_usage": true}`. */ choices: Array; /** * The Unix timestamp (in seconds) of when the chat completion was created. Each * chunk has the same timestamp. */ created: number; /** * The model to generate the completion. */ model: string; /** * The object type, which is always `chat.completion.chunk`. */ object: "chat.completion.chunk"; /** * Specifies the processing type used for serving the request. * * - If set to 'auto', then the request will be processed with the service tier * configured in the Project settings. Unless otherwise configured, the Project * will use 'default'. * - If set to 'default', then the request will be processed with the standard * pricing and performance for the selected model. * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or * '[priority](https://openai.com/api-priority-processing/)', then the request * will be processed with the corresponding service tier. * - When not set, the default behavior is 'auto'. * * When the `service_tier` parameter is set, the response body will include the * `service_tier` value based on the processing mode actually used to serve the * request. This response value may be different from the value set in the * parameter. */ service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; /** * @deprecated This fingerprint represents the backend configuration that the model * runs with. Can be used in conjunction with the `seed` request parameter to * understand when backend changes have been made that might impact determinism. */ system_fingerprint?: string; /** * An optional field that will only be present when you set * `stream_options: {"include_usage": true}` in your request. When present, it * contains a null value **except for the last chunk** which contains the token * usage statistics for the entire request. * * **NOTE:** If the stream is interrupted or cancelled, you may not receive the * final usage chunk which contains the total token usage for the request. */ usage?: CompletionsAPI.CompletionUsage | null; } declare namespace ChatCompletionChunk { interface Choice { /** * A chat completion delta generated by streamed model responses. */ delta: Choice.Delta; /** * The reason the model stopped generating tokens. This will be `stop` if the model * hit a natural stop point or a provided stop sequence, `length` if the maximum * number of tokens specified in the request was reached, `content_filter` if * content was omitted due to a flag from our content filters, `tool_calls` if the * model called a tool, or `function_call` (deprecated) if the model called a * function. */ finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call" | null; /** * The index of the choice in the list of choices. */ index: number; /** * Log probability information for the choice. */ logprobs?: Choice.Logprobs | null; } namespace Choice { /** * A chat completion delta generated by streamed model responses. */ interface Delta { /** * The contents of the chunk message. */ content?: string | null; /** * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a * function that should be called, as generated by the model. */ function_call?: Delta.FunctionCall; /** * The refusal message generated by the model. */ refusal?: string | null; /** * The role of the author of this message. */ role?: "developer" | "system" | "user" | "assistant" | "tool"; tool_calls?: Array; } namespace Delta { /** * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a * function that should be called, as generated by the model. */ interface FunctionCall { /** * The arguments to call the function with, as generated by the model in JSON * format. Note that the model does not always generate valid JSON, and may * hallucinate parameters not defined by your function schema. Validate the * arguments in your code before calling your function. */ arguments?: string; /** * The name of the function to call. */ name?: string; } interface ToolCall { index: number; /** * The ID of the tool call. */ id?: string; function?: ToolCall.Function; /** * The type of the tool. Currently, only `function` is supported. */ type?: "function"; } namespace ToolCall { interface Function { /** * The arguments to call the function with, as generated by the model in JSON * format. Note that the model does not always generate valid JSON, and may * hallucinate parameters not defined by your function schema. Validate the * arguments in your code before calling your function. */ arguments?: string; /** * The name of the function to call. */ name?: string; } } } /** * Log probability information for the choice. */ interface Logprobs { /** * A list of message content tokens with log probability information. */ content: Array | null; /** * A list of message refusal tokens with log probability information. */ refusal: Array | null; } } } /** * Learn about * [text inputs](https://platform.openai.com/docs/guides/text-generation). */ declare type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPart.File; declare namespace ChatCompletionContentPart { /** * Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text * generation. */ interface File { file: File.File; /** * The type of the content part. Always `file`. */ type: "file"; } namespace File { interface File { /** * The base64 encoded file data, used when passing the file to the model as a * string. */ file_data?: string; /** * The ID of an uploaded file to use as input. */ file_id?: string; /** * The name of the file, used when passing the file to the model as a string. */ filename?: string; } } } /** * Learn about [image inputs](https://platform.openai.com/docs/guides/vision). */ declare interface ChatCompletionContentPartImage { image_url: ChatCompletionContentPartImage.ImageURL; /** * The type of the content part. */ type: "image_url"; } declare namespace ChatCompletionContentPartImage { interface ImageURL { /** * Either a URL of the image or the base64 encoded image data. */ url: string; /** * Specifies the detail level of the image. Learn more in the * [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). */ detail?: "auto" | "low" | "high"; } } /** * Learn about [audio inputs](https://platform.openai.com/docs/guides/audio). */ declare interface ChatCompletionContentPartInputAudio { input_audio: ChatCompletionContentPartInputAudio.InputAudio; /** * The type of the content part. Always `input_audio`. */ type: "input_audio"; } declare namespace ChatCompletionContentPartInputAudio { interface InputAudio { /** * Base64 encoded audio data. */ data: string; /** * The format of the encoded audio data. Currently supports "wav" and "mp3". */ format: "wav" | "mp3"; } } declare interface ChatCompletionContentPartRefusal { /** * The refusal message generated by the model. */ refusal: string; /** * The type of the content part. */ type: "refusal"; } /** * Learn about * [text inputs](https://platform.openai.com/docs/guides/text-generation). */ declare interface ChatCompletionContentPartText { /** * The text content. */ text: string; /** * The type of the content part. */ type: "text"; } declare type ChatCompletionCreateParams = ChatCompletionCreateParamsNonStreaming | ChatCompletionCreateParamsStreaming; declare namespace ChatCompletionCreateParams { /** * @deprecated */ interface Function { /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain * underscores and dashes, with a maximum length of 64. */ name: string; /** * A description of what the function does, used by the model to choose when and * how to call the function. */ description?: string; /** * The parameters the functions accepts, described as a JSON Schema object. See the * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, * and the * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for * documentation about the format. * * Omitting `parameters` defines a function with an empty parameter list. */ parameters?: Shared.FunctionParameters; } /** * This tool searches the web for relevant results to use in a response. Learn more * about the * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). */ interface WebSearchOptions { /** * High level guidance for the amount of context window space to use for the * search. One of `low`, `medium`, or `high`. `medium` is the default. */ search_context_size?: "low" | "medium" | "high"; /** * Approximate location parameters for the search. */ user_location?: WebSearchOptions.UserLocation | null; } namespace WebSearchOptions { /** * Approximate location parameters for the search. */ interface UserLocation { /** * Approximate location parameters for the search. */ approximate: UserLocation.Approximate; /** * The type of location approximation. Always `approximate`. */ type: "approximate"; } namespace UserLocation { /** * Approximate location parameters for the search. */ interface Approximate { /** * Free text input for the city of the user, e.g. `San Francisco`. */ city?: string; /** * The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of * the user, e.g. `US`. */ country?: string; /** * Free text input for the region of the user, e.g. `California`. */ region?: string; /** * The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the * user, e.g. `America/Los_Angeles`. */ timezone?: string; } } } type ChatCompletionCreateParamsNonStreaming = CompletionsCompletionsAPI.ChatCompletionCreateParamsNonStreaming; type ChatCompletionCreateParamsStreaming = CompletionsCompletionsAPI.ChatCompletionCreateParamsStreaming; } declare interface ChatCompletionCreateParamsBase { /** * A list of messages comprising the conversation so far. Depending on the * [model](https://platform.openai.com/docs/models) you use, different message * types (modalities) are supported, like * [text](https://platform.openai.com/docs/guides/text-generation), * [images](https://platform.openai.com/docs/guides/vision), and * [audio](https://platform.openai.com/docs/guides/audio). */ messages: Array; /** * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a * wide range of models with different capabilities, performance characteristics, * and price points. Refer to the * [model guide](https://platform.openai.com/docs/models) to browse and compare * available models. */ model: (string & {}) | Shared.ChatModel; /** * Parameters for audio output. Required when audio output is requested with * `modalities: ["audio"]`. * [Learn more](https://platform.openai.com/docs/guides/audio). */ audio?: ChatCompletionAudioParam | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on their * existing frequency in the text so far, decreasing the model's likelihood to * repeat the same line verbatim. */ frequency_penalty?: number | null; /** * @deprecated Deprecated in favor of `tool_choice`. * * Controls which (if any) function is called by the model. * * `none` means the model will not call a function and instead generates a message. * * `auto` means the model can pick between generating a message or calling a * function. * * Specifying a particular function via `{"name": "my_function"}` forces the model * to call that function. * * `none` is the default when no functions are present. `auto` is the default if * functions are present. */ function_call?: "none" | "auto" | ChatCompletionFunctionCallOption; /** * @deprecated Deprecated in favor of `tools`. * * A list of functions the model may generate JSON inputs for. */ functions?: Array; /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a JSON object that maps tokens (specified by their token ID in the * tokenizer) to an associated bias value from -100 to 100. Mathematically, the * bias is added to the logits generated by the model prior to sampling. The exact * effect will vary per model, but values between -1 and 1 should decrease or * increase likelihood of selection; values like -100 or 100 should result in a ban * or exclusive selection of the relevant token. */ logit_bias?: { [key: string]: number; } | null; /** * Whether to return log probabilities of the output tokens or not. If true, * returns the log probabilities of each output token returned in the `content` of * `message`. */ logprobs?: boolean | null; /** * An upper bound for the number of tokens that can be generated for a completion, * including visible output tokens and * [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). */ max_completion_tokens?: number | null; /** * @deprecated The maximum number of [tokens](/tokenizer) that can be generated in * the chat completion. This value can be used to control * [costs](https://openai.com/api/pricing/) for text generated via API. * * This value is now deprecated in favor of `max_completion_tokens`, and is not * compatible with * [o-series models](https://platform.openai.com/docs/guides/reasoning). */ max_tokens?: number | null; /** * Set of 16 key-value pairs that can be attached to an object. This can be useful * for storing additional information about the object in a structured format, and * querying for objects via API or the dashboard. * * Keys are strings with a maximum length of 64 characters. Values are strings with * a maximum length of 512 characters. */ metadata?: Shared.Metadata | null; /** * Output types that you would like the model to generate. Most models are capable * of generating text, which is the default: * * `["text"]` * * The `gpt-4o-audio-preview` model can also be used to * [generate audio](https://platform.openai.com/docs/guides/audio). To request that * this model generate both text and audio responses, you can use: * * `["text", "audio"]` */ modalities?: Array<"text" | "audio"> | null; /** * How many chat completion choices to generate for each input message. Note that * you will be charged based on the number of generated tokens across all of the * choices. Keep `n` as `1` to minimize costs. */ n?: number | null; /** * Whether to enable * [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) * during tool use. */ parallel_tool_calls?: boolean; /** * Static predicted output content, such as the content of a text file that is * being regenerated. */ prediction?: ChatCompletionPredictionContent | null; /** * Number between -2.0 and 2.0. Positive values penalize new tokens based on * whether they appear in the text so far, increasing the model's likelihood to * talk about new topics. */ presence_penalty?: number | null; /** * Used by OpenAI to cache responses for similar requests to optimize your cache * hit rates. Replaces the `user` field. * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). */ prompt_cache_key?: string; /** * Constrains effort on reasoning for * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning * effort can result in faster responses and fewer tokens used on reasoning in a * response. */ reasoning_effort?: Shared.ReasoningEffort | null; /** * An object specifying the format that the model must output. * * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured * Outputs which ensures the model will match your supplied JSON schema. Learn more * in the * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). * * Setting to `{ "type": "json_object" }` enables the older JSON mode, which * ensures the message the model generates is valid JSON. Using `json_schema` is * preferred for models that support it. */ response_format?: Shared.ResponseFormatText | Shared.ResponseFormatJSONSchema | Shared.ResponseFormatJSONObject; /** * A stable identifier used to help detect users of your application that may be * violating OpenAI's usage policies. The IDs should be a string that uniquely * identifies each user. We recommend hashing their username or email address, in * order to avoid sending us any identifying information. * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). */ safety_identifier?: string; /** * @deprecated This feature is in Beta. If specified, our system will make a best * effort to sample deterministically, such that repeated requests with the same * `seed` and parameters should return the same result. Determinism is not * guaranteed, and you should refer to the `system_fingerprint` response parameter * to monitor changes in the backend. */ seed?: number | null; /** * Specifies the processing type used for serving the request. * * - If set to 'auto', then the request will be processed with the service tier * configured in the Project settings. Unless otherwise configured, the Project * will use 'default'. * - If set to 'default', then the request will be processed with the standard * pricing and performance for the selected model. * - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or * '[priority](https://openai.com/api-priority-processing/)', then the request * will be processed with the corresponding service tier. * - When not set, the default behavior is 'auto'. * * When the `service_tier` parameter is set, the response body will include the * `service_tier` value based on the processing mode actually used to serve the * request. This response value may be different from the value set in the * parameter. */ service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; /** * Not supported with latest reasoning models `o3` and `o4-mini`. * * Up to 4 sequences where the API will stop generating further tokens. The * returned text will not contain the stop sequence. */ stop?: string | null | Array; /** * Whether or not to store the output of this chat completion request for use in * our [model distillation](https://platform.openai.com/docs/guides/distillation) * or [evals](https://platform.openai.com/docs/guides/evals) products. * * Supports text and image inputs. Note: image inputs over 8MB will be dropped. */ store?: boolean | null; /** * If set to true, the model response data will be streamed to the client as it is * generated using * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). * See the * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) * for more information, along with the * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) * guide for more information on how to handle the streaming events. */ stream?: boolean | null; /** * Options for streaming response. Only set this when you set `stream: true`. */ stream_options?: ChatCompletionStreamOptions | null; /** * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will * make the output more random, while lower values like 0.2 will make it more * focused and deterministic. We generally recommend altering this or `top_p` but * not both. */ temperature?: number | null; /** * Controls which (if any) tool is called by the model. `none` means the model will * not call any tool and instead generates a message. `auto` means the model can * pick between generating a message or calling one or more tools. `required` means * the model must call one or more tools. Specifying a particular tool via * `{"type": "function", "function": {"name": "my_function"}}` forces the model to * call that tool. * * `none` is the default when no tools are present. `auto` is the default if tools * are present. */ tool_choice?: ChatCompletionToolChoiceOption; /** * A list of tools the model may call. You can provide either * [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) * or [function tools](https://platform.openai.com/docs/guides/function-calling). */ tools?: Array; /** * An integer between 0 and 20 specifying the number of most likely tokens to * return at each token position, each with an associated log probability. * `logprobs` must be set to `true` if this parameter is used. */ top_logprobs?: number | null; /** * An alternative to sampling with temperature, called nucleus sampling, where the * model considers the results of the tokens with top_p probability mass. So 0.1 * means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or `temperature` but not both. */ top_p?: number | null; /** * @deprecated This field is being replaced by `safety_identifier` and * `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching * optimizations. A stable identifier for your end-users. Used to boost cache hit * rates by better bucketing similar requests and to help OpenAI detect and prevent * abuse. * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). */ user?: string; /** * Constrains the verbosity of the model's response. Lower values will result in * more concise responses, while higher values will result in more verbose * responses. Currently supported values are `low`, `medium`, and `high`. */ verbosity?: "low" | "medium" | "high" | null; /** * This tool searches the web for relevant results to use in a response. Learn more * about the * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). */ web_search_options?: ChatCompletionCreateParams.WebSearchOptions; } declare interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase { /** * If set to true, the model response data will be streamed to the client as it is * generated using * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). * See the * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) * for more information, along with the * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) * guide for more information on how to handle the streaming events. */ stream?: false | null; } declare interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase { /** * If set to true, the model response data will be streamed to the client as it is * generated using * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). * See the * [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) * for more information, along with the * [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) * guide for more information on how to handle the streaming events. */ stream: true; } /** * A custom tool that processes input using a specified format. */ declare interface ChatCompletionCustomTool { /** * Properties of the custom tool. */ custom: ChatCompletionCustomTool.Custom; /** * The type of the custom tool. Always `custom`. */ type: "custom"; } declare namespace ChatCompletionCustomTool { /** * Properties of the custom tool. */ interface Custom { /** * The name of the custom tool, used to identify it in tool calls. */ name: string; /** * Optional description of the custom tool, used to provide more context. */ description?: string; /** * The input format for the custom tool. Default is unconstrained text. */ format?: Custom.Text | Custom.Grammar; } namespace Custom { /** * Unconstrained free-form text. */ interface Text { /** * Unconstrained text format. Always `text`. */ type: "text"; } /** * A grammar defined by the user. */ interface Grammar { /** * Your chosen grammar. */ grammar: Grammar.Grammar; /** * Grammar format. Always `grammar`. */ type: "grammar"; } namespace Grammar { /** * Your chosen grammar. */ interface Grammar { /** * The grammar definition. */ definition: string; /** * The syntax of the grammar definition. One of `lark` or `regex`. */ syntax: "lark" | "regex"; } } } } declare interface ChatCompletionDeleted { /** * The ID of the chat completion that was deleted. */ id: string; /** * Whether the chat completion was deleted. */ deleted: boolean; /** * The type of object being deleted. */ object: "chat.completion.deleted"; } /** * Developer-provided instructions that the model should follow, regardless of * messages sent by the user. With o1 models and newer, `developer` messages * replace the previous `system` messages. */ declare interface ChatCompletionDeveloperMessageParam { /** * The contents of the developer message. */ content: string | Array; /** * The role of the messages author, in this case `developer`. */ role: "developer"; /** * An optional name for the participant. Provides the model information to * differentiate between participants of the same role. */ name?: string; } /** * Specifying a particular function via `{"name": "my_function"}` forces the model * to call that function. */ declare interface ChatCompletionFunctionCallOption { /** * The name of the function to call. */ name: string; } /** * @deprecated */ declare interface ChatCompletionFunctionMessageParam { /** * The contents of the function message. */ content: string | null; /** * The name of the function to call. */ name: string; /** * The role of the messages author, in this case `function`. */ role: "function"; } /** * A function tool that can be used to generate a response. */ declare interface ChatCompletionFunctionTool { function: Shared.FunctionDefinition; /** * The type of the tool. Currently, only `function` is supported. */ type: "function"; } /** * A chat completion message generated by the model. */ declare interface ChatCompletionMessage { /** * The contents of the message. */ content: string | null; /** * The refusal message generated by the model. */ refusal: string | null; /** * The role of the author of this message. */ role: "assistant"; /** * Annotations for the message, when applicable, as when using the * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). */ annotations?: Array; /** * If the audio output modality is requested, this object contains data about the * audio response from the model. * [Learn more](https://platform.openai.com/docs/guides/audio). */ audio?: ChatCompletionAudio | null; /** * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a * function that should be called, as generated by the model. */ function_call?: ChatCompletionMessage.FunctionCall | null; /** * The tool calls generated by the model, such as function calls. */ tool_calls?: Array; } declare namespace ChatCompletionMessage { /** * A URL citation when using web search. */ interface Annotation { /** * The type of the URL citation. Always `url_citation`. */ type: "url_citation"; /** * A URL citation when using web search. */ url_citation: Annotation.URLCitation; } namespace Annotation { /** * A URL citation when using web search. */ interface URLCitation { /** * The index of the last character of the URL citation in the message. */ end_index: number; /** * The index of the first character of the URL citation in the message. */ start_index: number; /** * The title of the web resource. */ title: string; /** * The URL of the web resource. */ url: string; } } /** * @deprecated Deprecated and replaced by `tool_calls`. The name and arguments of a * function that should be called, as generated by the model. */ interface FunctionCall { /** * The arguments to call the function with, as generated by the model in JSON * format. Note that the model does not always generate valid JSON, and may * hallucinate parameters not defined by your function schema. Validate the * arguments in your code before calling your function. */ arguments: string; /** * The name of the function to call. */ name: string; } } /** * A call to a custom tool created by the model. */ declare interface ChatCompletionMessageCustomToolCall { /** * The ID of the tool call. */ id: string; /** * The custom tool that the model called. */ custom: ChatCompletionMessageCustomToolCall.Custom; /** * The type of the tool. Always `custom`. */ type: "custom"; } declare namespace ChatCompletionMessageCustomToolCall { /** * The custom tool that the model called. */ interface Custom { /** * The input for the custom tool call generated by the model. */ input: string; /** * The name of the custom tool to call. */ name: string; } } /** * A call to a function tool created by the model. */ declare interface ChatCompletionMessageFunctionToolCall { /** * The ID of the tool call. */ id: string; /** * The function that the model called. */ function: ChatCompletionMessageFunctionToolCall.Function; /** * The type of the tool. Currently, only `function` is supported. */ type: "function"; } declare namespace ChatCompletionMessageFunctionToolCall { /** * The function that the model called. */ interface Function { /** * The arguments to call the function with, as generated by the model in JSON * format. Note that the model does not always generate valid JSON, and may * hallucinate parameters not defined by your function schema. Validate the * arguments in your code before calling your function. */ arguments: string; /** * The name of the function to call. */ name: string; } } /** * Developer-provided instructions that the model should follow, regardless of * messages sent by the user. With o1 models and newer, `developer` messages * replace the previous `system` messages. */ declare type ChatCompletionMessageParam = ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam | ChatCompletionUserMessageParam | ChatCompletionAssistantMessageParam | ChatCompletionToolMessageParam | ChatCompletionFunctionMessageParam; declare type ChatCompletionMessageParamsWithToolCalls = Omit & { 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; }; /** * A call to a function tool created by the model. */ declare type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall; declare type ChatCompletionModality = "text" | "audio"; /** * Specifies a tool the model should use. Use to force the model to call a specific * function. */ declare interface ChatCompletionNamedToolChoice { function: ChatCompletionNamedToolChoice.Function; /** * For function calling, the type is always `function`. */ type: "function"; } declare namespace ChatCompletionNamedToolChoice { interface Function { /** * The name of the function to call. */ name: string; } } /** * Specifies a tool the model should use. Use to force the model to call a specific * custom tool. */ declare interface ChatCompletionNamedToolChoiceCustom { custom: ChatCompletionNamedToolChoiceCustom.Custom; /** * For custom tool calling, the type is always `custom`. */ type: "custom"; } declare namespace ChatCompletionNamedToolChoiceCustom { interface Custom { /** * The name of the custom tool to call. */ name: string; } } /** * Static predicted output content, such as the content of a text file that is * being regenerated. */ declare interface ChatCompletionPredictionContent { /** * The content that should be matched when generating a model response. If * generated tokens would match this content, the entire model response can be * returned much more quickly. */ content: string | Array; /** * The type of the predicted content you want to provide. This type is currently * always `content`. */ type: "content"; } declare type ChatCompletionReasoningEffort = Shared.ReasoningEffort | null; /** * The role of the author of a message */ declare type ChatCompletionRole = "developer" | "system" | "user" | "assistant" | "tool" | "function"; /** * A chat completion message generated by the model. */ declare interface ChatCompletionStoreMessage extends ChatCompletionMessage { /** * The identifier of the chat message. */ id: string; /** * If a content parts array was provided, this is an array of `text` and * `image_url` parts. Otherwise, null. */ content_parts?: Array | null; } /** * Options for streaming response. Only set this when you set `stream: true`. */ declare interface ChatCompletionStreamOptions { /** * When true, stream obfuscation will be enabled. Stream obfuscation adds random * characters to an `obfuscation` field on streaming delta events to normalize * payload sizes as a mitigation to certain side-channel attacks. These obfuscation * fields are included by default, but add a small amount of overhead to the data * stream. You can set `include_obfuscation` to false to optimize for bandwidth if * you trust the network links between your application and the OpenAI API. */ include_obfuscation?: boolean; /** * If set, an additional chunk will be streamed before the `data: [DONE]` message. * The `usage` field on this chunk shows the token usage statistics for the entire * request, and the `choices` field will always be an empty array. * * All other chunks will also include a `usage` field, but with a null value. * **NOTE:** If the stream is interrupted, you may not receive the final usage * chunk which contains the total token usage for the request. */ include_usage?: boolean; } /** * Developer-provided instructions that the model should follow, regardless of * messages sent by the user. With o1 models and newer, use `developer` messages * for this purpose instead. */ declare interface ChatCompletionSystemMessageParam { /** * The contents of the system message. */ content: string | Array; /** * The role of the messages author, in this case `system`. */ role: "system"; /** * An optional name for the participant. Provides the model information to * differentiate between participants of the same role. */ name?: string; } declare interface ChatCompletionTokenLogprob { /** * The token. */ token: string; /** * A list of integers representing the UTF-8 bytes representation of the token. * Useful in instances where characters are represented by multiple tokens and * their byte representations must be combined to generate the correct text * representation. Can be `null` if there is no bytes representation for the token. */ bytes: Array | null; /** * The log probability of this token, if it is within the top 20 most likely * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very * unlikely. */ logprob: number; /** * List of the most likely tokens and their log probability, at this token * position. In rare cases, there may be fewer than the number of requested * `top_logprobs` returned. */ top_logprobs: Array; } declare namespace ChatCompletionTokenLogprob { interface TopLogprob { /** * The token. */ token: string; /** * A list of integers representing the UTF-8 bytes representation of the token. * Useful in instances where characters are represented by multiple tokens and * their byte representations must be combined to generate the correct text * representation. Can be `null` if there is no bytes representation for the token. */ bytes: Array | null; /** * The log probability of this token, if it is within the top 20 most likely * tokens. Otherwise, the value `-9999.0` is used to signify that the token is very * unlikely. */ logprob: number; } } /** * A function tool that can be used to generate a response. */ declare type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool; /** * Controls which (if any) tool is called by the model. `none` means the model will * not call any tool and instead generates a message. `auto` means the model can * pick between generating a message or calling one or more tools. `required` means * the model must call one or more tools. Specifying a particular tool via * `{"type": "function", "function": {"name": "my_function"}}` forces the model to * call that tool. * * `none` is the default when no tools are present. `auto` is the default if tools * are present. */ declare type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionAllowedToolChoice | ChatCompletionNamedToolChoice | ChatCompletionNamedToolChoiceCustom; declare interface ChatCompletionToolMessageParam { /** * The contents of the tool message. */ content: string | Array; /** * The role of the messages author, in this case `tool`. */ role: "tool"; /** * Tool call that this message is responding to. */ tool_call_id: string; } declare interface ChatCompletionUpdateParams { /** * Set of 16 key-value pairs that can be attached to an object. This can be useful * for storing additional information about the object in a structured format, and * querying for objects via API or the dashboard. * * Keys are strings with a maximum length of 64 characters. Values are strings with * a maximum length of 512 characters. */ metadata: Shared.Metadata | null; } /** * Messages sent by an end user, containing prompts or additional context * information. */ declare interface ChatCompletionUserMessageParam { /** * The contents of the user message. */ content: string | Array; /** * The role of the messages author, in this case `user`. */ role: "user"; /** * An optional name for the participant. Provides the model information to * differentiate between participants of the same role. */ name?: string; } declare type ChatModel = "gpt-5" | "gpt-5-mini" | "gpt-5-nano" | "gpt-5-2025-08-07" | "gpt-5-mini-2025-08-07" | "gpt-5-nano-2025-08-07" | "gpt-5-chat-latest" | "gpt-4.1" | "gpt-4.1-mini" | "gpt-4.1-nano" | "gpt-4.1-2025-04-14" | "gpt-4.1-mini-2025-04-14" | "gpt-4.1-nano-2025-04-14" | "o4-mini" | "o4-mini-2025-04-16" | "o3" | "o3-2025-04-16" | "o3-mini" | "o3-mini-2025-01-31" | "o1" | "o1-2024-12-17" | "o1-preview" | "o1-preview-2024-09-12" | "o1-mini" | "o1-mini-2024-09-12" | "gpt-4o" | "gpt-4o-2024-11-20" | "gpt-4o-2024-08-06" | "gpt-4o-2024-05-13" | "gpt-4o-audio-preview" | "gpt-4o-audio-preview-2024-10-01" | "gpt-4o-audio-preview-2024-12-17" | "gpt-4o-audio-preview-2025-06-03" | "gpt-4o-mini-audio-preview" | "gpt-4o-mini-audio-preview-2024-12-17" | "gpt-4o-search-preview" | "gpt-4o-mini-search-preview" | "gpt-4o-search-preview-2025-03-11" | "gpt-4o-mini-search-preview-2025-03-11" | "chatgpt-4o-latest" | "codex-mini-latest" | "gpt-4o-mini" | "gpt-4o-mini-2024-07-18" | "gpt-4-turbo" | "gpt-4-turbo-2024-04-09" | "gpt-4-0125-preview" | "gpt-4-turbo-preview" | "gpt-4-1106-preview" | "gpt-4-vision-preview" | "gpt-4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-1106" | "gpt-3.5-turbo-0125" | "gpt-3.5-turbo-16k-0613"; /** * 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; } /** * Returns true when the Claude model variant supports tool search. * Supported: Mythos Preview, Fable, Sonnet 4.0+, Opus 4.0+ (no Haiku). */ declare function claudeModelSupportsToolSearch(model: string): boolean; /** * Cleans up all temp files created by this module. * Errors are logged but not thrown to avoid disrupting shutdown flows. * * Set COPILOT_KEEP_TEMP_FILES=true to skip cleanup (useful for debugging). */ declare function cleanupTempFiles(): Promise; /** * Clears the `deferLoading` flag on every tool in place. * * Call this whenever tool search is disabled for the current model to strip any * stale deferral inherited from another session or a previous model selection. * * @param tools - The mutable array of tools (modified in place) */ declare function clearAllDeferral(tools: Tool_2[]): void; /** Clears the cached model list so the next retrieval hits the server. */ export declare function clearCachedModels(): 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_2[], customAgent: { tools?: string[] | null; deferredToolLoading?: boolean; } | undefined): void; export declare const CLI_CLIENT_NAME = "github/cli"; declare interface Client { readonly model: string; supportsNativeFileAttachmentMimeType(mimeType: string): Promise; getPreferredImageAttachmentFormat?(): ImageAttachmentRequestFormat; /** * Per-image binary budget (in bytes) for inline base64 image attachments, * or `undefined` when the client imposes no request-size cap. The vision * processor clamps its resize target to this so a single image plus the * rest of the request stays within the transport's request-size limit. */ getMaxInlineImageBytes?(): number | undefined; getCompletionWithTools(systemMessage: SystemMessageContent, initialMessages: ChatCompletionMessageParam[], tools: Tool_2[], options?: GetCompletionWithToolsOptions): AsyncGenerator; } /** * 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; /** Stable machine identifier from @vscode/deviceid */ dev_device_id?: string; } /** * Connection information for an MCP client. */ declare type ClientInfo_2 = { /** * Name of the MCP server this connection is for. */ clientName: string; /** * Optional original/display name for this server. * This may contain "/" when the internal `clientName` has been adapted (e.g. "/" -> "__"). */ displayName?: string; /** * MCP client instance connected to the server. * Undefined until `pendingConnection` resolves for deferred connections. */ mcpClient?: NativeMcpSession; /** * Telemetry configuration for this connection. */ safeForTelemetry?: Tool_2["safeForTelemetry"]; /** * List of tools from the server to expose. ["*"] means all tools. */ tools: string[]; /** * Filter mode for the tools from this client. * If not specified, defaults to ContentFilterMode.HiddenCharacters. * If specified as a map, it applies to each tool by name. */ filterMapping?: Record | ContentFilterMode; /** * Optional timeout in milliseconds for tool calls to this server. * If not specified, uses the default timeout. */ timeout?: number; /** * Optional promise that resolves when the connection is established. * Used for deferred connections where the client is created immediately but * the connection is established in the background. */ pendingConnection?: Promise; /** * Whether this is the default Playwright server configured by the system, * as opposed to a user-provided Playwright server. */ isDefaultServer?: boolean; /** * When true, secret masking is disabled for tool calls to this server. */ disableSecretMasking?: boolean; /** * Whether this server declared the `tasks.requests.tools.call` capability, * indicating it supports task-augmented tool calls. */ serverSupportsTaskTools?: boolean; /** * Optional list of tool names to exclude, applied after the `tools` include filter. * A tool in this list is hidden even when `tools` is `["*"]`. */ excludeTools?: string[]; /** * Tool-search deferral policy for this server, propagated to each of its tools. * When "never", the server's tools are never deferred for tool search. */ deferTools?: "auto" | "never"; }; /** * 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. * This field remains optional even in ClientOptionsRequired since not all models support it. */ thinkingBudget?: number | undefined; requestHeaders?: Record; /** * 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; /** * 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; /** * 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?: Responses.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; /** * 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; /** 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_regex` implementation. The API handles search * execution and tool reference expansion automatically. * Only applicable to Anthropic models. */ builtinToolSearch?: boolean; /** * Experimental: when true, the runtime materializes citable tool output (web-search * results) into Anthropic `search_result` blocks and enables * `citations.enabled` on attached documents, so the model returns native * citations that are normalized onto the `assistant.message` SDK event. * OFF by default — no behavior change for consumers that don't opt in. * Only affects Anthropic (Claude) models today. * May change or be removed while the citations surface is experimental. */ enableCitations?: boolean; /** * When true, uses OpenAI's client-executed tool search * (`{ type: "tool_search", execution: "client" }`) instead of the hosted * server-side Responses tool search. The runtime runs the search and returns * the matching tool definitions via `tool_search_output`. * Only applicable to OpenAI models. */ clientToolSearch?: 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; }; close(params: CanvasProviderCloseRequest): void | Promise; open(params: CanvasProviderOpenRequest): CanvasProviderOpenResult | Promise; }; providerToken: { getToken(params: ProviderTokenAcquireRequest): ProviderTokenAcquireResult | Promise; }; sessionFs: { appendFile(params: SessionFsAppendFileRequest): SessionFsError | Promise; exists(params: SessionFsExistsRequest): SessionFsExistsResult | Promise; mkdir(params: SessionFsMkdirRequest): SessionFsError | Promise; readFile(params: SessionFsReadFileRequest): SessionFsReadFileResult | Promise; readdir(params: SessionFsReaddirRequest): SessionFsReaddirResult | Promise; readdirWithTypes(params: SessionFsReaddirWithTypesRequest): SessionFsReaddirWithTypesResult | Promise; rename(params: SessionFsRenameRequest): SessionFsError | Promise; rm(params: SessionFsRmRequest): SessionFsError | Promise; sqliteExists(): SessionFsSqliteExistsResult | Promise; sqliteQuery(params: SessionFsSqliteQueryRequest): SessionFsSqliteQueryResult | Promise; stat(params: SessionFsStatRequest): SessionFsStatResult | Promise; writeFile(params: SessionFsWriteFileRequest): SessionFsError | Promise; }; } declare type CloudSessionStoreSqlInput = { description: string; query: string; }; /** Diagnostic stats exposed by {@link CoalescingWriteQueue.stats}. */ declare interface CoalescingWriteQueueStats { writeCount: number; pendingLength: number; drainScheduled: boolean; } /** 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; /** * 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; }; declare type CommandHookConfig = z_2.infer; declare const CommandHookConfigSchema: z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>; /** 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"; } /** Schema for the `CommandsChangedCommand` type. */ 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; } declare type CommonHookContext = { /** * The session identifier for correlating hook events. */ sessionId: string; /** * The commit hash before the agent made any changes. */ initialCommitHash: string; /** * The location where the agent is currently making changes. */ location: string; callback?: IAgentCallback; settings: RuntimeSettings; logger: RunnerLogger; /** * A git handler to use for any git operations. */ gitHandler: GitHandler; }; /** 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 | 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; /** 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; /** 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"; } /** * A filter used to compare a specified attribute key to a given value using a * defined comparison operation. */ declare interface ComparisonFilter { /** * The key to compare against the value. */ key: string; /** * Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. * * - `eq`: equals * - `ne`: not equal * - `gt`: greater than * - `gte`: greater than or equal * - `lt`: less than * - `lte`: less than or equal */ type: "eq" | "ne" | "gt" | "gte" | "lt" | "lte"; /** * The value to compare against the attribute key; supports string, number, or * boolean types. */ value: string | number | boolean; } export declare function completeOrphanedToolCalls(messages: ChatCompletionMessageParam[]): ChatCompletionMessageParam[]; declare namespace CompletionsAPI { export { CompletionUsage } } declare namespace CompletionsCompletionsAPI { export { ChatCompletion, ChatCompletionAllowedToolChoice, ChatCompletionAssistantMessageParam, ChatCompletionAudio, ChatCompletionAudioParam, ChatCompletionChunk, ChatCompletionContentPart, ChatCompletionContentPartImage, ChatCompletionContentPartInputAudio, ChatCompletionContentPartRefusal, ChatCompletionContentPartText, ChatCompletionCustomTool, ChatCompletionDeleted, ChatCompletionDeveloperMessageParam, ChatCompletionFunctionCallOption, ChatCompletionFunctionMessageParam, ChatCompletionFunctionTool, ChatCompletionMessage, ChatCompletionMessageCustomToolCall, ChatCompletionMessageFunctionToolCall, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionModality, ChatCompletionNamedToolChoice, ChatCompletionNamedToolChoiceCustom, ChatCompletionPredictionContent, ChatCompletionRole, ChatCompletionStoreMessage, ChatCompletionStreamOptions, ChatCompletionSystemMessageParam, ChatCompletionTokenLogprob, ChatCompletionTool, ChatCompletionToolChoiceOption, ChatCompletionToolMessageParam, ChatCompletionUserMessageParam, ChatCompletionAllowedTools, ChatCompletionReasoningEffort, ChatCompletionCreateParams, ChatCompletionCreateParamsBase, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, ChatCompletionUpdateParams } } /** 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[]; } /** * Usage statistics for the completion request. */ declare interface CompletionUsage { /** * Number of tokens in the generated completion. */ completion_tokens: number; /** * Number of tokens in the prompt. */ prompt_tokens: number; /** * Total number of tokens used in the request (prompt + completion). */ total_tokens: number; /** * Breakdown of tokens used in a completion. */ completion_tokens_details?: CompletionUsage.CompletionTokensDetails; /** * Breakdown of tokens used in the prompt. */ prompt_tokens_details?: CompletionUsage.PromptTokensDetails; } declare namespace CompletionUsage { /** * Breakdown of tokens used in a completion. */ interface CompletionTokensDetails { /** * When using Predicted Outputs, the number of tokens in the prediction that * appeared in the completion. */ accepted_prediction_tokens?: number; /** * Audio input tokens generated by the model. */ audio_tokens?: number; /** * Tokens generated by the model for reasoning. */ reasoning_tokens?: number; /** * When using Predicted Outputs, the number of tokens in the prediction that did * not appear in the completion. However, like reasoning tokens, these tokens are * still counted in the total completion tokens for purposes of billing, output, * and context window limits. */ rejected_prediction_tokens?: number; } /** * Breakdown of tokens used in the prompt. */ interface PromptTokensDetails { /** * Audio input tokens present in the prompt. */ audio_tokens?: number; /** * Cached tokens present in the prompt. */ cached_tokens?: number; } } 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; }; }; }; }; /** * Combine multiple filters using `and` or `or`. */ declare interface CompoundFilter { /** * Array of filters to combine. Items can be `ComparisonFilter` or * `CompoundFilter`. */ filters: Array; /** * Type of operation: `and` or `or`. */ type: "and" | "or"; } 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; } /** * Auto-mode discount % (0–100) from `discounted_costs`: {@link selectedModel}'s entry if present, else the average. * Returns `undefined` when there is no discount — i.e. an empty map, a computed value that rounds to 0%, or an * out-of-range value — so callers can omit the `billing` field entirely rather than surfacing a meaningless or * nonsensical discount. */ export declare function computeDiscountPercent(discountedCosts: Record | undefined, selectedModel?: string): number | undefined; /** 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; } /** Optional connection token presented by the SDK client during the handshake. */ declare interface ConnectRequest { /** 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_2.infer; /** * Zod schema for a single entry in the content exclusion API response array. */ declare const contentExclusionApiResponseSchema: z_2.ZodObject<{ rules: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, "passthrough", z_2.ZodTypeAny, z_2.objectOutputType<{ paths: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, z_2.ZodTypeAny, "passthrough">, z_2.objectInputType<{ paths: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, z_2.ZodTypeAny, "passthrough">>, "many">; last_updated_at: z_2.ZodUnion<[z_2.ZodString, z_2.ZodNumber]>; scope: z_2.ZodEnum<["repo", "all"]>; }, "passthrough", z_2.ZodTypeAny, z_2.objectOutputType<{ rules: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, "passthrough", z_2.ZodTypeAny, z_2.objectOutputType<{ paths: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, z_2.ZodTypeAny, "passthrough">, z_2.objectInputType<{ paths: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, z_2.ZodTypeAny, "passthrough">>, "many">; last_updated_at: z_2.ZodUnion<[z_2.ZodString, z_2.ZodNumber]>; scope: z_2.ZodEnum<["repo", "all"]>; }, z_2.ZodTypeAny, "passthrough">, z_2.objectInputType<{ rules: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, "passthrough", z_2.ZodTypeAny, z_2.objectOutputType<{ paths: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, z_2.ZodTypeAny, "passthrough">, z_2.objectInputType<{ paths: z_2.ZodArray; ifAnyMatch: z_2.ZodOptional>; ifNoneMatch: z_2.ZodOptional>; source: z_2.ZodObject<{ name: z_2.ZodString; type: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { name: string; type: string; }, { name: string; type: string; }>; }, z_2.ZodTypeAny, "passthrough">>, "many">; last_updated_at: z_2.ZodUnion<[z_2.ZodString, z_2.ZodNumber]>; scope: z_2.ZodEnum<["repo", "all"]>; }, z_2.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; /** * 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; /** * 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 native leveled log lines through the JS logger. */ private replayLogs; } declare enum ContentFilterMode { None = "none", Markdown = "markdown", HiddenCharacters = "hidden_characters" } /** Controls how MCP tool result content is filtered: none leaves content unchanged, markdown sanitizes HTML while preserving Markdown-friendly output, and hidden_characters removes characters that can hide directives. */ declare type ContentFilterMode_2 = "none" | "markdown" | "hidden_characters"; /** * Well-known context tiers for models with tiered context pricing. * The wire protocol leaves `contextTier` open as a string for forward * compatibility; the runtime validates against this list at the wire boundary. */ declare const CONTEXT_TIER_LEVELS: readonly ["default", "long_context"]; /** 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"; } /** 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"; declare type ContextTier_3 = (typeof CONTEXT_TIER_LEVELS)[number]; 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; }; /** Schema for the `CopilotApiTokenAuthInfo` type. */ 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 & { choices: CopilotChatCompletionChunkChoices; usage?: CopilotCompletionUsage | null; copilot_usage?: CopilotUsage; }; declare type CopilotChatCompletionChunkChoice = Omit & { delta: CopilotChatCompletionChunkDelta; }; declare type CopilotChatCompletionChunkChoices = Array; declare type CopilotChatCompletionChunkDelta = Omit & ReasoningMessageParam & { responses_message_status?: ResponsesMessageStatus; tool_calls?: Array; copilot_annotations?: string | undefined; /** Phase of generation for phased-output models (e.g. gpt-5.3-codex). */ phase?: 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, "prompt_tokens_details"> & { prompt_tokens_details?: CopilotPromptTokensDetails; /** Reasoning tokens reported by CAPI for models like Gemini. */ reasoning_tokens?: number; }; declare type CopilotExpAssignmentResponse = z.infer; /** * CopilotExpAssignmentResponse represents the response structure from the ExP API for feature assignments. */ declare const CopilotExpAssignmentResponseSchema: z.ZodObject<{ Features: z.ZodArray; Flights: z.ZodRecord; Configs: z.ZodArray>; }, "strip", z.ZodTypeAny, { Id: string; Parameters: Record; }, { Id: string; Parameters: Record; }>, "many">; ParameterGroups: z.ZodOptional>; FlightingVersion: z.ZodOptional; ImpressionId: z.ZodOptional; AssignmentContext: z.ZodString; }, "strip", z.ZodTypeAny, { Features: string[]; Flights: Record; Configs: { Id: string; Parameters: Record; }[]; AssignmentContext: string; ParameterGroups?: unknown; FlightingVersion?: number | undefined; ImpressionId?: string | undefined; }, { Features: string[]; Flights: Record; Configs: { Id: string; Parameters: Record; }[]; AssignmentContext: string; ParameterGroups?: unknown; FlightingVersion?: number | undefined; ImpressionId?: string | undefined; }>; declare type CopilotPromptTokensDetails = NonNullable["prompt_tokens_details"]> & { /** Tokens written to the prompt cache (e.g. Anthropic's `cache_creation_input_tokens`). */ cache_creation_tokens?: number; }; declare interface CopilotSessionsClient { sessionId(): string; error(error: Error): Promise; log(logs: SessionLogsContent): Promise; logNonCompletionContent(content: string): Promise; createOrUpdateMCPStartupToolCall(params: { content?: string; serverName: string; toolNamesToDisplayNames?: Record; }): Promise; createOrUpdateCloneToolCall(params: { content?: string; repo: string; }): Promise; logTitleAndBody(title: string, body: string, agentId?: string): Promise; getLogs(sessionId: string): Promise; callbackRuntimeClientConfig?(): CallbackRuntimeSessionsClientConfig | undefined; } /** 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. The * zod schema above is the runtime parser; its inferred shape is a structural * superset (it carries a `quota_snapshots` catchall index signature the generated * type omits), so parse results assign cleanly to this type while consumers see * exactly the wire contract. Drift is caught at the `fetchCopilotUser` parse site. */ 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 { access_type_sku?: string; analytics_tracking_id?: string; assigned_date?: string | null; can_signup_for_limited?: boolean; can_upgrade_plan?: boolean; chat_enabled?: boolean; cli_remote_control_enabled?: boolean; cloud_session_storage_enabled?: boolean; codex_agent_enabled?: boolean; copilot_plan?: string; copilotignore_enabled?: boolean; /** Schema for the `CopilotUserResponseEndpoints` type. */ endpoints?: CopilotUserResponseEndpoints; is_mcp_enabled?: boolean | null; is_staff?: boolean; limited_user_quotas?: Record; limited_user_reset_date?: string; login?: string; monthly_quotas?: Record; organization_list?: ({ login?: string | null; name?: string | null; } | null)[] | null; organization_login_list?: string[]; quota_reset_date?: string; quota_reset_date_utc?: string; /** Schema for the `CopilotUserResponseQuotaSnapshots` type. */ quota_snapshots?: CopilotUserResponseQuotaSnapshots; restricted_telemetry?: boolean; te?: boolean; token_based_billing?: boolean; } /** Schema for the `CopilotUserResponseEndpoints` type. */ declare interface CopilotUserResponseEndpoints { api?: string; "origin-tracker"?: string; proxy?: string; telemetry?: string; } /** Schema for the `CopilotUserResponseQuotaSnapshots` type. */ declare interface CopilotUserResponseQuotaSnapshots { /** Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. */ chat?: CopilotUserResponseQuotaSnapshotsChat; /** Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. */ completions?: CopilotUserResponseQuotaSnapshotsCompletions; /** Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. */ premium_interactions?: CopilotUserResponseQuotaSnapshotsPremiumInteractions; } /** Schema for the `CopilotUserResponseQuotaSnapshotsChat` type. */ declare interface CopilotUserResponseQuotaSnapshotsChat { entitlement?: number; has_quota?: boolean; overage_count?: number; overage_permitted?: boolean; percent_remaining?: number; quota_id?: string; quota_remaining?: number; quota_reset_at?: number; remaining?: number; timestamp_utc?: string; token_based_billing?: boolean; unlimited?: boolean; } /** Schema for the `CopilotUserResponseQuotaSnapshotsCompletions` type. */ declare interface CopilotUserResponseQuotaSnapshotsCompletions { entitlement?: number; has_quota?: boolean; overage_count?: number; overage_permitted?: boolean; percent_remaining?: number; quota_id?: string; quota_remaining?: number; quota_reset_at?: number; remaining?: number; timestamp_utc?: string; token_based_billing?: boolean; unlimited?: boolean; } /** Schema for the `CopilotUserResponseQuotaSnapshotsPremiumInteractions` type. */ declare interface CopilotUserResponseQuotaSnapshotsPremiumInteractions { entitlement?: number; has_quota?: boolean; overage_count?: number; overage_permitted?: boolean; percent_remaining?: number; quota_id?: string; quota_remaining?: number; quota_reset_at?: number; remaining?: number; timestamp_utc?: string; token_based_billing?: boolean; 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; }; /** * Counts the total number of hooks in a QueryHooks object. */ export declare function countHooks(hooks: QueryHooks | undefined): number; declare const CREATE_PULL_REQUEST_TOOL_NAME = "create_pull_request"; declare type CreateArgs = CreateInput & { command: "create"; }; /** * Creates the ask_user tool with the provided request function. * The request function is provided by the CLI to handle the UI interaction. */ declare function createAskUserTool(requestUserInput: RequestUserInputFn): Tool_2; declare function createCanvasTools(canvas: SessionCanvasApi, permissions: PermissionsConfig): Tool_2[]; /** * Creates the cloud session store SQL tool for querying cross-session history * via DuckDB. Queries target only the current user's sessions (personal scope). * * This tool registers under the same name as the local session store tool * (`session_store_sql`) — only one should be registered at a time, with cloud * taking precedence when CLOUD_SESSION_STORE is enabled. * * @param _config - Tool configuration * @param options - Settings and current repo context */ declare const createCloudSessionStoreSqlTool: (_config: ToolConfig, options: { settings: RuntimeSettings; /** Whether the local session store is also available for supplementary queries */ localEnabled?: boolean; }) => Tool_2; export declare function createCoreServices({ telemetryService, createFeatureFlagService, autoModeManager, }: CoreServicesInput): CoreServices; /** * Factory for creating a deferred FeatureFlagService. CLI callers use this so * ExP-backed accessors wait until the CLI-owned ExP coordinator injects a * fetched or empty assignment response. */ 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; /** Initial ExP assignment response for this feature flag service instance. */ expAssignments?: CopilotExpAssignmentResponse; /** Whether ExP-backed accessors should wait for an assignment response. */ deferExpResponse?: boolean; }) => SessionFeatureFlagService; declare type CreateInput = { path: string; file_text: string; }; /** * Factory for creating a LocalFeatureFlagService. * Convenience wrapper for `new LocalFeatureFlagService(options)`. */ export declare function createLocalFeatureFlagService(options?: Partial): LocalFeatureFlagService; export declare function createLocalFeatureFlagServiceCreator(options?: Partial): CreateFeatureFlagService; /** * Create the LSP code intelligence tool. * Returns an empty array if no language servers are configured. */ declare function createLSPRefactorTools(config: ToolConfig, logger: RunnerLogger): Tool_2[]; declare function createLSPTool(config: ToolConfig, logger: RunnerLogger): Tool_2; declare interface CreateMessageRequestParams extends TaskAugmentedRequestParams, Record { messages: SamplingMessage[]; modelPreferences?: ModelPreferences; systemPrompt?: string; includeContext?: string; temperature?: number; maxTokens: number; stopSequences?: string[]; metadata?: Record; tools?: ToolDescriptor[]; toolChoice?: ToolChoice; } declare interface CreateMessageResultWithTools extends Record { role: "user" | "assistant"; content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; model: string; stopReason?: "maxTokens" | "endTurn" | "stopSequence" | "toolUse" | (string & {}); _meta?: Record; } declare type CreatePullRequestInput = z_2.infer; declare const createPullRequestInputSchema: z_2.ZodObject<{ title: z_2.ZodString; description: z_2.ZodOptional; draft: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { title: string; description?: string | undefined; draft?: boolean | undefined; }, { title: string; description?: string | undefined; draft?: boolean | undefined; }>; declare const createPullRequestTool: (settings: RuntimeSettings, logger: RunnerLogger, agentAction?: AgentAction) => Tool_2 | undefined; declare const createPullRequestToolDescription = "Create a pull request for the current branch. Call this tool when the task is complete and the changes are ready for review. If a pull request already exists for the branch, this tool will return successfully and indicate that. Only call this tool when the user explicitly asks for a pull request to be created."; declare const createPullRequestToolInstructions = "## Examples\n\n### Create a standard pull request\n```json\n{\n \"title\": \"Fix null pointer exception in user authentication\",\n \"description\": \"## Summary\\nFixed a null pointer exception that occurred when...\\n\\n## Changes\\n- Added null check in auth middleware\\n- Updated tests\",\n \"draft\": false\n}\n```\n\n### Create a draft pull request\n```json\n{\n \"title\": \"WIP: Refactor database connection pooling\",\n \"description\": \"## Summary\\nRefactoring the connection pool to support...\\n\\n## TODO\\n- [ ] Add integration tests\\n- [ ] Update docs\",\n \"draft\": true\n}\n```\n\n## Notes\n* Always provide a clear, descriptive title\n* The description should summarize the changes made and any context needed for reviewers\n* Use `draft: true` if the work is still in progress\n* It is safe to call this tool even if a pull request may already exist for the branch\n* Before calling this tool, check for a pull request template in the repository (e.g. `.github/pull_request_template.md` or `.github/PULL_REQUEST_TEMPLATE/`). If a template exists, read it and follow its structure when writing the description. Keep all section headings, maintain their order, and fill in the relevant sections with your changes."; /** * Creates the SQL tool for executing queries against the session database. * * This tool provides a structured data primitive for agent workflows: * - Task tracking with dependencies * - TDD test case tracking * - PR comment review batching * - State machine / workstream tracking * - Any custom schema the agent needs * * The database is per-session and isolated - agent mistakes are contained. * When sessionStoreEnabled is true, the tool also exposes a read-only * global session store for cross-session history queries. * * @param workspacePath - Path to the workspace directory containing session.db * @param _config - Tool configuration * @param options - Optional settings for session store access */ declare const createSqlTool: (workspacePath: string, _config: ToolConfig, options?: { settings?: RuntimeSettings; sessionStoreEnabled?: boolean; sessionFs?: SessionFs; noPlanning?: boolean; }) => Tool_2 | undefined; /** * Creates the task_complete tool. * The session emits the `session.task_complete` event when this tool is executed. */ declare function createTaskCompleteTool(): Tool_2; /** * Creates the tool_search tool that allows the model to discover deferred tools. * * The tool search tool is a custom tool search implementation for the CAPI endpoint. * It searches through all available tools (including deferred ones) using a regex pattern, * and returns matching tool names as `tool_reference` content blocks. * * Deferred tools are sent to the model with `copilot_defer_loading: true` and are not * loaded into context until the model discovers them via this tool. * * See: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#custom-tool-search-implementation */ declare function createToolSearchTool(options: ToolSearchToolOptions): Tool_2; declare const createToolSet: (tools: Tool_2[]) => Record; /** 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; /** 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; } /** * Names of tools that use custom (grammar-based) format instead of standard function format. * These tools accept freeform input (like patch text) rather than structured JSON arguments. * * IMPORTANT: When adding a new custom tool (type: "custom"), add its name here. * This list is used for tool call format conversion when switching between models * that do/don't support custom tools. */ 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; } /** Schema for the `CustomAgentsUpdatedAgent` type. */ 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; } /** Schema for the `CustomAgentsUpdatedData` type. */ 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". */ declare interface CustomAgentsUpdatedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `CustomAgentsUpdatedData` type. */ 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; /** * Type for a custom tool call delta (streaming). */ declare type CustomToolCallDelta = { index: number; id?: string; type?: "custom"; custom?: { name?: string; input?: string; }; }; /** * The input format for the custom tool. Default is unconstrained text. */ declare type CustomToolInputFormat = CustomToolInputFormat.Text | CustomToolInputFormat.Grammar; declare namespace CustomToolInputFormat { /** * Unconstrained free-form text. */ interface Text { /** * Unconstrained text format. Always `text`. */ type: "text"; } /** * A grammar defined by the user. */ interface Grammar { /** * The grammar definition. */ definition: string; /** * The syntax of the grammar definition. One of `lark` or `regex`. */ syntax: "lark" | "regex"; /** * Grammar format. Always `grammar`. */ type: "grammar"; } } /** * Format specification for custom tools that use grammar-based input. */ declare type CustomToolInputFormat_2 = { /** * The type of format. Currently only "grammar" is supported. */ type: "grammar"; /** * The syntax of the grammar (e.g., "lark"). */ syntax: string; /** * The grammar definition. */ 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; }; /** Like {@link DeepPartial} but correctly recurses into `T | undefined` union properties. */ declare type DeepOptional = { [P in keyof T]?: NonNullable extends (infer U)[] ? U[] : NonNullable extends object ? DeepOptional> : T[P]; }; declare type DeepPartial = { [P in keyof T]?: T[P] extends (infer U)[] ? U[] : T[P] extends object ? DeepPartial : 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; /** @deprecated Use {@link UserSettings} instead. */ declare type DefaultConfig = UserSettings; /** * Default feature flags (non-staff, non-experimental). * Use this as a fallback when you don't have access to staff/experimental status. */ export declare const defaultFeatureFlags: Readonly>; /** * When the total tool count exceeds this threshold, MCP and external * tools are automatically marked as deferred (`deferLoading: true`). The model * discovers them at runtime via the tool_search tool instead of loading all * definitions up front. */ 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", /** 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, enables multi-turn subagents with message passing via write_agent tool */ MULTI_TURN_AGENTS = "copilot_cli_multi_turn_agents", /** * 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, surfaces MCP `CallToolResult._meta` (incl. `_meta.ifc`) on `ToolResultExpanded.mcpMeta` for the FIDES labelling engine */ FIDES_IFC = "copilot_cli_fides_ifc", /** When true, uses targeted validation/install prompt guidance */ TARGETED_VALIDATION_PROMPT = "copilot_cli_targeted_validation_prompt", /** 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, 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, 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, splits built-in subagent system messages into static and per-user blocks for improved prompt cache hit rates */ SPLIT_SUBAGENT_SYSTEM_MESSAGE_CACHE = "copilot_cli_split_subagent_system_message_cache", /** When true, reasoning summaries are hidden by default (users can re-enable in-session with ctrl+t) */ REASONING_SUMMARIES_OFF_BY_DEFAULT = "copilot_cli_reasoning_summaries_off_by_default", /** * When true, Gemini models request validated tool choice (`tool_choice: "validated"`) * so CAPI constrains tool calls to the advertised schema. Only applies to Gemini models * when the caller did not request an explicit tool choice. A/B via ExP. */ GEMINI_VALIDATED_TOOL_CHOICE = "copilot_cli_gemini_validated_tool_choice", /** 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 `` 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" } 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; declare type DetachedShellLaunch = { pid: number; cancel(): void; }; export declare type DirectoryAttachment = WireTypes.DirectoryAttachment; declare type DirectoryListingResult = { lines: string[]; entryCount: number; entryCountIsComplete: boolean; exceededLimit: "soft" | "hard" | undefined; sizeBytes: number; }; /** 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; /** JSON Schema for canvas open input */ inputSchema?: CanvasJsonSchema; } /** Schema for the `DiscoveredMcpServer` type. */ 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; } declare interface DisposableTelemetrySender extends TelemetrySender { dispose(): void; setExtraFeatures(features: Record): 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 function 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; /** Directories already scanned (to avoid re-scanning) */ discoveredDirs: Set; /** Source IDs already delivered to the agent (to avoid re-injecting) */ deliveredSourceIds: Set; /** Promise chain that serializes concurrent discovery walks to protect dedupe invariants */ pendingDiscovery: Promise; } declare const editingTools: (config: ToolConfig, logger: RunnerLogger, settings?: RuntimeSettings) => Tool_2[]; declare type EditInput = { path: string; old_str?: string; new_str?: string; }; /** The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed) */ declare type ElicitationCompletedAction = "accept" | "decline" | "cancel"; /** Schema for the `ElicitationCompletedContent` type. */ 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; /** 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; /** List of required field names */ required?: string[]; /** Schema type indicator (always 'object') */ type: "object"; } declare interface ElicitRequestFormParams extends TaskAugmentedRequestParams, Record { mode?: "form"; message: string; requestedSchema: { type: "object"; properties: Record; required?: string[]; }; } declare type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; declare interface ElicitRequestURLParams extends TaskAugmentedRequestParams, Record { mode: "url"; message: string; elicitationId?: string; url: string; } /** * Extends the MCP SDK's ElicitRequestFormParams with an optional toolCallId * so the runtime can correlate elicitation prompts with the tool call visible * to remote UIs. */ declare type ElicitRequestWithToolCallId = ElicitRequestFormParams & { toolCallId?: string; }; declare interface ElicitResult extends Record { action: "accept" | "decline" | "cancel"; content?: Record; _meta?: Record; } /** Schema for the `EmbeddedBlobResourceContents` type. */ 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; } /** Schema for the `EmbeddedBlobResourceContents` type. */ 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; /** Schema for the `EmbeddedTextResourceContents` type. */ declare interface EmbeddedTextResourceContents { /** MIME type of the text content */ mimeType?: string; /** Text content of the resource */ text: string; /** URI identifying the resource */ uri: string; } /** Schema for the `EmbeddedTextResourceContents` type. */ 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; /** Per-source result names. */ names: Record; /** 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; export 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; }; /** Schema for the `EnvAuthInfo` type. */ 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"; } /** * EnvValueMode controls how the value of a key/value pair in the `env` block of an MCP server config is * interpreted. `direct` means the value is used as-is. `indirect` means the value is the name * of an environment variable whose value should be used. */ 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 interface ErrorObject { code: string | null; message: string; param: string | null; type: string; } export declare type ErrorOccurredHook = Hook; /** * Error occurred hook types */ export declare interface ErrorOccurredHookInput extends BaseHookInput { error: Error; errorContext: "model_call" | "tool_execution" | "system" | "user_input"; recoverable: boolean; } export declare interface ErrorOccurredHookOutput { suppressOutput?: boolean; errorHandling?: "retry" | "skip" | "abort"; retryCount?: number; userNotification?: string; } declare type Event_2 = MessageEvent_2 | ResponseEvent | ModelCallFailureEvent_2 | TurnEvent | TruncationEvent_2 | UsageInfoEvent_2 | CompactionEvent | ImageProcessingEvent | BinaryAttachmentRemovalEvent | ModelCallSuccessEvent | ToolExecutionEvent | TelemetryEvent_2 | MessagesSnapshotEvent | EmbeddingRetrievalInjectionEvent; declare type EventData = EventPayload["data"]; declare type EventHandler = (event: EventPayload) => void | Promise; /** 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 = Extract; /** 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 = { /** * 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; /** * 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; } export declare function executeHooks(hooks: Hook[] | undefined, input: TInput, logger: RunnerLogger, hookType?: keyof QueryHooks, emitter?: HookEventEmitter): Promise; export declare function executeNativeDeclarativeHook(hook: NativeDeclarativeHook, input: TInput, logger: RunnerLogger, hookType?: keyof QueryHooks): Promise; /** * Executes preMcpToolCall hooks while threading the current `_meta` through each hook. * * Unlike generic hook output merging, each hook sees the metadata produced by * earlier hooks. This keeps multiple metadata providers composable while * preserving the public `metaToUse` output contract. */ export declare function executePreMcpToolCallHooks(hooks: PreMcpToolCallHook[] | undefined, input: PreMcpToolCallHookInput, logger: RunnerLogger, emitter?: HookEventEmitter): Promise; export declare function executeSingleHook(hook: Hook, input: TInput, logger: RunnerLogger, hookType?: keyof QueryHooks): Promise; /** 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"; } /** * Request for plan approval dialog. */ declare type ExitPlanModeRequest = { /** Summary of the plan written by the agent */ summary: string; /** Exit options shown to the user */ actions: ExitPlanModeAction_2[]; /** Which action should be highlighted and shown first */ recommendedAction: ExitPlanModeAction_2; /** The LLM-assigned tool call ID, threaded from the tool execution context */ 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"; } /** * Response from the plan approval dialog. */ declare type ExitPlanModeResponse = { /** Whether the plan was approved */ approved: boolean; /** Which action the user selected */ selectedAction?: ExitPlanModeAction_2; /** Whether edits should be auto-approved without confirmation */ autoApproveEdits?: boolean; /** Feedback from the user if they requested changes */ feedback?: string; }; /** * Returns env with `CAPI_SANITY_FLAGS_ENV_VAR` expanded into * `COPILOT_CLI_ENABLED_FEATURE_FLAGS`: any flag marked `capiSanity: true` is * appended to (or seeds) the comma-separated enabled-flags list. Returns the * original reference unchanged when the switch is absent or not "true". */ export declare function expandCapiSanityFlagsEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv; /** * Descriptions for experimental feature flags shown in the `/experimental` command help. * This is type-checked to ensure all experimental flags have descriptions. */ export declare const experimentalFeatureFlagDescriptions: ExperimentalFeatureFlags; /** * Type that extracts only the experimental feature flags from FeatureFlagAvailabilityMap. * This ensures that all experimental flags must have descriptions defined. */ declare type ExperimentalFeatureFlags = { [K in keyof FeatureFlagAvailabilityMap as FeatureFlagAvailabilityMap[K]["availability"] extends "experimental" | "staff-or-experimental" ? K : never]: 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; declare type ExpFlagValue = z.infer; /** Value type for ExP (Experiment Platform) flags */ declare const ExpFlagValueSchema: z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>; /** Schema for the `Extension` type. */ 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//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; /** Disable an extension, stop its process, and remove its tools. */ disableExtension(id: string): Promise; /** Reload all extensions from disk. */ reloadExtensions(): Promise; } /** 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; }; /** * 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[]; }; /** Schema for the `ExtensionsAttachmentsPushedData` type. */ 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". */ declare interface ExtensionsAttachmentsPushedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `ExtensionsAttachmentsPushedData` type. */ 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; } /** Schema for the `ExtensionsLoadedData` type. */ declare interface ExtensionsLoadedData { /** Array of discovered extensions and their status */ extensions: ExtensionsLoadedExtension[]; } /** Session event "session.extensions_loaded". */ declare interface ExtensionsLoadedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `ExtensionsLoadedData` type. */ 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"; } /** Schema for the `ExtensionsLoadedExtension` type. */ 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//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; /** * 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"; } /** Serializable external tool request, inferred from the event schema (minus the requestId added by the store). */ declare type ExternalToolRequest = Omit; /** 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; /** Optional tool-specific telemetry */ toolTelemetry?: Record; [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; /** 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"; } /** * Extract ExP flag overrides from a CAPI assignment response. Reused by the CLI * `ExpAssignmentCoordinator` to surface a flat `configFeatures` map; the * `FeatureFlagService` itself feeds the raw response straight to the Rust state * machine and never invokes this wrapper. * * Re-throws as `TypeError` on malformed input so callers that branch on * `instanceof TypeError` keep working (the pre-port code threw a native * `TypeError` when `for...of` was applied to a non-iterable `Configs`, * e.g. `undefined` or `null`). */ export declare function extractExpFlagsFromResponse(response: CopilotExpAssignmentResponse): ExpFlags; declare type ExtraKnownMarketplaces = Record; 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; }; export declare type FeatureFlag = keyof FeatureFlagAvailabilityMap; export declare interface FeatureFlagAssignmentSink { /** Applies the latest CLI-fetched assignments to services owned by this sink. */ setExpAssignments(assignments?: CopilotExpAssignmentResponse): void; } /** * Feature flag availability tiers: * - "on": Available to all users, cannot be turned off * - "team": Only available by default for team members (determined by repo remote URL hash match) * - "staff-or-experimental": Available to staff users OR experimental mode users * - "staff": Only available to staff users * - "experimental": Only available when experimental mode is explicitly enabled * - "off": Always disabled unless explicitly enabled via env var or config */ export declare type FeatureFlagAvailability = "on" | "team" | "staff-or-experimental" | "staff" | "experimental" | "off"; /** * Internal feature flag availability definitions. Defines which tier each flag belongs to. * * @internal Exported for testing only */ export declare const featureFlagAvailability: { readonly FEATURE_FLAG_TEST: { readonly availability: "staff"; readonly capiSanity: false; }; readonly "copilot-feature-agentic-memory": { readonly availability: "on"; readonly capiSanity: false; }; readonly "copilot-feature-agentic-memory-disabled": { readonly availability: "off"; readonly capiSanity: false; }; readonly copilot_feature_agentic_memory_user_scoped: { readonly availability: "on"; readonly capiSanity: false; }; readonly QUEUED_COMMANDS: { readonly availability: "staff"; readonly capiSanity: false; }; readonly AUTOPILOT_OBJECTIVES: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly AUTOPILOT_NO_PROGRESS_STOP: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly DISABLE_WEB_TOOLS: { readonly availability: "off"; readonly capiSanity: false; }; readonly CONTENT_EXCLUSION: { readonly availability: "staff"; readonly capiSanity: false; }; readonly TUIKIT_COMMAND: { readonly availability: "team"; readonly capiSanity: false; }; readonly PLUGINS_DASHBOARD: { readonly availability: "team"; readonly capiSanity: false; }; readonly CHILD_CUSTOM_INSTRUCTIONS: { readonly availability: "staff"; readonly capiSanity: true; }; readonly ON_DEMAND_INSTRUCTIONS: { readonly availability: "on"; readonly capiSanity: false; }; readonly FORGE_AGENT_ENABLED: { readonly availability: "off"; readonly capiSanity: false; }; readonly CLOUD_SESSION_STORE: { readonly availability: "on"; readonly capiSanity: false; }; readonly CHRONICLE_ORG_QUERY: { readonly availability: "off"; readonly capiSanity: false; }; readonly CHRONICLE_REPO_QUERY: { readonly availability: "off"; readonly capiSanity: false; }; readonly COPILOT_GITHUB_TABS: { readonly availability: "on"; readonly capiSanity: false; }; readonly COPILOT_GITHUB_THEME: { readonly availability: "on"; readonly capiSanity: false; }; readonly DOWNGRADE: { readonly availability: "team"; readonly capiSanity: false; }; readonly COLLECT_DEBUG_LOGS: { readonly availability: "staff"; readonly capiSanity: false; }; readonly MCP_ENTERPRISE_ALLOWLIST: { readonly availability: "off"; readonly capiSanity: false; }; readonly ASK_USER_ELICITATION: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly MULTI_TURN_AGENTS: { readonly availability: "experimental"; readonly capiSanity: true; }; readonly EXTENSIONS: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly TOOL_SEARCH: { readonly availability: "experimental"; readonly capiSanity: true; }; readonly TOOL_SEARCH_ANTHROPIC: { readonly availability: "off"; readonly capiSanity: false; }; readonly TOOL_SEARCH_OPENAI: { readonly availability: "off"; readonly capiSanity: false; }; readonly TOOL_SEARCH_CLIENT_OPENAI: { readonly availability: "off"; readonly capiSanity: true; }; readonly TOOL_SEARCH_BUILTIN_ANTHROPIC: { readonly availability: "off"; readonly capiSanity: true; }; readonly TOOL_SEARCH_DISABLED: { readonly availability: "off"; readonly capiSanity: false; }; readonly AVAILABLE_TOOLS_HINT: { readonly availability: "staff-or-experimental"; readonly capiSanity: true; }; readonly DYNAMIC_INSTRUCTIONS_RETRIEVAL: { readonly availability: "off"; readonly capiSanity: true; }; readonly DYNAMIC_INSTRUCTIONS_RETRIEVAL_MCP: { readonly availability: "off"; readonly capiSanity: true; }; readonly DYNAMIC_INSTRUCTIONS_RETRIEVAL_BLACKBIRD: { readonly availability: "off"; readonly capiSanity: false; }; readonly COPILOT_SUBCONSCIOUS: { readonly availability: "team"; readonly capiSanity: false; }; readonly GPT_5_4_MINI_FOR_EXPLORE: { readonly availability: "off"; readonly capiSanity: false; }; readonly BACKGROUND_SESSIONS: { readonly availability: "staff-or-experimental"; readonly capiSanity: false; }; readonly SANDBOX: { readonly availability: "staff-or-experimental"; readonly capiSanity: false; }; readonly EVERY_AND_AFTER: { readonly availability: "staff-or-experimental"; readonly capiSanity: false; }; readonly VOICE: { readonly availability: "on"; readonly capiSanity: false; }; readonly RUBBER_DUCK_AGENT: { readonly availability: "on"; readonly capiSanity: false; }; readonly COMPUTER_USE: { readonly availability: "staff"; readonly capiSanity: false; }; readonly MCP_REGISTRY_INSTALL: { readonly availability: "on"; readonly capiSanity: false; }; readonly SESSION_INDEXING: { readonly availability: "on"; readonly capiSanity: false; }; readonly CLI_CLOUD_SESSIONS: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly CLI_WORKTREE: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly SESSION_INDEXING_REPO: { readonly availability: "staff"; readonly capiSanity: false; }; readonly REMOTE_JSON_RPC: { readonly availability: "on"; readonly capiSanity: false; }; readonly SUBAGENT_PARALLELISM_PROMPTS: { readonly availability: "off"; readonly capiSanity: true; }; readonly CHILD_GIT_REPO_SCAN: { readonly availability: "staff"; readonly capiSanity: false; }; readonly COPILOT_ASSOCIATE_COMPUTE: { readonly availability: "off"; readonly capiSanity: false; }; readonly GITHUB_CONTEXT_SIDEKICK_AGENT: { readonly availability: "off"; readonly capiSanity: false; }; readonly GITHUB_CONTEXT_SIDEKICK_AGENT_FULL: { readonly availability: "off"; readonly capiSanity: false; }; readonly PROMPT_FRAME: { readonly availability: "on"; readonly capiSanity: false; }; readonly INLINE_IMAGES: { readonly availability: "staff-or-experimental"; readonly capiSanity: false; }; readonly REMOTE_KICKSTART: { readonly availability: "team"; readonly capiSanity: false; }; readonly READ_AGENT_INCREMENTAL_READS: { readonly availability: "team"; readonly capiSanity: false; }; readonly TGREP: { readonly availability: "off"; readonly capiSanity: false; }; readonly MCP_TASKS: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly MCP_TASKS_SEP2669: { readonly availability: "off"; readonly capiSanity: false; }; readonly MCP_TASKS_SEP2694: { readonly availability: "off"; readonly capiSanity: false; }; readonly BASH_OUTPUT_COMPACTION: { readonly availability: "team"; readonly capiSanity: true; }; readonly SEARCH_TOOL_OUTPUT_COMPACTION: { readonly availability: "team"; readonly capiSanity: true; }; readonly MCP_APPS: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly FIDES_IFC: { readonly availability: "off"; readonly capiSanity: false; }; readonly ANTHROPIC_ADVISOR: { readonly availability: "off"; readonly capiSanity: false; }; readonly SECURITY_REVIEW: { readonly availability: "on"; readonly capiSanity: false; }; readonly WORKTREE: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly REWIND_V2: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly DIFF_V2: { readonly availability: "experimental"; readonly capiSanity: false; }; readonly COPILOT_AGENTS_TAB: { readonly availability: "team"; readonly capiSanity: false; }; readonly TARGETED_VALIDATION_PROMPT: { readonly availability: "off"; readonly capiSanity: true; }; readonly ASYNC_ONLY_SHELL: { readonly availability: "off"; readonly capiSanity: true; }; readonly NO_PLANNING: { readonly availability: "off"; readonly capiSanity: true; }; readonly NO_VIEW_LINE_NUMBERS: { readonly availability: "off"; readonly capiSanity: true; }; readonly LSP_SERVICES_PROMPT: { readonly availability: "off"; readonly capiSanity: true; }; readonly REMOTE_EXPORT_MAX_EVENTS_PER_FLUSH: { readonly availability: "off"; readonly capiSanity: false; }; readonly REMOTE_EXPORT_SAFETY_INTERVAL_MS: { readonly availability: "off"; readonly capiSanity: false; }; readonly PRESERVE_REASONING: { readonly availability: "off"; readonly capiSanity: false; }; readonly REASONING_ONLY_CONTINUATION: { readonly availability: "team"; readonly capiSanity: true; }; readonly FAILBOT_ERROR_REPORTING: { readonly availability: "on"; readonly capiSanity: false; }; readonly SPLIT_SUBAGENT_SYSTEM_MESSAGE_CACHE: { readonly availability: "team"; readonly capiSanity: true; }; readonly SKILLS_LIST_IN_SYSTEM_PROMPT: { readonly availability: "off"; readonly capiSanity: true; }; readonly RELAY_CLIENT: { readonly availability: "off"; readonly capiSanity: false; }; readonly CLOUD_VIA_RELAY: { readonly availability: "off"; readonly capiSanity: false; }; readonly REASONING_SUMMARIES_OFF_BY_DEFAULT: { readonly availability: "off"; readonly capiSanity: false; }; readonly TIMELINE_TOUCHUP: { readonly availability: "on"; readonly capiSanity: false; }; readonly GEMINI_VALIDATED_TOOL_CHOICE: { readonly availability: "off"; readonly capiSanity: true; }; readonly NO_OUTER_LOOP_TRUNCATION: { readonly availability: "off"; readonly capiSanity: false; }; }; declare type FeatureFlagAvailabilityMap = typeof featureFlagAvailability; /** Callback type for feature flag change listeners */ export declare type FeatureFlagChangeListener = (flags: FeatureFlags, expFlags: ExpFlags, expResponse: CopilotExpAssignmentResponse) => void; /** Options for initializing feature flags */ export declare interface FeatureFlagInitOptions { /** Whether the user is a staff member (from config) */ isStaff: boolean; /** Whether experimental mode is enabled */ isExperimental: boolean; /** Whether the user is in a team repository */ isTeam: boolean; /** Whether streamer mode is enabled. Used by the CLI ExP coordinator, not core flag resolution. */ streamerMode?: boolean; /** Optional config object for config-based overrides */ config?: DefaultConfig; /** Timestamp of first CLI launch. Used by the CLI ExP coordinator, not core flag resolution. */ firstLaunchAt?: Date; /** Static overrides for feature flags (e.g. from RuntimeSettings.featureFlags or tests) */ flagOverrides?: Partial>; /** Static overrides for ExP experiment flags (e.g. for tests without ExP infrastructure) */ expFlagOverrides?: Partial>; /** Runtime settings carried for CLI coordinator consumers; not used by core flag resolution. */ settings?: RuntimeSettings; } declare interface FeatureFlagResolutionOptions { baseFlags?: FeatureFlags; env?: NodeJS.ProcessEnv; config?: DefaultConfig; flagOverrides?: Partial>; } /** Resolved feature flags with boolean values for runtime use */ export declare type FeatureFlags = Readonly>; /** * Service for accessing feature flags for one runtime owner. * * The core service owns pure feature flag resolution and ExP assignment state. * CLI-specific ExP fetching, caching, auth subscription, and telemetry live in * CLI modules and inject assignment responses through `setExpAssignments`. * * Implemented as a thin TypeScript shim around the Rust-owned state machine in * `crate::feature_flag_service::ServiceState`. The shim: * - allocates a native handle in the constructor and threads it through every * state-mutating call, * - caches the snapshot returned by each mutation so synchronous getters can * serve reads without an FFI hop, * - keeps async wrappers, listener notification, and `waitForExpResponse` * waiters in JS, where Promise / Set primitives belong. */ export declare class FeatureFlagService implements SessionFeatureFlagService { private readonly handle; private snapshot; private readonly listeners; /** * Mutable working copy of the active config. We track this JS-side so that * `applyConfigOverride({ memory: undefined })` reproduces JS spread * semantics exactly (the undefined entry overrides any prior value before * `JSON.stringify` drops it). The Rust state machine treats every * `applyConfigOverride` call as a full replacement. */ private currentConfig; /** Tracks whether the initial ExP response has been supplied */ private expFetchStatus; /** Callbacks waiting for the initial ExP response to complete */ private expFetchWaiters; /** * CAPI assignment context retained JS-side for telemetry. The pre-port * code stored this as a plain field; keeping it in JS preserves the * sync-getter contract (no FFI hop per call) and matches the original * `.trim()`-then-store semantics exactly. */ private latestSecondaryAssignmentContext; constructor(options: FeatureFlagInitOptions, constructorOptions?: FeatureFlagServiceConstructorOptions); /** * Disposable hook for session-scoped lifetime management. Routes to the * existing `destroy()` path so the native handle is released when the * owning session is disposed. Both `dispose()` and `destroy()` are * idempotent, so the call is safe to make more than once. */ dispose(): void; /** * Creates a deferred FeatureFlagService for tests that need to exercise * wait-for-assignment behavior without a CLI ExP client. */ static createForTest(options: FeatureFlagInitOptions): FeatureFlagService; /** * Resets the service instance. Primarily for testing purposes. */ resetInstance(): void; resetExpResponse(): void; setExpAssignments(assignments?: CopilotExpAssignmentResponse): void; getLegacyFlag(flag: FeatureFlag): boolean; getFlag(flag: FeatureFlag): Promise; getAllFlags(): FeatureFlags; getExpFlag(flag: ExpFlagKey): Promise; getFlagWithExpOverride(expFlag: ExpFlagKey, featureFlag: FeatureFlag): Promise; /** * Whether the gpt-5.4-mini default model for explore subagents is enabled. * Awaits the ExP assignment for `copilot_cli_gpt_5_4_mini_for_explore`; * falls back to the `GPT_5_4_MINI_FOR_EXPLORE` feature flag when ExP has no assignment. */ isGpt54MiniForExploreEnabled(): Promise; /** * Resolves the arm of the three-arm dynamic instruction retrieval * experiment from the `copilot_cli_dynamic_instructions_retrieval_arm` ExP * flag. Returns undefined when ExP has no (or an unrecognised) assignment, * letting callers fall back to the standalone DYNAMIC_INSTRUCTIONS_RETRIEVAL * (+ Blackbird) feature flags. */ getDynamicInstructionsRetrievalArm(): Promise; /** * Whether embedding-based retrieval of MCP server instructions is enabled. * Awaits the ExP assignment for `copilot_cli_dynamic_instructions_retrieval_mcp`; * falls back to the `DYNAMIC_INSTRUCTIONS_RETRIEVAL_MCP` feature flag when ExP has * no assignment. Gated separately from skill retrieval. */ isDynamicInstructionsRetrievalMcpEnabled(): Promise; /** * Whether the GPT default model experiment is enabled. * Awaits the ExP assignment for `copilot_cli_gpt_default_model`. */ isGptDefaultModelEnabled(): Promise; /** * Whether MCP `_meta` (FIDES IFC) surfacing on `ToolResultExpanded.mcpMeta` is enabled. * Awaits the ExP assignment for `copilot_cli_fides_ifc`; * falls back to the `FIDES_IFC` feature flag when ExP has no assignment. */ isFidesIfcEnabled(): Promise; /** * Whether the Copilot Subconscious experiment is enabled. * Awaits the ExP assignment for `copilot_cli_subconscious`; * falls back to the `COPILOT_SUBCONSCIOUS` feature flag when ExP has no assignment. */ isCopilotSubconsciousEnabled(): Promise; /** * Whether preserved reasoning (`reasoning.context: "all_turns"`) is enabled. * Awaits the ExP assignment for `copilot_cli_preserve_reasoning`; * falls back to the `PRESERVE_REASONING` feature flag when ExP has no assignment. */ isPreserveReasoningEnabled(): Promise; /** * Whether built-in subagent system messages should be split into static and per-user blocks for cache optimization. * Awaits the ExP assignment for `copilot_cli_split_subagent_system_message_cache`; * falls back to the `SPLIT_SUBAGENT_SYSTEM_MESSAGE_CACHE` feature flag when ExP has no assignment. */ isSplitSubagentSystemMessageCacheEnabled(): Promise; /** * Whether reasoning summaries should be hidden by default. * Awaits the ExP assignment for `copilot_cli_reasoning_summaries_off_by_default`; * falls back to the `REASONING_SUMMARIES_OFF_BY_DEFAULT` feature flag when ExP has no assignment. */ isReasoningSummariesOffByDefaultEnabled(): Promise; /** * Whether Gemini models should request validated tool choice. * Awaits the ExP assignment for `copilot_cli_gemini_validated_tool_choice`; * falls back to the `GEMINI_VALIDATED_TOOL_CHOICE` feature flag when ExP has no assignment. */ isGeminiValidatedToolChoiceEnabled(): Promise; /** * Whether a reasoning-only completed turn should be nudged to continue * instead of stopping silently. Awaits the ExP assignment for * `copilot_cli_reasoning_only_continuation`; falls back to the * `REASONING_ONLY_CONTINUATION` feature flag when ExP has no assignment. */ isReasoningOnlyContinuationEnabled(): Promise; /** * Returns a promise that resolves once the initial ExP response has completed. * If the response has already been supplied, resolves immediately. * * Use this to gate work that requires ExP assignment context (e.g. * experimentation-critical telemetry). */ waitForExpResponse(): Promise; getAllExpFlagsSync(): ExpFlags; getLatestExpResponse(): CopilotExpAssignmentResponse; /** * Gets the latest cached assignment context if available. * Returns undefined if no ExP response has been fetched yet or if the fetch failed. * This is a synchronous accessor for telemetry purposes - it returns immediately * without waiting for any pending ExP requests. * * @returns The assignment context string, or undefined if not available */ getLatestAssignmentIfPresent(): string | undefined; getSecondaryAssignmentIfPresent(): string | undefined; captureSecondaryAssignmentContext(assignmentContext: string): void; /** * Subscribes to feature flag changes. * The listener will be called whenever flags are updated. * * @param listener Callback function that receives the new flags and expFlags * @returns Unsubscribe function - call this to remove the listener * * @example * const unsubscribe = service.subscribe((flags, expFlags) => { * console.log("New flags:", flags, expFlags); * }); * // When done: * unsubscribe(); */ subscribe(listener: FeatureFlagChangeListener): () => void; applyConfigOverride(partialConfig: Partial): void; /** * Release the native handle held by this service. Idempotent; the * `FinalizationRegistry` also runs the same release on GC. */ destroy(): void; private resolveWaiters; private notifyListeners; } declare interface FeatureFlagServiceConstructorOptions { deferExpResponse?: boolean; } /** * Per-flag specification. Every feature flag in `featureFlagAvailability` * must declare both fields explicitly — we deliberately have no string * shorthand so that adding a new flag forces a conscious decision about * each piece of metadata. * * - `availability`: the tier that gates default visibility (see * `FeatureFlagAvailability`). * - `capiSanity`: when true, the flag is force-enabled in the CAPI sanity * smoke tests (set `COPILOT_CLI_ENABLE_CAPI_SANITY_FLAGS=true` to flip the * switch). Set this to `true` when toggling the flag materially changes * what the CLI sends to or receives from CAPI — e.g. request transport, * advertised tools, beta headers, or system-prompt content — so the * live-CAPI workflow exercises the alternate code path. Set it to `false` * when the flag only flips local UX (themes, layouts), local execution * backends, debug commands, or kill-switches. Also set it to `false` for * flags that require beta-header allowlisting on the test integration ID * (see ANTHROPIC_ADVISOR's CI history). */ export declare interface FeatureFlagSpec { availability: FeatureFlagAvailability; capiSanity: boolean; } /** * Mapping from FeatureFlag names to their corresponding ExP flag keys. * Used by feature flag services to check COPILOT_EXP_* env overrides and * by async flag resolution to look up ExP experiments for a given feature flag. */ export declare const featureFlagToExpFlag: Partial>; /** * 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_2 | undefined; declare const FETCH_DOCUMENTATION_TOOL_NAME = "fetch_copilot_cli_documentation"; export declare type FileAttachment = WireTypes.FileAttachment; /** * Metrics for file editing operations (numeric values only). * Used by file-editing tools to report line changes in their telemetry metrics. */ declare type FileEditedMetrics = { /** Number of lines added in the edit operation */ linesAdded: number; /** Number of lines removed in the edit operation */ linesRemoved: number; }; /** * Properties for file editing operations (string values). * Used by file-editing tools to report file paths in their telemetry properties. */ declare type FileEditedRestrictedProperties = { /** Paths of all files that were edited, JSON-encoded */ filePaths: string; /** Paths of files that were added (created), JSON-encoded */ addedPaths?: string; /** Paths of files that were deleted, JSON-encoded */ deletedPaths?: string; }; export declare class FileLogger extends BaseLogger implements RunnerLogger, LogWriter { private readonly filePath; private readonly queue; constructor(filePath: string, logLevel?: LogLevel, debugEnvironmentVariables?: string[]); /** Promise that resolves when pending writes are complete. Used to serialize * writes and for testing. */ get writeQueue(): Promise; outputPath(): 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; /** @internal Exported for testing only. */ get stats(): CoalescingWriteQueueStats; write(category: string, message: string): void; /** Implementation for LogWriter interface */ writeLog(level: LogLevel_2, message: string): Promise; } /** * 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; /** * 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; } /** Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. */ declare type FilterMapping = Record | ContentFilterMode_2; /** * 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; }[]; /** * Flattens the FeatureFlagSpec map down to a plain `{ name: availabilityTier }` * map for the Rust resolver, which only knows about tiers. Per-flag metadata * (like `capiSanity`) is handled entirely on the TS side before hitting Rust. */ export declare function flattenAvailabilityMap(): Record; /** 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; } /** * Formats bytes into a human-readable string (e.g., "1.5 MB", "48 KB"). */ declare function formatBytes(bytes: number): string; declare interface FunctionDefinition { /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain * underscores and dashes, with a maximum length of 64. */ name: string; /** * A description of what the function does, used by the model to choose when and * how to call the function. */ description?: string; /** * The parameters the functions accepts, described as a JSON Schema object. See the * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, * and the * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for * documentation about the format. * * Omitting `parameters` defines a function with an empty parameter list. */ parameters?: FunctionParameters; /** * Whether to enable strict schema adherence when generating the function call. If * set to true, the model will follow the exact schema defined in the `parameters` * field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn * more about Structured Outputs in the * [function calling guide](https://platform.openai.com/docs/guides/function-calling). */ strict?: boolean | null; } /** * The parameters the functions accepts, described as a JSON Schema object. See the * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, * and the * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for * documentation about the format. * * Omitting `parameters` defines a function with an empty parameter list. */ declare type FunctionParameters = { [key: string]: unknown; }; /** * Type for a function tool call delta (streaming). */ declare type FunctionToolCallDelta = { index: number; id?: string; type?: "function"; function?: { name?: string; arguments?: string; }; }; /** * Generates a message to tell the LLM where to find the large output. */ declare function generateLargeOutputMessage(filePath: string, originalSizeBytes: number, preview: string, grepToolName?: string, contentKind?: string): string; declare interface GenerationalHolder { value?: T; lock?: Promise; invalidated?: boolean; generation?: number; } /** * Returns names of current tools that were not in `previousNames`. */ declare function getAddedToolsByName(previousNames: string[], currentTools: Tool_2[]): string[]; /** * Retrieves the list of available models based on availability, policies, and integration including * capabilities and billing information, which may be cached from previous calls. * * This list is in order of preference to be the default model for new sessions where the first model is * the most preferred. It can be empty if no models are available. * * @deprecated Used solely by vscode-copilot-chat extension, use {@link retrieveAvailableModels} instead. */ export declare function getAvailableModels(authInfo: AuthInfo): Promise; /** * Returns every feature flag marked `capiSanity: true` in the availability * map. The order matches insertion order in `featureFlagAvailability`. */ 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; /** * 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[]; }; /** * Signal to abort the completion request. */ abortSignal?: AbortSignal; /** * An optional identifier for the completion with tools call. This can be used for logging * and tracing purposes. */ callId?: string; /** * The reasoning effort level for the model to use, if supported by the client. */ reasoningEffort?: ReasoningEffort_3; /** * 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; /** * 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_2[] | undefined | Promise; /** * 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>; }; /** * Returns the list of temp files that have been created (for testing). */ declare function getCreatedTempFiles(): ReadonlyArray<{ sessionFs: SessionFs; filePath: string; }>; /** Gets the list of available custom agents. */ export declare function getCustomAgents(authInfo: AuthInfo, workingDir: string, integrationId?: string, logger?: RunnerLogger, settings?: RuntimeSettings, additionalPlugins?: InstalledPlugin[]): Promise; /** * Extracts the underlying model class from a custom model ID. * Custom model IDs follow the format `org/key/model-class`. * Returns undefined if the ID doesn't match the expected format. */ export declare function getCustomModelClass(model: Model): string | undefined; /** * Returns the environment variable name for an ExP flag override. * Convention: `COPILOT_EXP_` + upper-cased flag name with hyphens replaced by underscores. */ export declare function getExpFlagEnvKey(flag: ExpFlagKey): string; declare function getGrepToolNameFromTools(tools: readonly Pick[]): string | undefined; /** * Extract MCP server and tool name from a tool's metadata. * Prefers explicit `mcpServerName`/`mcpToolName` when set. * Falls back to splitting `namespacedName` on the last "/". * * @returns The MCP server and tool names, or undefined for non-MCP tools. */ declare function getMcpInfo(tool: Pick): { mcpServerName: string; mcpToolName: string; } | undefined; export declare function getPostToolUseFailureError(toolResult: ToolResultExpanded): string; /** * Returns tool names from `previousNames` that are not in the current tool list. */ declare function getRemovedToolsByName(previousNames: string[], currentTools: Tool_2[]): string[]; declare function getStrReplaceEditorArgsOrNull(toolCall: CopilotChatCompletionMessageToolCall): StrReplaceEditorArgs | null; declare function getToolDeniedWithoutUserRequest(isAutopilotMode?: boolean): Readonly; /** * Extracts unique tool names from assistant tool_calls in the chat history. * Returns undefined if no tool calls are found (i.e., the model never called any tools). * This is used on session resume to determine which tools the model has "seen" — * only tools it actually called need a removal notice, since the model has no * memory of tools it never invoked beyond the current system prompt. */ declare function getToolNamesFromHistory(messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): string[] | undefined; /** * Returns the registration source of a tool. `source` is required on every tool, so this * is a thin accessor; it exists as a named call site for tool-filtering code paths that * want to be explicit about reading classification metadata rather than tool fields. */ declare function getToolSource(tool: ToolMetadata): ToolSource; /** 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; }; /** Schema for the `GhCliAuthInfo` type. */ 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: RuntimeSettings, repo: string, repoLocation: string, branchName: string, commitCount?: number, baseCommit?: string, execOptions?: RunnerExecOptions) => Promise; /** * 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: RuntimeSettings, branchName: string, repoLocation: string, commitMessage: string, allowEmptyCommit?: boolean, noVerify?: boolean, execOptions?: RunnerExecOptions) => Promise; /** * 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: RuntimeSettings, branchName: string, repoLocation: string, commitMessage: string, allowEmptyCommit?: boolean, noVerify?: boolean, execOptions?: RunnerExecOptions) => Promise; /** * Stages all changes in the repository (including new files). * * @param repoLocation The location of the repository. */ stageChanges(repoLocation: string, execOptions?: RunnerExecOptions): Promise; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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; execReadOnlyGit(gitArgs: string[], execOptions: RunnerExecOptions, filteredCmdArgs?: string[]): Promise; } declare const GITHUB_MCP_SERVER_NAME = "github-mcp-server"; 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.ZodObject<{ type: z.ZodLiteral<"github_reference">; number: z.ZodNumber; title: z.ZodString; referenceType: z.ZodEnum<["issue", "pr", "discussion"]>; state: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { number: number; url: string; type: "github_reference"; title: string; referenceType: "issue" | "pr" | "discussion"; state: string; }, { number: number; url: string; type: "github_reference"; title: string; referenceType: "issue" | "pr" | "discussion"; state: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_commit">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; oid: z.ZodString; message: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { message: string; url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_commit"; oid: string; }, { message: string; url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_commit"; oid: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_release">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; tagName: z.ZodString; name: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { url: string; name: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_release"; tagName: string; }, { url: string; name: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_release"; tagName: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_actions_job">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; jobId: z.ZodNumber; jobName: z.ZodString; workflowName: z.ZodString; url: z.ZodString; conclusion: z.ZodOptional; }, "strip", z.ZodTypeAny, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_actions_job"; jobId: number; jobName: string; workflowName: string; conclusion?: string | undefined; }, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_actions_job"; jobId: number; jobName: string; workflowName: string; conclusion?: string | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"github_repository">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; url: z.ZodString; description: z.ZodOptional; ref: z.ZodOptional; }, "strip", z.ZodTypeAny, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_repository"; description?: string | undefined; ref?: string | undefined; }, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_repository"; description?: string | undefined; ref?: string | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"github_file_diff">; url: z.ZodString; head: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; }, "strip", z.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.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; }, "strip", z.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.ZodTypeAny, { url: string; type: "github_file_diff"; 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; }, { url: string; type: "github_file_diff"; 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.ZodObject<{ type: z.ZodLiteral<"github_tree_comparison">; url: z.ZodString; base: z.ZodObject<{ repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; revision: z.ZodString; }, "strip", z.ZodTypeAny, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }>; head: z.ZodObject<{ repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; revision: z.ZodString; }, "strip", z.ZodTypeAny, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }>; }, "strip", z.ZodTypeAny, { url: string; type: "github_tree_comparison"; head: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; base: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; }, { url: string; type: "github_tree_comparison"; head: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; base: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; }>, z.ZodObject<{ type: z.ZodLiteral<"github_url">; url: z.ZodString; }, "strip", z.ZodTypeAny, { url: string; type: "github_url"; }, { url: string; type: "github_url"; }>, z.ZodObject<{ type: z.ZodLiteral<"github_file">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_file"; ref: string; }, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_file"; ref: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_snippet">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; url: z.ZodString; lineRange: z.ZodObject<{ start: z.ZodNumber; end: z.ZodNumber; }, "strip", z.ZodTypeAny, { start: number; end: number; }, { start: number; end: number; }>; }, "strip", z.ZodTypeAny, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_snippet"; lineRange: { start: number; end: number; }; ref: string; }, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_snippet"; lineRange: { start: number; end: 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. */ enableInsidersMode?: boolean; } 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; /** * Returns true when the GPT model version supports tool search. * Supported: GPT-5.4 and later (major > 5, or major === 5 && minor >= 4). */ declare function 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; }; declare function handleProgressReport(prDescription: string, branchName: string, logger: RunnerLogger, callbackRuntime?: IAgentCallback): Promise<{ isError: boolean; }>; /** * Handler for the "view" command * * TODO(permissions-improvement) * The user may have configured file denial e.g. !View(.secrets/**), so we should have permissions * checks here as well. */ declare function handleViewCommand(input: StrReplaceEditorArgs & { command: typeof VIEW_TOOL_NAME; }, baseToolTelemetry: StrReplaceEditorTelemetry, permissions: PermissionsConfig, logger: RunnerLogger, options?: ToolCallbackOptions, lineNumbers?: boolean): Promise; /** 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; } 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"; /** * Returns true when a model has issues that prevent it from being used. */ export declare function hasModelIssues(model: Model): boolean; declare type HeadersRefreshCallback = (request: HeadersRefreshRequest) => Promise | undefined> | Record | 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}) */ export declare const HELP_VISIBLE_MODELS: readonly SupportedModel[]; /** * Models that are not publicly visible by default. The canonical set lives * in the Rust runtime. * * **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) */ export declare const HIDDEN_MODELS: ReadonlySet; /** 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; }; /** Schema for the `HMACAuthInfo` type. */ 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"; } export declare type Hook = CallbackHook | NativeDeclarativeHook; /** * A validated hook block result: decision is "block" and reason is guaranteed present. * Use {@link isHookBlock} to narrow a hook output to this type. */ export declare interface HookBlock { decision: "block"; reason: string; } /** * Decision returned by hooks that can block an operation. * - "block": The operation is denied. Must be accompanied by a `reason`. * - "allow": Explicitly permits the operation (same as omitting `decision`). */ export declare type HookBlockDecision = "block" | "allow"; /** 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"; } /** Callback for emitting hook lifecycle events from within executeHooks. */ export declare type HookEventEmitter = { emitHookStart(data: HookStartEvent["data"]): void; emitHookEnd(data: HookEndEvent["data"]): void; }; /** * A hook's handler — the function invoked when the hook runs. Hooks supplied by * SDK consumers, loaded from config, or produced by plugins are all reduced to * this signature before the runtime invokes them. */ export declare type HookHandler = (input: TInput) => Promise; /** * 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; }; /** 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"; } declare type HooksObject = z_2.infer; /** Schema for the hooks object shared by dedicated hook config files and settings/config files. */ declare const _HooksObjectSchema: z_2.ZodObject<{ sessionStart: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, z_2.ZodObject<{ type: z_2.ZodLiteral<"prompt">; prompt: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { type: "prompt"; prompt: string; }, { type: "prompt"; prompt: string; }>]>, "many">>; sessionEnd: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; userPromptSubmitted: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; preToolUse: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; preMcpToolCall: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; postToolUse: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; postToolUseFailure: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; errorOccurred: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; agentStop: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; subagentStop: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; subagentStart: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; preCompact: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; permissionRequest: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; notification: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; }, "passthrough", z_2.ZodTypeAny, z_2.objectOutputType<{ sessionStart: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, z_2.ZodObject<{ type: z_2.ZodLiteral<"prompt">; prompt: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { type: "prompt"; prompt: string; }, { type: "prompt"; prompt: string; }>]>, "many">>; sessionEnd: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; userPromptSubmitted: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; preToolUse: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; preMcpToolCall: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; postToolUse: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; postToolUseFailure: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; errorOccurred: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; agentStop: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; subagentStop: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; subagentStart: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; preCompact: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; permissionRequest: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; notification: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; }, z_2.ZodTypeAny, "passthrough">, z_2.objectInputType<{ sessionStart: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, z_2.ZodObject<{ type: z_2.ZodLiteral<"prompt">; prompt: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { type: "prompt"; prompt: string; }, { type: "prompt"; prompt: string; }>]>, "many">>; sessionEnd: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; userPromptSubmitted: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; preToolUse: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; preMcpToolCall: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; postToolUse: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; postToolUseFailure: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; errorOccurred: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; agentStop: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; subagentStop: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; }>]>, "many">>; subagentStart: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; preCompact: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; permissionRequest: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; notification: z_2.ZodOptional; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; allowedEnvVars?: string[] | undefined; }>, z_2.ZodEffects>; bash: z_2.ZodOptional; powershell: z_2.ZodOptional; command: z_2.ZodOptional; /** * Path to a native executable. When set, the hook is spawned directly * (no shell wrapper). Mutually exclusive with bash/powershell/command. * Used by policy hooks (e.g. Defender scanning executables). */ exec: z_2.ZodOptional; /** Arguments passed to the native executable specified by `exec`. */ args: z_2.ZodOptional>; cwd: z_2.ZodOptional; env: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; } & { matcher: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, { type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>, Omit<{ type: "command"; timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }, "timeout" | "command">, { timeout?: number | undefined; cwd?: string | undefined; env?: Record | undefined; command?: string | undefined; exec?: string | undefined; type?: "command" | undefined; bash?: string | undefined; powershell?: string | undefined; args?: string[] | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; matcher?: string | undefined; }>]>, "many">>; }, z_2.ZodTypeAny, "passthrough">>; /** * Formats a ` from ""` suffix for hook diagnostic log messages, or an * empty string when the source is unknown. * * This is for CLI/log output only — never surfaced to the model. */ export declare function hookSourceLogSuffix(source: string | undefined): string; declare class HooksProcessor implements IPreToolsExecutionProcessor, IPostToolExecutionProcessor { private readonly logger; private readonly commonHookContext; private readonly preEditsHooks; private readonly postEditsHooks; private readonly preCommitHooks; private readonly prePRDescriptionHooks; private readonly postResultHooks; private readonly nativeSecretScanningHandle; private readonly nativeSecretScanningFinalizerToken; private userHooks?; /** * Called when a preToolUse hook explicitly allows a tool call (`permissionDecision: "allow"`). * Wires the approval into the session's permission gate so the tool is not re-prompted. */ private onToolCallAllowed?; /** Called when a preToolUse or postToolUse hook returns `additionalContext` for a tool call. */ private onAdditionalContext?; /** * Called at the start of each `preToolsExecution` batch to clear stale hook-allowed tool * call IDs from the session's permission store. Prevents an `allow` decision from one batch * from leaking into later batches when a model call reuses the same `toolCallId`. */ private onClearBatch?; constructor(commonHookContext: CommonHookContext, initialHooks?: AgentHook[]); /** * Registers a callback invoked when a preToolUse hook returns `permissionDecision: "allow"`. * For CLI sub-agents, pass `(id) => pendingRequests.addHookAllowedToolCallId(id)` so the * session's permission gate auto-approves the tool without re-prompting the user. */ setOnToolCallAllowed(callback: (toolCallId: string) => void): void; /** * Registers a callback invoked when a preToolUse or postToolUse hook returns `additionalContext`. * On the top-level CLI path this context is injected into the next model turn; for * sub-agents that injection happens inside `Agent.agent()` which is not exposed here, * so callers should collect and apply the context through the agent loop themselves. */ setOnAdditionalContext(callback: (toolCallId: string, context: string) => void): void; /** * Registers a callback invoked at the start of each `preToolsExecution` batch. * For CLI sub-agents, pass `() => pendingRequests.clearHookAllowedToolCallIds()` to * prevent `allow` decisions from one batch leaking into subsequent batches. */ setOnClearBatch(callback: () => void): void; toJSON(): string; addHook(hook: AgentHook): HooksProcessor; addUserHooksFromRepoConfig(): Promise; /** * Loads hooks from installed plugins and merges them with existing user hooks. * Plugin hooks use the plugin directory as the working directory for commands. * * @param installedPlugins - List of installed plugins to load hooks from * @param settings - Optional runtime settings * @returns An object with `hookCount` (total individual hooks loaded) and `pluginCount` (plugins that provided hooks) */ addHooksFromInstalledPlugins(installedPlugins: InstalledPlugin[], settings?: RuntimeSettings): Promise<{ hookCount: number; pluginCount: number; }>; setUserHooks(userHooks: QueryHooks): Promise; createMcpToolCallInterceptor(): McpToolCallInterceptor; preSession(source: "new" | "resume", initialPrompt: string): Promise; postSession(): Promise; userPrompt(prompt: string): Promise; applyPrePRDescriptionHooks(prDescription: string): Promise; preToolsExecution(context: PreToolsExecutionContext): Promise>; private withoutPreComputedToolCalls; private runUserPreToolUseHooks; /** * Execute out-of-proc SDK `preToolUse` callback hooks per (hook, tool call) * in TypeScript. Mirrors the primary session path * (`PreToolUseHooksProcessor` in session.ts): policy hooks run first, a * denial is terminal for that tool call, `allow` marks the call pre-approved, * `modifiedArgs` rewrites the arguments, and `additionalContext` is always * forwarded. There is no interactive permission prompt available here, so an * `ask` decision is treated as a denial. Hooks fail closed on error and fail * open on a runtime-imposed timeout. */ private runCallbackPreToolUseHooks; private runNativeSecretScanningPreCommit; private runPreCommitHooks; private getReportProgressCalls; private extractCommitMessagesByCallId; private applyRedactedCommitMessage; private runPreEditHooks; postToolExecution(context: PostToolExecutionContext): Promise; onResult(currentCommitHash: string): Promise; private runUserPostToolUseHooks; /** * Execute out-of-proc SDK `postToolUse` callback hooks per-hook in * TypeScript. Mirrors the primary session path * (`PostToolUseHooksProcessor` in session.ts): policy hooks run first, a * `block` decision scrubs the result and is terminal, `modifiedResult` is * applied via `Object.assign` so later hooks observe the running mutation, * and every non-empty `additionalContext` is aggregated and appended once. * Policy hooks fail closed (scrub) on error; non-policy hooks fail open. */ private runCallbackPostToolUseHooks; private runUserPostToolUseFailureHooks; /** * Execute out-of-proc SDK `postToolUseFailure` callback hooks per-hook in * TypeScript. Each hook may return `additionalContext`; the non-empty * strings are aggregated and appended once to the tool's `textResultForLlm`, * mirroring the native path. */ private runCallbackPostToolUseFailureHooks; private runPostResultHooks; private prepareNativeProcessorHooks; private runNativeEventHooks; private nativeProcessorRunEnv; private commonNativeInput; private toNativeToolCall; private applyModifiedArgs; private applyToolResultJson; private stringifyJson; private replayNativeLogs; private replayNativeSecretScanningLogs; private runNativeSecretScanningPrePRDescription; private isNativeSecretScanningEnabled; private hookLogger; } /** 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; }; /** Current color theme preference. */ theme?: "light" | "dark"; /** Style configuration for theming. */ styles?: { /** CSS custom properties the view can reference. */ variables?: Record; /** 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 interface HostDelegatingOAuthRequest { reason: McpOAuthRequestReason; wwwAuthenticateParams?: McpOAuthRequestContext["wwwAuthenticateParams"]; resourceMetadata?: string; } declare type HttpHookConfig = z_2.infer; declare const HttpHookConfigSchema: z_2.ZodEffects; url: z_2.ZodEffects; headers: z_2.ZodOptional>; allowedEnvVars: z_2.ZodOptional>; timeoutSec: z_2.ZodOptional; timeout: z_2.ZodOptional; /** * When set, use VS Code / Open Plugins payload format. Value is the original PascalCase event name. * Events without a VS Code payload mapper keep their CLI-native payload, so this tag is inert at runtime. */ _vsCodeCompat: z_2.ZodOptional>; }, "strip", z_2.ZodTypeAny, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>, Omit<{ url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }, "timeout">, { url: string; type: "http"; headers?: Record | undefined; timeout?: number | undefined; timeoutSec?: number | undefined; _vsCodeCompat?: "SessionStart" | "SessionEnd" | "UserPromptSubmit" | "PreToolUse" | "PreMcpToolCall" | "PostToolUse" | "PostToolUseFailure" | "ErrorOccurred" | "Stop" | "SubagentStop" | "SubagentStart" | "PreCompact" | "PermissionRequest" | "Notification" | undefined; allowedEnvVars?: string[] | undefined; }>; /** * 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; /** Numeric metrics */ metrics: Record; /** Experiment assignment context */ exp_assignment_context?: string; /** Feature flags enabled for this session */ features?: Record; /** 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; /** Numeric metrics */ metrics: Record; /** Experiment assignment context */ exp_assignment_context?: string; /** Feature flags enabled for this session */ features?: Record; /** 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; partialResult(result: AgentCallbackPartialResultEvent): Promise; commentReply(reply: AgentCallbackCommentReplyEvent): Promise; checkQuota?(content: AgentCallbackCheckQuotaEvent): Promise; result(result: AgentCallbackResultEvent): Promise; error(error: AgentCallbackErrorEvent): Promise; dispose?(): void; emitNamespacedProgress?(namespace: string, kind: string, content: string): Promise; } /** 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"; } /** * Thin TypeScript boundary over the native IFC session engine * (`src/runtime/src/ifc/session_engine.rs`). The context label, the * per-repository visibility/collaborator caches, the policy decisions, the label * propagation, and the entire resolve-loop all live in Rust behind the `handle`. * * The only logic that remains in TypeScript is the asynchronous MCP tool I/O the * native engine cannot perform itself: when Rust needs a repository's visibility * or collaborator audience it reverse-calls {@link buildFetchHandler}, which * invokes the real `tool.callback` and hands the raw result JSON back via * `ifcEngineFetchComplete`. The processor entry points map the native decision / * label-update result onto the host's structured logger and pre/post-tool outputs. */ declare class IFCEngine implements IPreToolsExecutionProcessor, IPostToolExecutionProcessor { private readonly logger; private readonly requestHookPermission?; private readonly onToolCallAllowed?; private readonly handle; /** * Dedicated token used to unregister the finalizer. A separate object * (rather than `this`) keeps the unregister intent explicit and decoupled * from the registered target. */ private readonly finalizationToken; private listCollaboratorsTool; private searchRepositoriesTool; private settings; constructor(logger: RunnerLogger, initialLabel?: string, requestHookPermission?: ((request: PermissionRequest_2) => Promise) | undefined, onToolCallAllowed?: ((toolCallId: string) => void) | undefined); /** * Sets the MCP tool used to resolve repository sink recipients. * Called after tools are loaded (they are not available at construction time). */ setCollaboratorsTool(tool: Tool_2 | undefined, settings: RuntimeSettings): void; /** * Sets the MCP tool used to check repository visibility. * Called after tools are loaded (they are not available at construction time). */ setSearchRepositoriesTool(tool: Tool_2 | undefined): void; getContextLabel(): string; setContextLabel(label: string): void; toJSON(): string; /** * Releases the native engine handle. Idempotent; the `FinalizationRegistry` * also runs the same release on GC. */ dispose(): void; /** * Builds the per-call reverse-call handler the native resolve-loop invokes to * resolve a repository's visibility or collaborator audience. It performs the * asynchronous MCP `tool.callback`, then reports the tool's text result back * to Rust (which parses it) via `ifcEngineFetchComplete`. A missing tool * reports a `"null"` result (resolved as "no value"); a thrown call is logged * here and reported as a failure. */ private buildFetchHandler; preToolsExecution(context: PreToolsExecutionContext): Promise; private handleAskDecision; postToolExecution(context: PostToolExecutionContext): Promise; } /** * Read-only interface for consuming feature flags. * * Includes the convenience boolean methods and flag accessors that consumers * need. */ export declare interface IFeatureFlagService { /** * Gets the value of a specific feature flag (sync, local-only). * This returns the statically-resolved value without consulting ExP. */ getLegacyFlag(flag: FeatureFlag): boolean; /** * Gets the value of a feature flag, checking ExP via the mapping table * then falling back to the local static value. */ getFlag(flag: FeatureFlag): Promise; /** Gets all feature flags (frozen copy). */ getAllFlags(): FeatureFlags; /** Gets all ExP flags synchronously (may contain pending/stale data). */ getAllExpFlagsSync(): ExpFlags; /** Gets the latest ExP response synchronously. */ getLatestExpResponse(): CopilotExpAssignmentResponse; /** Gets the cached assignment context string for telemetry, if available. */ getLatestAssignmentIfPresent(): string | undefined; /** Gets the CAPI assignment context string for telemetry, if available. */ getSecondaryAssignmentIfPresent(): string | undefined; /** Stores a CAPI assignment context for telemetry. */ captureSecondaryAssignmentContext(assignmentContext: string): void; /** Subscribes to feature flag changes. Returns an unsubscribe function. */ subscribe(listener: FeatureFlagChangeListener): () => void; /** * Applies a partial config override and re-resolves flags through the * normal resolution chain (env, config, flag overrides), then notifies * subscribers. Use for in-session toggles (e.g. `/memory on|off`) so the * change takes effect without a CLI restart. */ applyConfigOverride(partialConfig: Partial): void; /** Returns a promise that resolves once the initial ExP fetch has completed. */ waitForExpResponse(): Promise; /** Gets a feature flag, preferring the ExP assignment and otherwise falling back to the static flag. */ getFlagWithExpOverride(expFlag: ExpFlagKey, featureFlag: FeatureFlag): Promise; /** Gets the value of a specific ExP flag (awaits the ExP response first). */ getExpFlag(flag: ExpFlagKey): Promise; /** Applies CLI-fetched assignments and resolves any pending waiters. */ setExpAssignments(assignments?: CopilotExpAssignmentResponse): void; /** Whether the gpt-5.4-mini default model for explore subagents is enabled. */ isGpt54MiniForExploreEnabled(): Promise; /** * Resolves the arm of the three-arm dynamic instruction retrieval * experiment ("control" | "blackbird" | "text-embedding"), or undefined * when ExP has no arm assignment. */ getDynamicInstructionsRetrievalArm(): Promise; /** Whether the GPT default model experiment is enabled. */ isGptDefaultModelEnabled(): Promise; /** Whether MCP `_meta` (FIDES IFC) surfacing on `ToolResultExpanded.mcpMeta` is enabled. */ isFidesIfcEnabled(): Promise; /** Whether the Copilot Subconscious (cross-session context sharing) experiment is enabled. */ isCopilotSubconsciousEnabled(): Promise; /** Whether preserved reasoning (`reasoning.context: "all_turns"`) is enabled for supported models. */ isPreserveReasoningEnabled(): Promise; /** Whether built-in subagent system messages should be split into static and per-user blocks for cache optimization. */ isSplitSubagentSystemMessageCacheEnabled(): Promise; /** Whether reasoning summaries should be hidden by default (the REASONING_SUMMARIES_OFF_BY_DEFAULT experiment). */ isReasoningSummariesOffByDefaultEnabled(): Promise; /** Whether Gemini models should request validated tool choice (the GEMINI_VALIDATED_TOOL_CHOICE experiment). */ isGeminiValidatedToolChoiceEnabled(): Promise; /** Whether a reasoning-only completed turn should be nudged to continue (the REASONING_ONLY_CONTINUATION experiment). */ isReasoningOnlyContinuationEnabled(): Promise; } declare type ImageAttachmentRequestFormat = "capi_url" | "inline_base64"; 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) | Record; /** * 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; read(options?: ReadInboxEntryOptions): Promise; getUnreadUnnotifiedEntries(): Promise; markNotified(entryId: string): Promise; getById(entryId: string): Promise; /** Returns entries sent by a specific sender for a specific interaction. */ getEntriesBySenderAndInteraction(senderId: string, interactionId: string): Promise; 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"; } /** * A message to be injected into the conversation history after tool execution. * Used by tools like skills that need to add content to the conversation. */ declare type InjectedUserMessage = { /** * The content to inject as a user message. */ content: string; /** * A source identifier for tracking where this message came from. * Used for filtering in the timeline display. * Example: "skill-pdf", "skill-code-reviewer" */ source: string; }; declare class InProcMCPTransport extends MCPTransport { private toolIdToClientInfo; private onReauthRequired?; /** * Callback invoked when a tool call fails with "Not connected" (transport disconnected). * The callback should reconnect the server and return the fresh MCP client. * If undefined, disconnect errors are surfaced without retry. */ private onDisconnectReconnect?; /** * Callback invoked when a tool call receives HTTP 404 (session expired per MCP spec). * Should evict tokens, restart the server, and return the fresh MCP client. */ private onSessionExpiredReconnect?; /** * Callback invoked when a tool call fails with an OAuth 401. The callback should * reconnect the server with fresh auth and return the new native session so the * tool call can be retried. The host owns whether that recovery can be silent * (cached/refresh/`client_credentials`) or must use an interactive OAuth handler. * When undefined, the transport falls back to a single naive retry. When it throws * because interaction is required but unavailable, the transport defers to needs-auth * instead of blocking the tool call on a browser flow (copilot-mcp-core#1761). */ private onReauthAndRetry?; private onOAuthReplacementAndRetry?; /** Maps tool IDs (which may be truncated) to original MCP tool names for invocation. */ private toolIdToOriginalName; /** Maps tool IDs to their MCP task support level. */ private toolIdToTaskSupport; /** Handler for URL elicitation required errors from tool invocations. */ private urlElicitationHandler?; /** Optional task registry for non-blocking MCP task execution. */ private taskRegistry?; constructor(settings: RuntimeSettings, logger: RunnerLogger, cacheProviderTools?: boolean); /** Register a callback invoked when a tool call detects the server needs re-authentication. */ setOnReauthRequired(callback: (serverName: string) => void): void; /** * Register a callback invoked when a tool call fails because the transport disconnected. * The callback should restart the MCP server and return the fresh client instance. */ setOnDisconnectReconnect(callback: (serverName: string) => Promise): void; /** * Register a callback invoked when a tool call receives HTTP 404 (session expired). * The callback should evict tokens, restart the server with fresh auth, and return the new client. */ setOnSessionExpiredReconnect(callback: (serverName: string) => Promise): void; /** * Register a callback invoked when a tool call fails with an OAuth 401. The callback * should reconnect the server with fresh auth and return the new native session so * the call can be retried. */ setOnReauthAndRetry(callback: (serverName: string) => Promise): void; setOnOAuthReplacementAndRetry(callback: (serverName: string, request: HostDelegatingOAuthRequest) => Promise): void; /** * Set the handler for URL elicitation required errors. * This handler is called when a tool invocation returns a UrlElicitationRequiredError (-32042). */ setUrlElicitationHandler(handler: ((serverName: string, elicitation: ElicitRequestURLParams) => Promise) | undefined): void; /** * Set the task registry for non-blocking MCP task execution. * When set, tools with `taskSupport: "required"` will register as background * tasks in the registry and return immediately instead of blocking. */ setTaskRegistry(registry: TaskRegistry | undefined): void; /** * Hook called when a provider (MCP client) is being refreshed. * Clears the tool ID mappings for this client. */ protected onProviderRefresh(clientInfo: ClientInfo_2): Promise; protected doInvokeTool(toolId: string, toolParams: Record, toolCallId?: string, _customAgentName?: string): Promise; private doInvokeToolWithRetry; private requireTaskRegistryForTask; /** * Invoke a tool using the MCP Tasks protocol via `callToolAsTask()`. * * Entry to this method already required `taskSupport === "required"`. If * a `TaskRegistry` is wired in, the task is registered as a background * entry and the method returns immediately with the agent/task ID; the * task is polled asynchronously, updating registry status/progress * until the task completes. If no `TaskRegistry` is available (e.g. the * Actions runtime pipeline doesn't use Session), the method throws — * there is no safe way to surface a long-running task without a registry, * and falling back to a blocking poll could hang the model turn for an * unbounded amount of time. */ private doInvokeToolWithTask; /** * Convert a `NativeMcpCallToolResult` into the shape the TaskRegistry executor * expects (`{ textResultForLlm, resultType }`). Throws on tool errors so * the registry marks the agent as failed with a useful message. * * Mirrors the LLM-visible text logic of the blocking path's * `invokeToolResponseToToolResult` by delegating to * `combineContentAndStructured` — see that helper for the precedence * rules. The combined string is computed before branching on `isError` * so a failure that only carries `structuredContent` (e.g. * `{ code: "RATE_LIMITED" }`) still surfaces that payload rather than * being reduced to the generic fallback string. Text items (and resource * items carrying text) are concatenated to form the `content` text input * to the helper. * * Known gap — binary content is not propagated. The blocking path * separately attaches images / resource blobs to the tool result via * `binaryResultsForLlm`, which the model layer (capi/anthropic) turns * into multimodal content blocks. The background-task path drops them * here because: * 1. The executor return shape is text-only and `task.result` flows * back through `read_agent`, which currently has no multimodal * surface. * 2. Persisting image/blob bytes on `task.result` would bloat session * snapshots and likely needs a side-channel keyed by task id. * 3. The TasksDialog UI renders `task.result` as truncated text and * would need updating to handle image-bearing completed tasks. * Addressing this would mean: (a) extend the executor return to carry * `binaryResultsForLlm`, (b) plumb it through `read_agent` so it ends * up on the surfaced ToolResult, (c) update the UI / persistence story. * Tracked as a follow-up to the experimental MCP_TASKS feature in * https://github.com/github/copilot-agent-runtime/issues/7419. */ private callToolResultToExecutorReturn; /** * Poll `getTask` until the task reaches a terminal state, then call * `getTaskResult` to fetch the final payload. This is the primary mechanism * for tracking MCP tasks with the native session. * * Note: This is a per-process recovery only — when the CLI itself * restarts, the in-memory MCP client and TaskRegistry are gone and * outstanding tasks are orphaned on the server (eventually expiring per * their TTL). The "non-easy" version of this would persist * `{ serverConfig, taskId, agentId }` to session state on `taskCreated`, * re-spawn / re-connect MCP servers on startup, rehydrate subagents via a * new `TaskRegistry.adoptExistingAgent(...)` API, and resume polling. * That matters because long-running MCP tasks are precisely the workloads * users are most likely to leave running across a restart, but it's a * meaningful chunk of work involving session-state schema, transport * reconnection, and a new registry surface — so it's deferred. */ private pollTaskUntilTerminal; protected getProviderCacheKey(provider: ClientInfo_2): string; protected loadToolsFromProvider(clientInfo: ClientInfo_2): Promise>; private static getToolIdFromClientAndToolName; private static getToolNameFromIdAndClientName; } declare type InsertArgs = InsertInput & { command: "insert"; }; declare type InsertInput = { path: string; insert_line: number; new_str: string; }; /** Schema for the `InstalledPlugin` type. */ 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; /** Schema for the `InstalledPluginSourceGitHub` type. */ declare interface InstalledPluginSourceGitHub { path?: string; ref?: string; repo: string; /** Constant value. Always "github". */ source: "github"; } /** Schema for the `InstalledPluginSourceLocal` type. */ declare interface InstalledPluginSourceLocal { path: string; /** Constant value. Always "local". */ source: "local"; } /** Schema for the `InstalledPluginSourceUrl` type. */ declare interface InstalledPluginSourceUrl { path?: string; ref?: string; /** Constant value. Always "url". */ source: "url"; url: string; } /** * Source identifier for the hidden follow-up user message that delivers * on-demand instruction file discoveries (e.g. nested AGENTS.md). Carried on * `ToolResultExpanded.newMessages[].source` so timeline rendering filters it * out (`isUserFacingUserMessageSource` only allows allowlisted prefixes) and so it is * excluded from `originalUserMessages` for compaction purposes. Mirrors the * pattern used by the skill tool (see `SKILL_MESSAGE_SOURCE_PREFIX`). */ declare const INSTRUCTION_DISCOVERY_MESSAGE_SOURCE = "instruction-discovery"; /** Schema for the `InstructionDiscoveryPath` type. */ 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[]; } /** Schema for the `InstructionSource` type. */ 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; /** 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"; /** * Implements tools that expose interactive shell terminals to Copilot agent. * This tool supports multiple shell sessions, including long-running and interactive * (apps using NCurses or requiring a TTY) to work. */ declare class InteractiveShellToolContext { private readonly config; private readonly inTests; private readonly options; private readonly sessions; /** * Whether each tracked session was actually spawned inside the sandbox. * Used to (1) reject shellId reuse across mismatched sandbox states and * (2) report the applied sandbox state in subsequent tool results. */ private readonly sessionSandboxApplied; private readonly sessionMetadata; private readonly currentExecutions; private readonly retainedAttachedShellTasks; private readonly promotableSyncShells; private readonly syncShellPromotionResolvers; private readonly shutdownSessionsInfos; /** Bounded map tracking recently-shutdown sessions for error classification. */ private readonly recentShutdowns; private readonly shellConfig; private readonly shellDisplayName; private readonly executionQueues; private onCommandComplete?; private readonly backgroundTaskNotificationsEnabled; private readonly taskRegistry; private readonly ownerId; private readonly contextGeneration; private currentLocation; readonly sessionFactory: IShellExecutionSessionFactory; constructor(config: ToolConfig, inTests?: boolean, sessionFactory?: IShellExecutionSessionFactory, options?: { readonly supportsPowerShell7Syntax?: boolean; readonly asyncOnlyShell?: boolean; }); private restoreDetachedExecutions; private getShellDescriptorOptions; /** * Creates the default session factory (spawn backend). getShellTools() in * config.ts normally constructs and passes an equivalent factory; this default * keeps direct constructions (e.g. tests) working without one. */ private createDefaultSessionFactory; /** * Updates the working directory used for new shell sessions. * Existing shell sessions retain their own cwd. */ updateLocation(newLocation: string): void; /** * Sets the callback to be invoked when a background shell command completes. * @param callback - The callback to invoke, or undefined to remove the callback */ setOnCommandCompleteCallback(callback: ShellCommandCompletionCallback | undefined): void; getShellTool(overrides?: { notifyOnComplete?: boolean; }): Tool_2; getReadShellTool(overrides?: { notifyOnComplete?: boolean; }): Tool_2; getStopShellTool(): Tool_2; getListShellsTool(overrides?: { notifyOnComplete?: boolean; }): Tool_2; private getReplacementContext; private isCurrentContext; private shellContextReconfiguringResult; private defaultTimeoutInMs; /** * Helper method to execute the shell tool callback with permission checks. * This is called either directly or through the execution queue. */ private executeShellToolCallback; private shellTool; private readShellTool; private stopShellTool; private listShellsTool; private getShellSessionInfos; private shutdown; getSession(shellId: string): IShellExecution | undefined; /** * Shuts down all shell sessions and cleans up resources. * This is intended to be called when the owning Session is being disposed. */ shutdownAll(): Promise; /** * Shuts down all attached shells immediately, even if they have a command * in progress. Detached shells are left alone — they were started to * outlive the agent under their original policy. * * Used when settings baked into the shell process at spawn time (e.g. sandbox * policy) change mid-session and existing shells must be torn down so the * next command spawns fresh. */ killAllAttachedShells(): void; /** * Shuts down attached shells that still have a command in progress. * * Called on user-initiated turn cancellation (esc) to reap shell commands * that slipped into the background — sync commands promoted on timeout, or * async commands started without detach — whose turn-scoped abort listener * was already removed when they were promoted. Detached shells * (servers/daemons) and idle reusable shells are intentionally left alone: * the former are meant to outlive the agent, the latter carry reusable * state (cwd, env, activated venvs) across turns. */ killRunningAttachedShells(): void; /** * Shuts down all attached shell sessions that don't have a command in progress * or unread output. * Intended to be called when the agent goes idle with no background tasks, * reclaiming child processes (pwsh/bash) and in-process resources (output buffers). * * This is intentionally synchronous — `shutdownSession` performs synchronous * process kills and map cleanup with no async I/O. */ shutdownIdleSessions(): number; /** * Waits for all running async shell commands to complete. * Returns when all commands have finished. */ waitForActiveShells(): Promise; /** * Returns true if any shell session has a command in progress. */ hasRunningCommands(): boolean; refreshShellTasks(): Promise; /** * Returns true if any attached shell session has a command currently in * progress. * * Unlike `hasCommandsAwaitingNotification()`, this is independent of the * notification opt-in: every running attached command counts. Detached * sessions are skipped because they're designed to outlive the session * (servers, daemons) and must not gate session-idle decisions. */ hasRunningAttachedCommands(): boolean; /** * Returns true if any attached shell has a command in progress that will * trigger a completion notification when it finishes. */ hasCommandsAwaitingNotification(): boolean; /** * Returns true if the specified sync shell wait can currently be released * into background execution. */ canPromoteShellToBackground(shellId: string): boolean; /** * Returns the currently-promotable sync shell wait, if any. */ getCurrentPromotableShell(): { shellId: string; description?: string; } | undefined; /** * Releases the current sync shell wait so the command keeps running in the * background and can be managed via read/write/stop. */ promoteShellToBackground(shellId: string): boolean; getTrackedShellTasks(): Array<{ type: "shell"; id: string; description: string; status: TaskStatus_2; startedAt: number; completedAt?: number; command: string; logPath?: string; pid?: number; exitCode?: number; attachmentMode: "attached" | "detached"; executionMode: "sync" | "background"; canPromoteToBackground?: boolean; }>; getShellTaskProgress(shellId: string): Promise<{ recentOutput: string; pid?: number; } | undefined>; cancelShellTask(shellId: string): Promise; removeShellTask(shellId: string): boolean; /** * Returns the TaskRegistry used for tracking detached shell sessions. * Primarily useful for tests and for retrieving detached shell state. */ getTaskRegistry(): TaskRegistry; private consumeDetachedShellCompletionNotification; private isAttachedShell; /** * Whether an existing session was spawned inside the sandbox. Defaults to * the host-level sandbox state when the session predates the per-session * tracking map (e.g. created before this code path landed). */ private getSessionSandboxApplied; /** * The shell config whose sandbox state reflects how a given run actually * executed. When a command bypassed the sandbox via the opt-out, the session was * created with the sandbox disabled, so sandbox-denial detection/footers * must be computed against the disabled config — otherwise a generic * non-zero exit of an already-bypassed command gets misattributed to the * sandbox and the model is told to retry with an opt-out it already used. */ private effectiveShellConfig; /** * The sandbox config in effect for this session *right now*, read live so a * mid-turn change (e.g. the user disabling the sandbox from a bypass prompt) * is honored by the in-flight tool. Falls back to the construction-time * `shellConfig.sandbox` snapshot when the host doesn't supply a live getter * (e.g. direct tool construction in tests) or it returns `undefined`. */ private liveSandbox; /** * Detects an attempt to reuse a `shellId` whose session was created in a * different sandbox state than this invocation requests. Reusing such a * session would run the command under the wrong sandbox boundary, so the * caller must reject it. Returns the user-facing rejection reason, or * `undefined` when there is no mismatch (no reused session, or the session's * sandbox boundary already matches what this command needs). * * This is evaluated before the permission prompt so a doomed sandbox-bypass * reuse does not consume a user elevation approval only to be rejected by * the same guard afterward. */ private sandboxStateMismatchReason; private detachedSandboxReason; private isSandboxOptOutAllowed; private wantsSandboxBypass; private shouldRetainAttachedShellTask; private retainAttachedShellTask; /** * Returns info about attached running shell commands that are awaiting notification. */ getRunningCommandsInfo(): Array<{ shellId: string; description?: string; }>; /** * Build a non-destructive sessions list for inclusion in error messages. */ private getActiveSessionsList; private markPromotableSyncShell; private clearPromotableSyncShell; private getOrCreateSession; private shutdownSession; private disposeSession; /** * Record a shutdown in the bounded tracking map. * Evicts the oldest entry only when inserting a new key would grow the map * beyond MAX_SHUTDOWN_TRACKING_ENTRIES. Updates to existing keys never * trigger eviction. */ private trackShutdown; /** * Compute the telemetry baseline for a `read_*` call against a given shellId. * * Returns the `read_target_state` and `read_target_original_mode` properties * to emit on this read, regardless of whether the read ultimately succeeds or * fails. Captures the operational state of the read target at the moment the * read is processed: alive session → `active`; recorded shutdown → mapped from * `ShutdownInfo.reason`; no record → `never_existed` / `unknown`. * * Callers should compute this once at the top of `readShellTool` and merge the * returned properties into the `toolTelemetry` of every exit path so we can * measure how often the model polls each state and compare outcomes. */ private getReadTargetTelemetry; /** * Classifies why a shell ID is not available and builds a categorized error result. * Checks active sessions, recently-shutdown sessions, and returns appropriate * error category, LLM message, and telemetry. */ private classifyShellError; /** * Get or create an execution queue for the given shell ID. * This ensures that all shell operations for the same session are executed sequentially. */ private getOrCreateExecutionQueue; } export declare namespace internal { export { AppInsightsTelemetryService, NoopTelemetryService, SessionTelemetry, missingRemoteBranchWarning, loadPersistedSessionCwd, HandoffStep, HandoffProgress, PruneResult, ForkSessionOptions, ForkSessionResult, LocalSessionManagerOptions, PersistedSessionCwdInfo, ResumeBehavior, LocalSessionManager } } /** * Information about a skill that was invoked during the session. * Used to preserve skill context across compaction. */ declare interface InvokedSkillInfo { /** The skill name */ name: string; /** Path to the SKILL.md file */ path: string; /** The full content of the skill file (YAML frontmatter stripped) */ content: string; /** * Tools that should be auto-approved when this skill is active. * Stored separately from `content` because the frontmatter is stripped before injection, * so the allowed-tools list cannot be recovered by re-parsing `content` on session resume. */ allowedTools?: readonly string[]; /** Turn number when the skill was invoked */ invokedAtTurn: number; } declare type InvokeToolResponseData = { isToolError: boolean; content: CallToolResult["content"]; structuredContent?: unknown; /** When true, secret masking would have applied but was skipped. */ secretMaskingSkipped?: boolean; /** When true, server config explicitly disabled secret masking. */ secretMaskingDisabledForServer?: boolean; /** * Resolved MCP App UI resource (SEP-1865), populated when the invoked * tool declared `_meta.ui.resourceUri` and the auto-fetch succeeded. */ uiResource?: McpUiResource; /** * MCP `CallToolResult._meta`, carried verbatim. On the OOP HTTP path this comes from * `response.json()` and is therefore unvalidated — always pass through `normalizeMcpMeta` * before treating it as an object. Surfaced as `mcpMeta` only when `FIDES_IFC` is on. */ _meta?: unknown; }; 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; /** * Called when a request to the model fails. The processor should not modify * the error. */ onRequestError(context: OnRequestErrorContext): Promise; } declare interface IOnStreamingChunkProcessor extends IToJson { /** * Called when a streaming chunk is received. */ onStreamingChunk(context: StreamingChunkContext): void; } declare interface IPostEditHook { readonly id: string; /** * Post-edit hooks are ran after any edit is made by the agent, once per turn. Note: if the agent decides to edit * using bash execution, like `echo 'content' > file.txt`, the hook will not run. */ postEdit(context: PostEditHookContext): Promise; } 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; } declare interface IPostResultHook { readonly id: string; /** * Post-result hooks are ran after the agent has finished its work for the current problem. */ postResult(context: PostResultHookContext): Promise; } 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; } declare interface IPreCommitHook { readonly id: string; /** * - Ran before commits are made by the agent, once per turn. Note: if the agent decides to commit using * bash execution of `git commit`, the hook will not run. * - May prevent the commit from happening via the returned {@link PreCommitHookResult} */ preCommit(context: PreCommitHookContext): Promise; } declare interface IPreEditsHook { readonly id: string; /** * - Ran before any edits are made by the agent, once per turn. Note: if the agent decides to edit * using bash execution, like `echo 'content' > file.txt`, the hook will not run. */ preEdits(context: PreEditsHookContext): Promise; } declare interface IPrePRDescriptionHook { readonly id: string; /** * Allows hooks to modify the staged PR description before it is returned. */ prePRDescription(context: PrePRDescriptionHookContext): Promise; } 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; } declare interface IPreToolsExecutionProcessor extends IToJson { /** * Called before any tool calls are executed. */ preToolsExecution(context: PreToolsExecutionContext): Promise; } /** * The complete settings type that represents all possible configuration options. */ declare interface IRuntimeSettings { version: string; clientName: string; github: { serverUrl: string; uploadsUrl: string; secretScanningUrl: string; host: string; hostProtocol: string; token: string; user: { name: string; email: string; actorId?: number; actorLogin?: string; }; owner: { id: number; name: string; }; repo: { id: number; name: string; branch: string; commit: string; readWrite: boolean; signCommits: boolean; }; pr: { commitCount?: number; }; }; problem: { statement: string; contentFilterMode?: ContentFilterMode; action: AgentAction; customAgentName?: string; }; service: { instance: { id: string; }; /** * - Options beyond `model` are currently only respected * when going through `RuntimeHarness` methods. * - The value of this {@link ClientOptions.model} is NOT * the name of a model, it is AgentName:ModelName. */ agent: ClientOptions; /** * Settings for tools that are used by the agent. Refer to the * source/documentation for each tool for their specific settings. */ tools: { [toolName: string]: { [key: string]: unknown; }; }; callback: { url: string; }; }; api: { aipSweAgent: { token: string; }; anthropic: { key: string; bearerToken: string; baseUrl: string; }; openai: { baseUrl: string; apiKey: string; azureKeyVaultUri: string; azureSecretName: string; azure: { url: string; /** When set, uses the versioned deployment route. When omitted, uses the GA versionless v1 route. */ apiVersion?: string; /** Bearer token for Azure AD authentication. When set, used instead of API key or managed identity. */ bearerToken?: string; }; }; copilot: { url: string; integrationId: string; hmacKey: string; azureKeyVaultUri: string; token: string; useSessions: boolean; sessionId: string; previousSessionIds: string[]; /** * The W3C Trace Context traceparent header value for distributed tracing. * Format: {version}-{trace-id}-{parent-id}-{trace-flags} * Example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01 */ traceParent: string; /** CAPI session token — JWT for auto-mode session-based billing discount, sent as Copilot-Session-Token header. */ capiSessionToken: string; /** * True when the parent session resolved the virtual "auto" model via `POST /models/session`. * Sub-agents check this to inherit the session model instead of selecting their own, * ensuring the Copilot-Session-Token billing header is forwarded and rate-limit quotas * are shared. Distinct from `capiSessionToken` presence, which can also be set from * Actions job details outside of CLI auto mode. */ autoMode: boolean; }; github: { /** * The GITHUB_PERSONAL_ACCESS_TOKEN that is passed to `github-mcp-server` when it is * started. (Currently only supported in the `cpd` entry point.) */ mcpServerToken: string; }; }; blackbird: { mode: "initial-search" | "tool"; backfillScoreThreshold?: number; repoNwo?: string; /** * The auth object contains the credentials for Blackbird's Metis API. * - modelBasedRetrievalToken: Token for model-based retrieval. * - metisApiKey: API key for Metis. */ auth: { modelBasedRetrievalToken: string; metisApiKey: string; }; }; swebench_base_commit?: string; trajectory: { outputFile: string; }; logs: { eventsLogDir: string; }; job: { nonce?: string; eventType?: string; isTriggerJob?: boolean; /** * CCAv3-only runtime signal for built-in MCP tool availability after * trigger policy resolution. Prompt builders use this to avoid * advertising built-in tools that are not callable for the session. */ builtInToolAvailability?: { reportProgress?: boolean; createPullRequest?: boolean; }; }; onlineEvaluation: { disableOnlineEvaluation?: boolean; enableOnlineEvaluationOutputFile?: boolean; }; /** * Test-only: Pre-formatted memories to inject into the agent's context. * Used by eval tests to seed memories without file I/O or cloud API calls. * When set, getMemoriesPrompt() returns this value directly. */ testInjectedMemories?: string; /** * Test-only: Pre-formatted repo/user memories to inject as separate sections * in the combined memories prompt used by user-scoped memory evals. */ testInjectedScopedMemories?: TestInjectedScopedMemories; /** * Test-only: When true, enables the vote_memory tool in local memory strategy evals. * Used by eval tests to verify voting behavior without requiring cloud API. */ testVoteToolEnabled?: boolean; /** * Test-only: When true and testInjectedMemories is set, a synthetic voteToolDefinition * is included so getMemoryTools() registers the vote_memory tool. Combined with * testInjectedMemories (which bypasses both the /enabled and /prompt Memory API calls), * this allows eval tests to exercise vote_memory with no real Memory API dependency. */ testEnableVoteTool?: boolean; tools: { bash: { /** * The default timeout for bash commands in seconds. If undefined, a default of 120 seconds (2 minutes) is used. */ defaultTimeout?: number; }; /** * Settings shared by all validation tools. */ validation?: { /** * The shared timeout budget for all the validation tools in seconds. If undefined, a default of 180 seconds is used. * This timeout is shared across all validation tools, and once the total time spent exceeds this budget, no further validation tools will be run. * A validation tool will be cancelled if it is in progress when the budget is exceeded. */ timeout?: number; /** * The timeout for the dependabot checker in seconds. Default is 240 seconds. */ dependabotTimeout?: number; /** * Settings for the CodeQL security checker tool. * When enabled is false, the tool will not run even if feature flags are enabled. * When enabled is true or undefined, the tool's availability will be determined by its feature flags. */ codeql?: { enabled?: boolean; }; /** * Settings for the code review (Autofind) tool. * When enabled is false, the tool will not run even if feature flags are enabled. * When enabled is true or undefined, the tool's availability will be determined by its feature flags. */ codeReview?: { enabled?: boolean; /** * Override the model passed to the autofind CLI's `--model` flag. * When undefined, the runtime uses its built-in default model. * * Useful when the default model is not available in a given * environment (e.g. 1P-only models in a 3P session) or when * experimenting with alternative models. */ model?: string; }; /** * Settings for the dependency/advisory checker tool and the corresponding post-commit hook. * When enabled is false, the tool will not run even if feature flags are enabled. * When enabled is true or undefined, the tool's availability will be determined by its feature flags. * The validation settings for the dependency/advisory checker tool control the availability of * DependaBot in the agent's toolbox and with respect its use post-commit. */ advisory?: { enabled?: boolean; }; /** * Settings for the secret scanning hook. * When enabled is false, the hook will not run even if feature flags are enabled. * When enabled is true or undefined, the hook's availability will be determined by its feature flags. * Note: the secret scanning hook is a pre-commit and pre-PR description hook that scans for secrets * before code is committed, and before PR descriptions are created/changed. */ secretScanning?: { enabled?: boolean; }; }; /** * CCAv3-only settings for runtime-tools memory tool exposure. * When storeEnabled or voteEnabled is false, the matching memory tool will not be exposed via MCP. * When enabled is true or undefined, the tool's availability is determined by the Memory API /prompt response. */ memory?: { storeEnabled?: boolean; voteEnabled?: boolean; }; /** * Settings for handling large tool outputs. */ largeOutput?: { /** * Whether large output handling is enabled. When false, large tool * outputs are returned inline instead of being redirected to temp * files. 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; }; }; /** * Settings for built-in agents. `rubberDuckAutoInvoke` is projected here from * its /subagents home (subagents.agents['rubber-duck'].autoInvoke) so the * prompt/task-tool layers can read it from RuntimeSettings. */ builtInAgents?: { rubberDuckAutoInvoke?: boolean; }; /** * The set of feature flags passed to the agent runtime process by sweagentd. * * Only flags listed in internal/launcher/runtime_feature_flags.go are passed * to the runtime. * * To add a new flag: * - Define it in accordance with the feature flag docs: https://thehub.github.com/epd/engineering/products-and-services/dotcom/features/feature-flags/ * - Add it to runtime_feature_flags.go * - Check whether it exists in the following object. * * Read a feature flag value with: @see isFeatureFlagEnabled * * if (isFeatureFlagEnabled(settings, 'copilot_swe_agent_flag_name')) { * } * * Report feature flag values in telemetry with: @see featureFlagsAsString in * a property named @see FEATURE_FLAGS_TELEMETRY_PROPERTY_NAME. * * NOTE: feature flag names may be visible to the user in logs or other output. */ featureFlags: { [key: string]: boolean; }; /** * EXP experiment configuration */ experiments: { [key: string]: string; }; /** * How many ms the runtime/the thing hosting the runtime has available to run * before it is considered to have timed out. */ timeoutMs: number; /** * The time when the runtime/the thing hosting the runtime started, in ms since epoch. * May not be 100% accurate. Not typically set by hand. */ startTimeMs: number; /** * Custom configuration directory for the session. * When set, overrides the default Copilot config directory (~/.copilot or $COPILOT_HOME). */ configDir: string; /** * LSP-specific settings. */ lsp?: { clientName: string; }; } /** * Single source of truth for whether the Agents-tab feature is enabled. * * Gates every Agents-tab surface (UI tab membership, registry watcher, managed-server * spawn, LocalRpcSession-based attach, the `--managed-server` CLI flag, and the * `agentRegistry.spawn` shared-API RPC). Tier `"team"`: on by default for team * repos, opt in elsewhere via `COPILOT_CLI_ENABLED_FEATURE_FLAGS=COPILOT_AGENTS_TAB` * or `defaultFeatureFlags` override. * * Use this helper instead of reading `featureFlags.COPILOT_AGENTS_TAB` directly so callers * have a single, greppable site to update if the gating widens or splits in the future. * * Accepts `undefined` so server-mode and tooling paths that propagate optional * featureFlags can call the helper without an explicit guard. Treating * `undefined` as "off" matches the rest of the feature-flag plumbing where a * missing flags object means "use defaults", and gating off in that case is the * safe choice for Agents-tab surfaces that depend on a resolved flag set. */ 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 settings indicate the parent session is using auto mode. * Requires both the explicit `autoMode` flag (set by the CLI session builder when auto mode * resolves) and a `capiSessionToken` (the JWT needed for billing header forwarding). * Checking both distinguishes CLI auto mode from Actions job details (which set the token * without the flag) and guards against a stale flag without a valid token. */ export declare function isAutoModeSession(settings: RuntimeSettings): boolean; declare function isAutopilotContinuationMessage(prompt: string): boolean; /** * Whether the code_review tool should dispatch to the TypeScript Autofind * engine rather than the legacy Go binary. See {@link CCA_USE_TS_AUTOFIND_FF_NAME}. */ declare function isCcaUseTsAutofindEnabled(settings: RuntimeSettings): boolean; /** * Checks whether the code review feature should be considered enabled. * Requires the enable flag while ensuring the disable flag is not set. * Also respects repo-level validation settings which take precedence. */ declare const isCodeReviewFeatureEnabled: (settings: RuntimeSettings) => boolean; /** * Returns true when a model is a custom (BYOK) model. Delegates to the Rust * runtime. */ export declare function isCustomModel(model: Model): 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; /** * Backend-neutral interface for observing and controlling a shell execution. */ declare interface IShellExecution { readonly attachmentMode: ShellAttachmentMode; readonly lifecyclePolicy: ReturnType; /** Whether a command is currently executing. */ readonly hasCommandInProgress: boolean; /** The PID of the command process, if available. */ getPid(): number | undefined; /** Refreshes cached state from the execution backend. */ refresh(): Promise; /** Reads output from the current or last command. */ readOutput(options?: ShellReadOptions): Promise; /** Waits for completion or the requested timeout. */ waitForOutput(timeoutMs: number, abortSignal?: AbortSignal): Promise; /** Explicitly stops the underlying process tree. */ stop(): Promise; /** Releases resources owned by this CLI process. */ dispose(): void; /** Signals that the caller consumed final output. */ acknowledgeFinalOutput(): void; /** Returns a point-in-time snapshot of cached execution state. */ getSnapshot(): ShellExecutionSessionSnapshot; } /** * Backend-neutral interface for reusable shell command launch sessions. * * This interface abstracts the execution backend so that * `InteractiveShellToolContext` can manage shell tool lifecycle without coupling * to a specific process management strategy. */ declare interface IShellExecutionSession extends IShellExecution { /** Sets a callback invoked when partial output changes during execution. */ setPartialOutputChangedCallback(callback: ShellPartialOutputChangedCallback | undefined): void; /** * Sets a callback invoked when a command completes. * The callback receives the final output and the process PID. * The caller is responsible for associating the shellId externally. */ setCommandCompleteCallback(callback: ((output: ShellOutput, pid?: number) => void) | undefined): void; /** * Executes a command synchronously with an optional timeout. * Returns undefined if a command is already in progress. */ executeCommand(command: string, timeoutMs?: number, abortSignal?: AbortSignal, releaseOnPromotion?: Promise, onCommandStarted?: () => void): Promise; /** * Starts a command asynchronously without waiting for completion. * Returns false if a command is already in progress. */ tryExecuteAsyncCommand(command: string, abortSignal?: AbortSignal): Promise; /** * Starts a detached command that survives session shutdown. * Output is redirected to the specified log file. * * Note: This is a temporary compatibility method. A future refactor will * move detached execution to a separate ShellDetachedExecutionLauncher. */ tryExecuteDetachedCommand(command: string, logPath: string, abortSignal?: AbortSignal): Promise; } /** Factory for creating shell execution sessions. */ declare interface IShellExecutionSessionFactory { create(options: ShellExecutionSessionCreateOptions): Promise; } /** * Type guard that narrows a hook output containing optional decision/reason * fields to a validated {@link HookBlock} with a guaranteed reason string. */ export declare function isHookBlock(output: { decision?: HookBlockDecision; reason?: string; } | void | undefined): output is HookBlock; /** * Whether large-output handling (temp-file redirection) is active for the given * options. Handling is on by default and only disabled when `enabled` is * explicitly `false`. */ declare function isLargeOutputEnabled(options?: Pick): boolean; export declare function isNativeDeclarativeHook(hook: Hook): hook is NativeDeclarativeHook; declare function isStrReplaceEditorCall(toolCall: CopilotChatCompletionMessageToolCall): toolCall is ChatCompletionMessageFunctionToolCall & { function: { name: "str_replace_editor" | StrReplaceEditorArgs["command"]; }; }; /** * Checks whether a hook output represents a terminal decision that should * lock further non-policy hooks from executing. Covers block decisions * (userPromptSubmitted, postToolUse, agentStop, subagentStop), deny * decisions (preToolUse), and behavior deny (permissionRequest). * * @internal Not intended for use by SDK consumers. */ export declare function isTerminalDecision(output: unknown): boolean; 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 function isWriteToFileStrReplaceEditorCommand(command: StrReplaceEditorArgs["command"]): 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 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 { jsonrpc: "2.0"; method: string; params?: TParams; } declare interface JSONRPCParams { _meta?: RequestMeta; [key: string]: unknown; } declare interface JSONRPCRequest { jsonrpc: "2.0"; id: RequestId; method: string; params?: TParams; } declare type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; declare interface JSONRPCResultResponse = Record> { jsonrpc: "2.0"; id: RequestId; result: TResult; } declare type KnownReasoningEffort = (typeof REASONING_EFFORT_LEVELS)[number]; /** * Sentinel "never spill" byte threshold used to disable large-output handling * on code paths that decide whether to spill purely from a numeric threshold * (e.g. the native ripgrep engine). Kept within `Number.MAX_SAFE_INTEGER` so it * round-trips safely across the `f64` napi boundary and no realistic tool output * can exceed it. */ declare const LARGE_OUTPUT_DISABLED_THRESHOLD_BYTES: number; declare type LargeOutputOptions = { /** Maximum output size in bytes before output is written to a temp file. */ maxOutputSizeBytes: number; /** Optional session filesystem for writing large output temp files. */ sessionFs?: SessionFs; /** * Optional directory to write large output temp files to. * Defaults to the session filesystem's `tmpdir` when unset. */ outputDir?: string; /** * Whether large output handling is enabled. When `false`, large outputs are * returned inline instead of being redirected to temp files. Defaults to * enabled (`true`) when unset. */ enabled?: boolean; /** Configured grep tool name to suggest when inspecting saved output. */ grepToolName?: string; /** Human-readable content kind for the generated large-output message. */ 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 = "This is an internal autopilot control message, not an end-user request. Do not acknowledge it in visible assistant text.\n\nYou have not yet marked the task as complete using the task_complete tool. If you were planning, stop planning and start implementing. You aren't done until you have fully completed the task.\n\nIMPORTANT: Do NOT call task_complete if:\n- You have open questions or ambiguities - make good decisions and keep working\n- You encountered an error - try to resolve it or find an alternative approach\n- There are remaining steps - complete them first\n\nIf the latest visible end-user request was conversational-only and you already answered it, your entire next response must be exactly one task_complete tool call with a short summary. Do not send assistant text before or after the tool call. Do not inspect the workspace, query session state, query todos, read files, search, run commands, run tests, validate, or continue implementation work.\n\nKeep working autonomously until the task is truly finished, then call task_complete."; /** 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; } /** * The sandbox in effect for a tool invocation right now: the live session * sandbox when the host wired {@link ToolConfig.getLiveSandboxConfig} (so a * mid-turn change applies immediately), falling back to the construction-time * {@link ToolConfig.shellConfig} snapshot and then to {@link SANDBOX_DISABLED}. */ declare function liveSandboxFromConfig(config: ToolConfig): SandboxConfig_2; /** HTTP headers as a map from lowercased header name to a list of values. Multi-valued headers (e.g. Set-Cookie) preserve all values. */ declare type LlmInferenceHeaders = Record; /** Set to terminate the response with a transport-level failure. Implies end-of-stream; any further chunks for this requestId are ignored. */ declare interface LlmInferenceHttpResponseChunkError { /** Optional machine-readable error code. */ code?: string; /** Human-readable failure description. */ message: string; } /** A response body chunk or terminal error. */ declare interface LlmInferenceHttpResponseChunkRequest { /** When true, `data` is base64-encoded bytes. When absent or false, `data` is UTF-8 text. */ binary?: boolean; /** Body byte range. UTF-8 text when `binary` is absent or false; base64-encoded bytes when `binary` is true. May be empty (e.g. when the response body is empty: send a single chunk with empty data and end=true). */ data: string; /** When true, this is the final body chunk for the response. The runtime treats the response body as complete after receiving an end-marked chunk. */ end?: boolean; /** Set to terminate the response with a transport-level failure. Implies end-of-stream; any further chunks for this requestId are ignored. */ error?: LlmInferenceHttpResponseChunkError; /** Matches the requestId from the originating httpRequestStart frame. */ requestId: string; } /** Whether the chunk was accepted. */ declare interface LlmInferenceHttpResponseChunkResult { /** True when the chunk was matched to a pending request; false when unknown. */ accepted: boolean; } /** Response head. */ declare interface LlmInferenceHttpResponseStartRequest { headers: LlmInferenceHeaders; /** Matches the requestId from the originating httpRequestStart frame. */ requestId: string; /** HTTP status code. */ status: number; /** Optional HTTP status reason phrase. */ statusText?: string; } /** Whether the start frame was accepted. */ declare interface LlmInferenceHttpResponseStartResult { /** True when the response start was matched to a pending request; false when unknown. */ accepted: boolean; } /** Indicates whether the calling client was registered as the LLM inference provider. */ declare interface LlmInferenceSetProviderResult { /** Whether the provider was set successfully */ success: boolean; } declare const llmToolRejectionMessage = "The tool call required approval from the user, but the user rejected it or an earlier tool call."; /** * Loads feature flags from the given config object. * This applies config-based overrides on top of already-resolved feature flags. * * @param config The configuration object to load feature flags from. * @param featureFlags The already-resolved feature flags to apply overrides to. * * @returns An object containing the updated feature flags. */ export declare function loadFeatureFlagsFromConfig(config: DefaultConfig, featureFlags: FeatureFlags): FeatureFlags; /** * Loads feature flags from the environment variable COPILOT_CLI_ENABLED_FEATURE_FLAGS. * The variable should contain a comma-separated list of feature flag names. * Unknown feature flags are ignored. * * Loads feature flags from the environment based on their exact names, e.g. * if there were a feature flag named "EXPERIMENTAL_MODE", setting the environment * variable EXPERIMENTAL_MODE=true would enable that flag. * * @param featureFlags The feature flags to match against for updating. * * @returns An object containing the feature flags. */ 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: RuntimeSettings | undefined): Promise; /** * 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"]; /** * Lightweight IFeatureFlagService implementation that resolves static flags * without ExP infrastructure. Suitable for the Actions runtime, SDK, and tests. */ export declare class LocalFeatureFlagService extends FeatureFlagService { constructor(options?: Partial); } /** * Result of a capped local session store query. */ declare interface LocalQueryResult { rows: Record[]; truncated: boolean; } /** * Session class with event sourcing */ declare class LocalSession extends Session { readonly isRemote: false; private nativeCallbackRuntime?; private readonly callbackRuntimeDelegate; private isProcessing; 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 _cachedTools; private cachedToolConfig?; private cachedSettings?; private lastDeferredToolHintMessage; protected getToolConfig(): ToolConfig | undefined; private getMcpServerDisplayNames; private queueDeferredToolHintIfNeeded; private _cachedClient; private premiumRequestProcessor; private immediatePromptProcessor; private responseLimitsPreRequestProcessor; private initializedSessionLimitsTelemetry; private hasEmittedSessionLimitsTerminalError; private hasEmittedSessionLimitsTerminalWarning; private compactionProcessor; private screenshotProcessor; readonly sidekickAgentManager: SidekickAgentManager; protected onUsageMetricsUpdated(event: SessionEvent): void; protected getResponseLimitsPreRequestProcessorForSubagent(): ResponseLimitsPreRequestProcessor | undefined; setInheritedResponseLimitsPreRequestProcessor(processor: ResponseLimitsPreRequestProcessor): void; /** * 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?; /** * The `CopilotOpenAIClient` whose native CAPI handle backs the * text-embedding retrieval provider. Held so the JS object outlives the * retrieval handle: GC-finalizing it disposes the underlying native handle, * which Rust still uses to issue `/embeddings`. Undefined for the blackbird * provider (which issues its own HTTP in Rust from the bare token). */ private embeddingCapiClient?; /** 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 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; 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; /** * 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, behavior?: UpdateOptionsBehavior): void; private emitSessionLimitsTerminalError; private emitSessionLimitsTerminalWarning; 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:` / `skill:`) 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; /** * 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; /** * 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; /** * 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; /** * Check if a plan.md file exists in the workspace. */ hasPlan(): Promise; 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; /** * Get plan.md content for post-compaction message. * Returns null if workspace is not enabled or plan doesn't exist. */ private getPlanContentForCompaction; private getAutopilotObjectiveContentForCompaction; /** * Write plan content to the workspace plan.md file. */ writePlan(content: string): Promise; /** * Delete the workspace plan.md file. */ deletePlan(): Promise; getAutopilotObjectivePath(): string | null; readAutopilotObjective(): Promise; writeAutopilotObjective(content: string): Promise<"create" | "update">; deleteAutopilotObjective(): Promise; autopilotObjectiveExists(): Promise; /** * List files in the workspace files directory. */ listWorkspaceFiles(): Promise; /** * Read a file from the workspace files directory. */ readWorkspaceFile(filePath: string): Promise; /** * Write a file to the workspace files directory. */ writeWorkspaceFile(filePath: string, content: string): Promise; /** * 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; /** * Get the plan reminder message to inject into user prompts. * Returns null if no reminder should be shown. */ getPlanReminderMessage(): Promise; /** * 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; /** * 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; /** * 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; /** * 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; /** * 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, options?: { passive?: PassivePolicy; }): void; private consumePendingSystemNotifications; private queuePostToolUseFailureContext; private runPostToolUseFailureHooks; private processToolExecutionResult; /** * Fire notification hooks for a given notification event. * Non-blocking — errors are caught and logged by executeHooks. * 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; /** * 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; /** * 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; /** * Process the item queue, handling both messages and commands in FIFO order. */ private processQueue; abort(params?: { reason?: AbortReason; }): Promise; /** * 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; /** * Shared abort + cleanup logic for abort() and suspend(). * * Running subagents are hard-cancelled here, not checkpointed. Idle * multi-turn agents survive an ordinary abort, while suspend cancels them * because their parked executor loops cannot cross the session boundary. * 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_3, modelCapabilitiesOverrides?: ModelCapabilitiesOverride, reasoningSummary?: ReasoningSummary, contextTier?: ContextTier_3): Promise; /** * 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; /** * Stricter sibling of `hasActiveBackgroundWork()` that only counts * background work whose completion fires a notification turn capable of * waking the queue: * - A multi-turn agent in the main task registry with status `"running"`. * - An attached shell session with a command in progress AND * `notifyOnComplete: true` (the opt-in that sends a synthetic * completion notification when the command finishes). * * Excludes attached shells without `notifyOnComplete`: those return to * the agent on output quiescence while the underlying process keeps * running, with no synchronous wake-up signal. Deferring queue draining * on them risks stranding messages indefinitely (e.g., the user keeps * a REPL alive). * * Use this predicate for paths that depend on a completion notification * to make progress — not for the idle-deferral path (which is drained * directly by `notifyBackgroundTaskChange()`) and not as the only * suspend-drain gate (since suspend preserves attached shells, * including notifying ones, across the resume boundary). * * Same subagent exclusion as `hasActiveBackgroundWork()`: when this * session's shell context is inherited from a parent, the shells live * in the parent and their completion only pulses the parent's task * registry. Subagents must not gate on parent-owned shells. */ private hasNotifyingBackgroundWork; /** * Emit `assistant.idle` whenever the main agent's processing loop * quiesces. * * Unlike `session.idle` — which is deferred until related background work * (running agents or in-flight attached shell commands) drains — this * fires every time the foreground agentic loop goes idle, regardless of * whether background work remains. It is a lightweight signal: SDK * consumers (e.g. an editor that wants to allow a follow-up prompt while * background work continues) can react to the main agent going idle * without waiting for the deferred `session.idle`. Consumers that need * details of any pending background work can call the tasks API; the * `session.background_tasks_changed` event signals when to re-fetch. When * there is no background work, this fires immediately before the matching * `session.idle`. * * Not emitted on the suspend tear-down path; see `processQueuedItems`. */ private emitAssistantIdle; 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; /** * 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). */ getPendingSteeringMessagesDisplayPrompt(): ReadonlyArray; getPendingQueuedMessagesDisplayPrompt(): ReadonlyArray; /** * Get pending queued items for UI display. * Returns both messages and commands with their display text. */ getPendingQueuedItems(): ReadonlyArray; /** * @deprecated Use getPendingQueuedItems() instead for proper display of mixed queue items. */ getPendingQueuedMessages(): ReadonlyArray; /** * 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; /** * 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). * * @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; /** * 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. */ 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; /** * 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 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; /** * 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; protected getOrCreateShellConfig(): ShellConfig; /** * Removes CAPI copilot credentials from a freshly built settings object for a * BYOK/legacy-provider request, enforcing the invariant that a BYOK-backed model * request never carries CAPI credentials. * * The session already passes `undefined` for the CAPI copilot token, HMAC key, and * session token when the resolved backend is BYOK. That is not sufficient on its own: * {@link buildSettings} merges {@link loadEnvironmentSettings} (which populates * `api.copilot.hmacKey` from `CAPI_HMAC_KEY`, `api.copilot.token` from * `GITHUB_COPILOT_API_TOKEN`, and `api.copilot.azureKeyVaultUri` from * `CAPI_AZURE_KEY_VAULT_URI`) via lodash.merge, which ignores the `undefined` overrides. * So in any environment that provides those CAPI credentials (e.g. the Actions runtime), * they would otherwise survive into the BYOK request's settings. This scrub completes the * isolation regardless of the ambient environment. */ private stripCapiCredentialsForByokRequest; private getEffectiveLegacyProviderConfig; /** * Merge the session-level largeOutput config (from {@link SessionOptions.largeOutput}) * into freshly-built {@link RuntimeSettings}. 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; /** * 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; /** * Resolve a user override for a dynamic-retrieval category from the * environment. Returns `true`/`false` to force the category on/off — * winning over the ExP arm and feature flags — or `undefined` when no * override is set. Populated by the CLI from the persisted * `dynamicRetrieval` user setting and the `--dynamic-retrieval * =` flag (see src/cli/index.ts). */ private resolveDynamicRetrievalCategoryOverride; 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; /** Convenience wrapper that delegates to the shared top-level function. */ private resolveToolSearchEnabled; private resolveIsRubberDuckAgentExpEnabled; /** * 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; /** * 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): Set; /** 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(allTools: T[]): T[]; private invokeCallbacks; /** Emit model_resolution_info telemetry once per session. */ private emitModelResolutionInfo; private getModelList; protected getAvailableModelsForAgentValidation(): Promise; /** * 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; /** * Emits an `assistant.usage` event from a `model_call_success`, computing the * cost multiplier from the supplied attribution. Shared by the agent callback * bridge (sub-agent/sidekick) and the direct MCP sampling completion so * initiator, multiplier, and `quotaSnapshots` handling cannot diverge. */ protected emitAssistantUsageFromModelCall(event: ModelCallSuccessEvent, attribution: { initiator: string; useModelMultiplier: boolean; isByokRequest: boolean; parentToolCallId?: string; }): Promise; /** * 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; /** * 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; /** * Executes the full agentic loop for a given prompt. * This method orchestrates the complete AI agent workflow including: * - Running hooks (userPromptSubmitted, 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 * @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; /** * 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; }): IAgentCallback; } /** * SessionManager subclass that persists sessions to JSONL files. * Uses SessionEventState for all file system operations. */ declare class LocalSessionManager implements SessionManager, 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; /** Per-session hook loggers, cached so deferred/reloaded hooks reuse the same logger. */ private sessionHookLoggers; /** * 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; private readonly shellNotifier; private readonly extensionControllers; private readonly telemetrySenders; /** Exporters owned by runtime-spawned sessions, keyed by session ID. */ private readonly spawnedExporters; /** * State machine for the runtime-managed remote-control singleton. * Mutated only by `startRemoteControl*` / `transferRemoteControl*` / * `stopRemoteControl*` / `setRemoteControlSteering*` / spawn callbacks. * The CLI reads it via `getRemoteControlStatus` and the corresponding * `sessionsApi` schema methods. */ private remoteControlState; /** * Bounded FIFO of spawn events for cursor-based long-poll consumers * (`pollSpawnedSessions`). Each event gets a monotonic sequence * number; consumers pass back the last seen `seq` as their cursor. */ private spawnedEventQueue; private spawnedSeqCounter; /** Awaiters parked inside `pollSpawnedSessions` waiting for new events. */ private spawnedWaiters; private static readonly SPAWN_POLL_MAX_WAIT_MS; private static readonly SPAWN_QUEUE_MAX; /** Factory for creating per-session virtual filesystems. */ sessionFsFactory: (sessionId: string, settings?: RuntimeSettings) => 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; /** * 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?: RuntimeSettings) => 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; /** * Get effective settings, preferring options.configDir over this.settings */ private getEffectiveSettings; private hasLegacyFlatSessionFile; /** * Create a new file-backed session */ createSession(options?: SessionOptions, emitStart?: boolean): Promise; private getHooksDir; /** * 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; /** * Load all hooks (user, repo, plugin), respecting disableAllHooks repo config. * When deferRepoHooks is true, repo config and repo hook configs are skipped — * only user hooks and global config are loaded. Used pre-trust to avoid reading * untrusted repo content. */ private loadAllHooks; private loadHooks; /** 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; startRemoteControl(params: { sessionId: string; config: RemoteControlConfig_2; }): Promise; private setupForegroundExporter; transferRemoteControl(params: { toSessionId: string; expectedFromSessionId?: string; }): Promise<{ status: RemoteControlStatus_2; transferred: boolean; }>; setRemoteControlSteering(params: { enabled: boolean; }): Promise; stopRemoteControl(params?: { expectedSessionId?: string; force?: boolean; }): Promise<{ status: RemoteControlStatus_2; stopped: boolean; }>; getRemoteControlStatus(): RemoteControlStatus_2; pollSpawnedSessions(params?: { cursor?: string; waitMs?: number; }): Promise<{ events: Array<{ sessionId: string; }>; cursor: string; }>; private remoteControlAttachedSessionId; private computeRemoteControlStatus; private notifySpawnedSession; private stopSpawnedExporterIfAny; /** * Internal session spawner invoked when Mission Control sends a * `start_session` command. Creates, authenticates, and exports a new * session without CLI involvement, then enqueues a spawn event that * CLI surfaces consume via {@link pollSpawnedSessions}. */ private spawnRemoteSession; /** * 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; /** * 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; /** * Get the most recently updated session */ getLastSession(options?: Omit, behavior?: ResumeBehavior): Promise; /** * Get the ID of the most recently updated session */ getLastSessionId(): Promise; /** * 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; /** * 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; /** * 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; /** * Resolve a session's persisted remote steering state. */ getPersistedRemoteSteerable(sessionId: string, settings?: RuntimeSettings): Promise; /** * 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; /** * 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?: RuntimeSettings): Promise; saveSession(session: Session): Promise; /** Flush a session's pending events to disk by session ID. */ saveSessionById(sessionId: string, options?: { force?: boolean; }): Promise; /** 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; /** * 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; 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; /** * 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; /** * 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; /** * 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[]>; /** * 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; private isDetachedSession; private getVisibleSessionEntriesWithBoundedDetachedDetection; private isDetachedSessionMarkerOnly; private hasDetachedSessionMarker; private writeDetachedSessionMarker; private readDetachedStatusFromSessionStart; /** * Delete a session from disk. */ deleteSession(sessionId: string): Promise; /** * 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?: RuntimeSettings): Promise; /** * 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>; /** * 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; /** * 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; 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>; /** * 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>; /** * 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; /** * 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; /** * Helper method to fetch from git remote */ private gitFetch; } declare type LocalSessionManagerOptions = { version?: string; flushDebounceMs?: number; settings?: RuntimeSettings; /** * 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; } /** Schema for the `LocalSessionMetadataValue` type. */ 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; /** @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; } /** * 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; /** Extra OTel resource attributes (⇄ OTEL_RESOURCE_ATTRIBUTES). */ resourceAttributes?: Record; /** 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; } /** Schema for the `MarketplaceRefreshEntry` type. */ 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 and external tools as deferred when the total tool count exceeds * {@link DEFERRED_TOOLS_THRESHOLD}. Deferred tools are sent to the model with * `copilot_defer_loading: true` and are discovered via the tool_search tool. * * * @param tools - The full mutable array of tools (modified in place) * @param externalToolNames - Names of externally-provided tools */ declare function markToolsAsDeferred(tools: Tool_2[], externalToolNames: ReadonlySet): void; /** Maximum size of the aggregated `additionalContext` from postToolUse hooks before truncation. */ export declare const MAX_POST_TOOL_USE_CONTEXT_LENGTH: number; export declare const MAX_POST_TOOL_USE_FAILURE_CONTEXT_LENGTH: number; /** Schema for the `McpAllowedServer` type. */ 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 "). */ redactedNote?: string; } /** MCP server, tool name, and arguments to invoke from an MCP App view. */ declare interface McpAppsCallToolRequest { /** Tool arguments */ arguments?: Record; /** **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[]; } /** 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[]; } /** Schema for the `McpAppsResourceContent` type. */ declare interface McpAppsResourceContent { /** Resource-level metadata (CSP, permissions, etc.) */ _meta?: Record; /** 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; /** 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; /** 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 { /** Schema for the `McpAppToolCallCompleteToolMetaUI` type. */ ui?: McpAppToolCallCompleteToolMetaUI; [key: string]: unknown; } /** Schema for the `McpAppToolCallCompleteToolMetaUI` type. */ 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; } /** * 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; } /** 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; } /** Schema for the `McpFilteredServer` type. */ 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; 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. */ declare class McpHeadersRefreshManager { private readonly callback; private readonly cache; private readonly inflightRefreshes; private readonly invalidationGenerations; constructor(callback: HeadersRefreshCallback); getHeaders(params: HeadersRefreshParams): Promise | undefined>; refreshAfterAuthFailure(params: AuthFailedHeadersRefreshParams): Promise | undefined>; invalidate(serverName: string): void; private refresh; private refreshCore; private invalidateCacheKey; private getInvalidationGeneration; private getCacheKey; private isCacheKeyForServer; private getTtlMs; private normalizeHeaders; } /** 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 processor; protected config: MCPServersConfig; private startServersPromise?; protected transport: InProcMCPTransport | null; private disabledServers; private progressCallback?; private traceContextResolver?; private mcpToolCallInterceptor?; private taskRegistry?; private mcp3pEnabled; private configFilter; private elicitationHandler?; protected statusCallback?: ServerStatusCallback; protected logger: RunnerLogger; protected onOAuthRequired?: McpHostOptions["onOAuthRequired"]; protected onOAuthReauthNonInteractive?: McpHostOptions["onOAuthReauthNonInteractive"]; /** Last non-interactive re-auth attempt per server; rate-limits per-turn retries. */ private readonly lastReauthAttempt; protected headersRefreshManager?: McpHeadersRefreshManager; protected settings?: RuntimeSettings; /** * 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 filteredServerNames; /** In-flight `handleToolsChanged` promises; awaited by `awaitPendingToolsChanges` (#7432). */ private pendingToolsChanges; private pendingServerStarts; /** * Single-flight chain for `applySandboxConfig` so concurrent sandbox toggles * serialize on a single restart pipeline instead of interleaving stops/starts. */ private sandboxApplyChain; /** 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; constructor(options: McpHostOptions); /** * 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; /** 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; /** Register a callback invoked when an individual server's connection status changes. */ setOnServerStatusChanged(callback: (serverName: string, status: ServerConnectionStatus) => 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; /** * 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; 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; /** * 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 runtime settings. * @param logger - The logger instance. * @param permissions - Permissions configuration for tool access. * @returns A promise that resolves to an array of tools. */ getTools(settings: RuntimeSettings, logger: RunnerLogger, permissions: PermissionsConfig): Promise; /** * Gets the current MCP configuration. */ getConfig(): MCPServersConfig; /** * Returns the set of MCP server names that are built-in/default servers. * Tools from these servers should not be deferred — the model should * always see them without requiring a tool_search discovery step. */ getDefaultServerNames(): Set; /** * Gets all connected MCP clients. * @returns A record of server names to their client instances */ getClients(): Record; /** * Gets all servers that failed to connect. * @returns A record of server names to their failure information */ getFailedServers(): Record; /** * Gets all servers that require user-initiated authentication. * @returns A record of server names to their needs-auth information */ getNeedsAuthServers(): Record; /** * 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>; /** * 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): Promise; private isServerActiveForConfig; private applyConfigFilterToServer; private startServerOnce; /** * 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; /** * Restart a server with new configuration * @param serverName - Name of the server to restart * @param config - New server 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): Promise; /** * 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: OAuthClientProvider): Promise; reconnectServerWithOAuthReplacement(serverName: string, request: HostDelegatingOAuthRequest): Promise; /** * 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; /** * 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; /** * Reconnect a remote OAuth server after a mid-session 401. First tries the * non-interactive path (cached/refresh/`client_credentials`); if that cannot * produce a provider, or produces a provider the server still rejects during * initialize, falls back to the host's force-reauth OAuth handler when one is * available. Without an interactive handler it records `needs-auth` and throws * so the caller can defer. */ reconnectServerWithFreshOAuth(serverName: string): Promise; private getInteractiveOAuthReauthProvider; /** * 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 non-interactive 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): Promise; /** * Non-interactively retry every remote OAuth server currently in `needs-auth`. * Intended to run at the start of an assistant turn so a server the user or * host authenticated out of band recovers automatically. Best-effort and * rate-limited per server; OIDC servers are skipped (they recover via their * own resolver path). Returns the names of servers that reconnected. */ retryAuthRequiredServers(): Promise; /** * 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; /** * 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. */ registerExternalClient(serverName: string, client: NativeMcpSession, transport: Transport, config: MCPServerConfig): void; /** * 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; /** * 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; /** * 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; /** * 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; /** * Re-authenticate a remote MCP server by clearing cached OAuth tokens * and restarting the connection with a forced OAuth flow. * Override in subclasses that support OAuth (e.g., CliMcpHost). * @param serverName - Name of the server to re-authenticate */ reauthenticateServer(_serverName: string): Promise; /** * 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; /** * 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; /** * 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; /** * Gets tool summaries for servers with deferred instructions. * Used to enrich embedding text for better retrieval relevance. */ getDeferredServerToolSummaries(): Promise>>; /** * 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 | undefined, hostOptions?: Omit): Promise; /** * Get an existing host for the given agent ID. */ getHost(agentId: string): McpHost | undefined; /** * Stop and remove all MCP hosts. */ cleanup(): Promise; /** * 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; setAllowAllServerInstructions(allowAllServerInstructions: boolean): 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) => Promise; onHeadersRefresh?: HeadersRefreshCallback; settings?: RuntimeSettings; elicitationHandler?: (serverName: string, request: ElicitRequestParams) => Promise; samplingHandler?: (serverName: string, requestId: string | number, request: CreateMessageRequestParams) => Promise; mcp3pEnabled?: boolean; onOIDCAuthRequired?: OIDCAuthCallback; /** * Non-interactive OAuth re-authentication used for mid-session tool-call * retry and per-turn recovery. Returns a provider when fresh tokens can be * obtained WITHOUT user/host interaction (cached tokens, refresh, or the * `client_credentials` grant), or `undefined` when interaction would be * required — in which case the caller defers to `needs-auth` rather than * blocking the tool call on a browser/broadcast flow. */ onOAuthReauthNonInteractive?: (serverName: string, config: MCPRemoteServerConfig) => Promise; 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; /** * 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; } /** 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; /** 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; /** Names of servers with in-flight connection attempts. */ pendingConnections: string[]; } declare interface MCPInMemoryServerConfig extends MCPServerConfigBase { type: "memory"; serverInstance: McpServer_2; } /** 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; } /** 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; cwd?: string; } /** 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; } /** 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; 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 { /** 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; } /** MCP OAuth request id and optional provider response. */ declare interface McpOauthRespondRequest { /** In-process OAuthClientProvider instance, or omitted to deny. Marked internal: cannot be serialized across the JSON-RPC boundary. */ provider?: unknown; /** OAuth request identifier from mcp.oauth_required */ requestId: string; } /** Empty result after recording the MCP OAuth response. */ declare interface McpOauthRespondResult { } 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 {@link oauthStoreKey}. * 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; saveTokens(key: string, tokens: MCPOAuthTokens): Promise; deleteTokens(key: string): Promise; getClientRegistration(key: string): Promise; saveClientRegistration(key: string, registration: MCPClientRegistration): Promise; deleteClientRegistration(key: string): Promise; getStaticClientSecret(key: string): Promise; saveStaticClientSecret(key: string, secret: string): Promise; deleteStaticClientSecret(key: string): Promise; saveCodeVerifier(key: string, verifier: string): Promise; getCodeVerifier(key: string): Promise; clearCodeVerifier(key: string): Promise; } /** * 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; }; /** * 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; }>; /** 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 logger; envValueMode: EnvValueMode; protected settings?: RuntimeSettings | undefined; /** Enable MCP Apps (SEP-1865) support. Combined with the FF in {@link isMcpAppsEnabled}. */ private mcpAppsEnabled; protected sandboxConfig?: SandboxConfig_2 | undefined; private headersRefreshManager?; private allowAllServerInstructions; clients: Record; transports: Record; configs: Record; /** * Server instructions provided by MCP servers during initialization. * These instructions describe how to use the server and its features. */ serverInstructions: Record; /** * Server instructions captured for embedding-based retrieval. * These are NOT included in the system prompt but indexed for JIT injection. */ deferredServerInstructions: Record; /** * Pending connection promises for servers that are connecting in the background. * Used for deferred connections where we don't want to block on server startup. */ pendingConnections: Record>; /** * Servers that failed to connect, with their error information. * Used to track and display connection failures to users. */ failedServers: Record; /** * Stderr streams for local MCP server processes, keyed by server name. * Used to retrieve stderr output when a server fails to start. */ private serverStderrStreams; /** * Servers that require user-initiated OAuth authentication. * Distinct from failed — the server would work if the user authenticates. */ needsAuthServers: Record; private toolsChangedCallback?; private elicitationHandler?; private samplingHandler?; /** Callback invoked when a server sends a notifications/elicitation/complete notification. */ private elicitationCompleteCallback?; private statusChangedCallback?; /** * Callback invoked when a server sends a notification the registry does not * route itself (e.g. a builtin server's `notifications/copilot` message). The * host interprets these per-server — see {@link McpHost}. */ private builtinNotificationCallback?; /** * Metadata needed to reconnect remote (HTTP/SSE) servers after transient disconnections. * Stored when a remote server is first connected; cleared on intentional stop. */ private remoteReconnectMeta; /** * Servers that were intentionally disconnected (e.g., via stopServer). * Prevents auto-reconnection from firing after deliberate shutdown. */ private intentionalDisconnects; /** * In-flight reconnection promises, keyed by server name. * Prevents duplicate concurrent reconnection attempts. */ private pendingReconnects; constructor(logger: RunnerLogger, envValueMode?: EnvValueMode, settings?: RuntimeSettings | undefined, elicitationHandler?: (serverName: string, request: ElicitRequestParams) => Promise, samplingHandler?: (serverName: string, requestId: string | number, request: CreateMessageRequestParams) => Promise, /** Enable MCP Apps (SEP-1865) support. Combined with the FF in {@link isMcpAppsEnabled}. */ mcpAppsEnabled?: boolean, sandboxConfig?: SandboxConfig_2 | undefined, headersRefreshManager?: McpHeadersRefreshManager | undefined, allowAllServerInstructions?: boolean); /** * Register a callback to be invoked when a server sends a tools/list_changed notification. * The callback can be sync or async. */ setToolsChangedCallback(callback: (clientName: string) => void | Promise): void; /** * Register a callback to be invoked when a server sends a notifications/elicitation/complete notification. */ setElicitationCompleteCallback(callback: (elicitationId: string) => void): void; /** Store the current abort signal for in-flight MCP tool call cancellation. */ private _abortSignal?; setAbortSignal(signal?: AbortSignal): void; getAbortSignal(): AbortSignal | undefined; /** Register a callback invoked when an individual server's connection status changes. */ setOnStatusChanged(callback: (serverName: string, status: ServerConnectionStatus) => void): void; /** * Register a callback invoked when a server sends a notification the registry * does not route itself, so the host can interpret builtin server * notifications (e.g. `user.abort`). */ setBuiltinNotificationCallback(callback: (serverName: string, method: string, params: unknown) => void): void; /** * Update the sandbox policy used when spawning new local (stdio) MCP servers. * Already-running servers retain their original policy until they are restarted — * callers that need them to pick up the new policy (e.g. the user toggling * `/sandbox`) must restart them explicitly via {@link McpHost.applySandboxConfig}. */ setSandboxConfig(config?: SandboxConfig_2): void; /** * Get the extra client capabilities advertised during the native initialize * handshake (beyond the sampling/elicitation support implied by a wired * responder). MCP Apps (SEP-1865) is advertised via the * `io.modelcontextprotocol/ui` extension when the per-session `mcp-apps` * capability is set. * * The `MCP_APPS` feature flag (and `COPILOT_MCP_APPS=true` env override) acts * as a fallback enable for environments that grant the capability by default * — e.g. an org-wide rollout where the FF flips on and any session without an * explicit `mcp-apps` opt-in still benefits. Either signal is sufficient. * * The MCP Tasks extension (spec 2025-11-25) is gated behind the `MCP_TASKS` * experimental flag. When disabled we omit the `tasks` capability so * well-behaved servers won't route through the task path; we also enforce * this defensively at the host detection layer (see `mcp-host.ts`). */ private getCapabilityOptions; /** * Computes the `initialize` handshake timeout for a connect. * * `serverConfig.timeout` is documented and used elsewhere as the per-tool-call * timeout, which can be much shorter than a slow `initialize` handshake (e.g. a * server with a 2s tool timeout still needs tens of seconds to broker auth on * startup). We therefore use it only to *extend* the handshake budget, never to * shorten it below {@link DEFAULT_CONNECT_TIMEOUT_MS}, so reusing the field here * cannot regress startup for servers configured with a low tool-call timeout. */ private getConnectTimeoutMs; /** * Build the bridge handlers shared by every connect path: the notification * router (tools/list_changed + elicitation/complete), the sampling responder, * and the elicitation responder. The responders are only created when their * corresponding handler is wired, so the native client advertises each * capability accordingly. */ private buildBridgeHandlers; /** * Record a server connection failure. * @param serverName - Name of the server that failed * @param error - The error that caused the failure */ recordFailure(serverName: string, error: Error): void; /** * Clear a server's failure record (e.g., when it successfully reconnects). * @param serverName - Name of the server */ clearFailure(serverName: string): void; /** * Returns the first stderr line captured from a local server process, if any. * @param serverName - Name of the server */ getServerStderr(serverName: string): string | undefined; /** * Record that a server requires user-initiated OAuth authentication. * Clears any existing failure record since the server isn't truly failed. * @param serverName - Name of the server */ recordNeedsAuth(serverName: string): void; /** * Clear a server's needs-auth record (e.g., after successful authentication). * @param serverName - Name of the server */ clearNeedsAuth(serverName: string): void; /** * Mark a server as intentionally disconnected to prevent auto-reconnection. * Call this before closing a remote server's transport. * * Per MCP spec §"Session Management": "Clients that no longer need a particular * session SHOULD send an HTTP DELETE to explicitly terminate the session." * Callers are responsible for sending the DELETE (via transport.terminateSession()) * before or after calling this method. * * @param serverName - Name of the server being intentionally stopped */ markIntentionalDisconnect(serverName: string): void; /** * Whether the given server has been marked as intentionally disconnected * (e.g. by stopServer/stopServers during shutdown or reconfiguration). * Used by the connect/retry path to bail out instead of reconnecting a * server whose teardown is already in progress. * * @param serverName - Name of the server */ isIntentionalDisconnect(serverName: string): boolean; /** * Get the connection status of a server. * @param serverName - Name of the server * @returns The server's connection status */ getServerStatus(serverName: string): ServerConnectionStatus; /** * Ensures a server is connected before invoking tools. * If the server has a pending connection, waits for it to complete. * @param serverName - Name of the server to ensure is connected * @throws Error if the pending connection fails */ ensureConnected(serverName: string): Promise; startLocalMcpClient(serverName: string, serverConfig: MCPLocalServerConfig): Promise; /** * Start a local MCP client with deferred connection. * The server process is started immediately but the connection is established in the background. * Use this for servers where we have a static tool manifest and don't need to wait for * the connection to complete before using the tools list. * * The client is added to registry.clients immediately (before connection completes), * so it will be included when iterating over clients. Call ensureConnected() before * invoking any tool on this server. * * @param serverName - Name of the server * @param serverConfig - Server configuration */ startLocalMcpClientDeferred(serverName: string, serverConfig: MCPLocalServerConfig): void; /** * Augments the given headers with the default User-Agent that this registry * applies to live remote connections. Used to keep the OAuth challenge probe's * request headers in parity with the connection that triggered the challenge. */ connectionHeadersWithDefaultUserAgent(headers: Record | undefined): Record; /** * Builds the native dynamic-header provider that bridges the engine's * per-request header lookups to the host {@link McpHeadersRefreshManager}. * Returns `undefined` when no manager is configured, so the connection runs * with only its static headers (no overlay, no `401`-refresh retry). */ private buildNativeHeadersRefresh; getRemoteAuthProvider(serverName: string): OAuthClientProvider | undefined; startHttpMcpClient(serverName: string, serverConfig: MCPRemoteServerConfig, authProvider?: OAuthClientProvider, headersRefreshManager?: McpHeadersRefreshManager): Promise; startSseMcpClient(serverName: string, serverConfig: MCPRemoteServerConfig, authProvider?: OAuthClientProvider, headersRefreshManager?: McpHeadersRefreshManager): Promise; startInMemoryMcpClient(serverName: string, serverConfig: MCPServerConfig, serverInstance: McpServer_2): Promise; /** * Test a connection to a remote MCP server without registering it. * This is useful for validating server configuration before saving. * Throws UnauthorizedError if the server requires authentication. * Throws other errors if the connection fails for other reasons. * * @param serverUrl - The URL of the remote server * @param serverType - The type of transport ("http" or "sse") * @param headers - Optional headers to include in requests * @param authProvider - Optional OAuth provider for authenticated connections */ testRemoteConnection(serverUrl: string, serverType: "http" | "sse", headers?: Record, authProvider?: OAuthClientProvider): Promise; /** * Attempt to reconnect a remote (HTTP/SSE) server after a transient disconnection. * Uses exponential backoff with a maximum number of retries. * On success, the server is fully re-registered in the registry. * On failure, the server is marked as failed. * * This implements the client-side reconnection behavior described in the MCP spec: * - Disconnections are transient and SHOULD NOT cancel requests * (§"Sending Messages to the Server", item 6) * - Clients SHOULD resume via HTTP GET with Last-Event-ID after broken connections * (§"Resumability and Redelivery") * - Clients MUST start a new session (InitializeRequest) when receiving HTTP 404 * for an expired session (§"Session Management") * * Our reconnection calls client.connect() which sends a fresh InitializeRequest, * establishing a new session as the spec requires. * * @see https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http */ /** * Builds an `onClose` callback for a direct-Rust session (one with no JS * transport object to hang lifecycle off). On connection close it removes the * session from the registry — identity-guarded via `bind` so a superseded * reconnect can't clobber the live session — emits a status change, and, for * remote servers not intentionally stopped, schedules a background reconnect. * This restores the crash/disconnect cleanup and proactive reconnect that the * JS `Client`'s `transport.onclose` previously provided. */ private makeDirectCloseHandler; private attemptReconnect; getTools(mcpServersConfig: MCPServersConfig | undefined, sessionClient?: CopilotSessionsClient): Promise>; private getServerTools; private logServerSuccessWithTools; /** * Gets all server instructions from connected MCP servers. * @returns A record mapping server names to their instructions */ getServerInstructions(): Record; getServerInstructionMode(): MCPServerInstructionMode; setAllowAllServerInstructions(allowAllServerInstructions: boolean): void; getServerInstructionsNotInAllowlistCount(): number; /** * Gets server instructions captured for embedding-based retrieval. * These are deferred from the system prompt and indexed for JIT injection. */ getDeferredServerInstructions(): Record; /** * Gets tool summaries (name and description) for each server that has * deferred instructions. Uses the already-connected clients to list tools. */ getDeferredServerToolSummaries(): Promise>>; } /** 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; /** * 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; } /** Server name and opaque configuration for an individual MCP server restart. */ declare interface McpRestartServerRequest { /** Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. */ config: unknown; /** Name of the MCP server to restart */ serverName: string; } declare interface McpSamplingAgentResult { 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; /** Save a secret value. Returns true if stored in keychain, false if file fallback. */ saveSecret(secretId: string, value: string): Promise; /** Delete a secret by its ID. */ deleteSecret(secretId: string): Promise; /** Delete all secrets for a given server name. */ deleteServerSecrets(serverName: string): Promise; /** * 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; } /** Schema for the `McpServer` type. */ 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; close?(): Promise; 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 | ContentFilterMode; /** * 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. For example, when the built-in * `create_pull_request` is active, add `"create_pull_request"` here to prevent the * github-mcp-server copy from appearing in the tool list. */ 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; /** 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; /** 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; /** * 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; } declare interface MCPServersConfig { mcpServers: Record; } /** * 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; }; }>; /** Schema for the `McpServersLoadedData` type. */ declare interface McpServersLoadedData { /** Array of MCP server status summaries */ servers: McpServersLoadedServer[]; } /** Session event "session.mcp_servers_loaded". */ declare interface McpServersLoadedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `McpServersLoadedData` type. */ 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"; } /** Schema for the `McpServersLoadedServer` type. */ 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"; /** Schema for the `McpServerStatusChangedData` type. */ 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". */ declare interface McpServerStatusChangedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `McpServerStatusChangedData` type. */ 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 opaque configuration for an individual MCP server start. */ declare interface McpStartServerRequest { /** Opaque server configuration (MCPServerConfig). Marked internal: an in-process runtime shape supplied only by in-process CLI callers. */ config: unknown; /** 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; declare interface McpToolCallInterceptor { (input: McpToolCallInterceptorInput): Promise; hasHooks?: () => boolean; } declare interface McpToolCallInterceptorInput { toolCallId?: string; serverName: string; toolName: string; arguments: Record; _meta?: Record; } declare interface McpToolCallInterceptorOutput { metaToUse?: Record | null; } /** Schema for the `McpTools` type. */ declare interface McpTools { /** Tool description, when provided. */ description?: string; /** Tool name. */ name: string; } /** * 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; /** The normalized server names that were added (used to filter out overridden servers from outer agent) */ serverNames?: string[]; }; declare abstract class MCPTransport { protected readonly settings: RuntimeSettings; protected readonly logger: RunnerLogger; protected readonly cacheProviderTools: boolean; /** * Per-host MCP Apps opt-in. Set by the owning {@link McpHost} via * {@link setMcpAppsEnabled} when the session that constructed this * transport has the `mcp-apps` capability. Used together with the * runtime feature flag in {@link isMcpAppsActive} so the transport * preserves `_meta.ui` on tools and fetches `ui://` resources when * either signal is present. */ private mcpAppsEnabled; setMcpAppsEnabled(enabled: boolean): void; protected isMcpAppsActive(): boolean; protected cachedTools: Map>; private _progressCallback?; private _traceContextResolver?; private _mcpToolCallInterceptor?; protected secretMaskingDisabledTools: Set; constructor(settings: RuntimeSettings, logger: RunnerLogger, cacheProviderTools: boolean); /** * Set the callback to be invoked when an MCP tool reports progress. */ setProgressCallback(callback: ToolProgressCallback | undefined): void; /** * Set the resolver used to obtain OTel trace context for MCP tool calls. * When set, `traceparent`/`tracestate` will be injected into `params._meta` * of `callTool` requests, following the OTel MCP semantic conventions. */ setTraceContextResolver(resolver: TraceContextResolver | undefined): void; /** * Set the interceptor invoked before MCP tool calls are sent. */ setMcpToolCallInterceptor(interceptor: McpToolCallInterceptor | undefined): void; /** Returns the current trace context resolver, if set. */ protected get traceContextResolver(): TraceContextResolver | undefined; /** * Resolves OTel trace context for a tool call, returning a shaped object * suitable for injection into `_meta` or the HTTP request body. * Best-effort: returns `undefined` on error or when unavailable. */ protected resolveTraceContext(toolCallId?: string): { traceparent: string; tracestate?: string; } | undefined; protected get progressCallback(): ToolProgressCallback | undefined; protected interceptMcpToolCall(input: McpToolCallInterceptorInput): Promise | undefined>; /** * Refresh tools for a specific provider. * This completely reloads the provider's tools, clearing all cached state. * Called when a tools/list_changed notification is received or when tools need to be refreshed. */ refreshProvider(provider: ToolsProviderT): Promise; /** * Hook for subclasses to perform additional cleanup when a provider is refreshed. * Default implementation does nothing. */ protected onProviderRefresh(_provider: ToolsProviderT): Promise; invokeTool(toolId: string, toolParams: Record, filterMode?: ContentFilterMode, toolCallId?: string, customAgentName?: string): Promise; /** * Combine `content` text and `structuredContent` into a single LLM-visible string, * never dropping either side. * * Per MCP spec [§5.2.6](https://modelcontextprotocol.io/specification/2025-11-25/server/tools#structured-content), * a server returning `structuredContent` SHOULD also surface the serialized JSON in a * `TextContent` block for backwards compatibility, but this is a SHOULD, not a MUST. * Servers in the wild send the structured payload alone, or pair it with human-readable * text that is not a literal JSON serialization. Dropping either side loses information, * so we surface both: text first (human-readable narrative), then the JSON payload, * deduplicated when `content` is already the literal serialization of `structuredContent`. * * Rules: * - Only `content` text → return text as-is. * - Only `structuredContent` → return its JSON serialization. * - Both, with text == JSON → return one copy (spec-compliant duplicate). * - Both, with text != JSON → return `text + "\n\n" + json` (avoid info loss). * - `JSON.stringify` throws → fall back to text-only (BigInt, cycles, etc.). * - `structuredContent` is `null` → treat as absent (non-conformant per spec; avoid * surfacing the literal string `"null"` to the LLM). */ protected combineContentAndStructured(textFromContent: string, structuredContent: unknown): string; /** * UTF-8 byte length of the serialized `structuredContent`, for telemetry. * Returns `undefined` when the payload cannot be serialized (BigInt, cycles, * `JSON.stringify` returning `undefined`, etc.) so the metric is simply omitted. */ private measureStructuredContentBytes; /** * Allows us to directly invoke a tool, which could be one that is suppressed from the tool list. * - Response can be either a text or a Base64 encoded image based on mcp-client/src/MCPServer.ts implementation of the invoke-tool endpoint. * - If `isToolError` is true, it means the tool call failed. */ protected abstract doInvokeTool(toolId: string, toolParams: Record, toolCallId?: string, customAgentName?: string): Promise; protected invokeToolResponseToToolResult(responseData: InvokeToolResponseData, filterMode: ContentFilterMode): ToolResultExpanded; private addMcpServerContext; private invokeToolWithMcpContext; loadTools(provider: ToolsProviderT, permissions?: PermissionsConfig): Promise; protected abstract getProviderCacheKey(provider: ToolsProviderT): string; protected abstract loadToolsFromProvider(provider: ToolsProviderT): Promise>; } /** 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; microphone?: Record; geolocation?: Record; clipboardWrite?: Record; } /** * 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; } /** * Result from getMemoriesPrompt containing both prompt components and tool definitions. * - memoriesContext: The formatted memories for injection into the system prompt (undefined if no memories) * - storeInstructions: Instructions for when/how to use store_memory tool * - storeToolDefinition: Metadata for the store_memory tool from API * - voteToolDefinition: Metadata for the vote_memory tool from API (only when voting is enabled) * - toolName / toolDescription: Deprecated store tool metadata retained for backward compatibility * - memoriesCount: Number of memories retrieved from the API (0 if none, undefined for test-injected memories) */ declare type MemoriesPromptResult = { memoriesContext?: string; storeInstructions?: string; /** Store tool metadata from the /prompt API (includes definitionVersion for scope detection). */ storeToolDefinition?: MemoryToolDefinition; /** Vote tool metadata from the /prompt API (present when voting is enabled server-side). */ voteToolDefinition?: MemoryToolDefinition; memoriesCount?: number; }; /** Shared mutable cache for Memory API results, owned by the session and passed * into every ToolConfig. Deduplicates concurrent API calls on the * first turn and provides a fast path on subsequent turns. */ declare type MemoryApiCache = { promise?: Promise; /** The repo the in-flight promise was initiated for, so repo-change * invalidation can discard stale in-flight fetches. */ promiseRepoName?: string; result?: MemoryApiCacheResult; }; /** Cached result from the Memory API, including the repo it was fetched for. */ declare type MemoryApiCacheResult = { enabled: boolean; repoName?: string; } & Partial; 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; }; /** Tool definition metadata from the Memory API /prompt response. */ declare type MemoryToolDefinition = { name: string; description: string; definitionVersion?: string; }; /** * Merges two QueryHooks objects by concatenating arrays for each hook type. * Does not mutate the input objects. */ export declare function mergeQueryHooks(existing: QueryHooks | undefined, additional: QueryHooks | undefined): QueryHooks; /** * 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 | undefined, requestHeaders: Record | undefined): Record | 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; } | 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[]; }; /** * Set of 16 key-value pairs that can be attached to an object. This can be useful * for storing additional information about the object in a structured format, and * querying for objects via API or the dashboard. * * Keys are strings with a maximum length of 64 characters. Values are strings with * a maximum length of 512 characters. */ declare type Metadata = { [key: string]: string; }; /** 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). */ declare interface MetadataRecordContextChangeResult { } /** Absolute path to set as the session's new working directory. */ 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 `process.chdir` and any related side-effects (file index, etc.); this method only updates the session's own recorded 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; /** * 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; }; /** 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; }[]; }; /** Schema for the `Model` type. */ 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; /** Token-level pricing information for this model */ tokenPrices?: ModelBillingTokenPrices; } /** 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 */ 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. */ 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 */ 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. */ contextMax?: number; /** AI Credits cost per billing batch of input tokens */ inputPrice?: number; /** Prompt token budget for the long context tier. The total context window is this value plus the model's max_output_tokens. */ maxPromptTokens?: number; /** AI Credits cost per billing batch of output tokens */ outputPrice?: number; } /** For HTTP 400 failures only: whether the response carried a structured CAPI error envelope (structured_error, a deterministic validation failure) or no error body (bodyless, the transient gateway/proxy signature). Absent for non-400 failures. */ 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; /** 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; /** What initiated this API call (e.g., "sub-agent", "mcp-sampling"); absent for user-initiated calls */ initiator?: string; /** 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; /** 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; } /** 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 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; }; /** 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"; /** * ----------------------------------------------------------------------- * 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; error?: string; status?: number; 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; } 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; /** * 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_2; /** 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[]; } /** * Deep-partial override for model capabilities, derived from {@link Model}. * Only non-undefined values are applied over the runtime-resolved capabilities. */ declare type ModelCapabilitiesOverride = DeepOptional; /** Optional capability overrides (vision, tool_calls, reasoning, etc.). */ declare interface ModelCapabilitiesOverride_2 { /** Token limits for prompts, outputs, and context window */ limits?: ModelCapabilitiesOverrideLimits; /** Feature flags indicating what the model supports */ supports?: ModelCapabilitiesOverrideSupports; } /** Token limits for prompts, outputs, and context window */ declare interface ModelCapabilitiesOverrideLimits { /** Maximum total context window size in tokens */ max_context_window_tokens?: number; /** Maximum number of output/completion tokens */ max_output_tokens?: number; /** Maximum number of prompt/input tokens */ max_prompt_tokens?: number; /** Vision-specific limits */ vision?: ModelCapabilitiesOverrideLimitsVision; } /** Vision-specific limits */ declare interface ModelCapabilitiesOverrideLimitsVision { /** Maximum image size in bytes */ max_prompt_image_size?: number; /** Maximum number of images per prompt */ max_prompt_images?: number; /** MIME types the model accepts */ supported_media_types?: string[]; } /** Feature flags indicating what the model supports */ declare interface ModelCapabilitiesOverrideSupports { /** Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). */ adaptive_thinking?: AdaptiveThinkingSupport_2; /** Whether this model supports reasoning effort configuration */ reasoningEffort?: boolean; /** Whether this model supports vision/image input */ vision?: boolean; } /** Feature flags indicating what the model supports */ declare interface ModelCapabilitiesSupports { /** Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). */ adaptive_thinking?: AdaptiveThinkingSupport_2; /** Whether this model supports reasoning effort configuration */ reasoningEffort?: boolean; /** Whether this model supports vision/image input */ vision?: boolean; } /** Model change details including previous and new model identifiers */ 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_2; /** Reasoning effort level after the model change, if applicable */ reasoningEffort?: string | null; /** Reasoning summary mode after the model change, if applicable */ reasoningSummary?: ReasoningSummary_2; } /** 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; } /** 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_creation_input_tokens` which has * no standard OpenAI equivalent, and CAPI reports Gemini reasoning tokens * as top-level `reasoning_tokens`; this type carries that data alongside the * standard usage fields so all token counts travel together. */ declare type ModelResponseUsage = NonNullable & { prompt_tokens_details?: { /** Tokens written to the prompt cache (e.g. Anthropic's `cache_creation_input_tokens`). */ cache_creation_tokens?: 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_2; /** Model selection id to switch to, as returned by `list`. A bare id (e.g. `claude-sonnet-4.6`) names a Copilot (CAPI) model; a provider-qualified id (`provider/id`, e.g. `acme/claude-sonnet`) targets a registry BYOK model. */ modelId: string; /** Reasoning effort level to use for the model. "none" disables reasoning. */ reasoningEffort?: string; /** Reasoning summary mode to request for supported model clients */ reasoningSummary?: ReasoningSummary_3; } /** 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 ` 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; /** 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; /** * 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 * ` 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; } export declare interface NativeDeclarativeHook { readonly kind: "native"; /** Temporary compatibility shim for callers that still invoke hook.handler directly; forwards to Rust. */ readonly handler: HookHandler; readonly eventName: keyof QueryHooks; readonly config: CommandHookConfig | HttpHookConfig; readonly specJson: string; readonly repoRoot?: string; readonly source?: string; readonly isPolicy?: boolean; } /** * 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; /** * 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; [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 | undefined>; refreshAfterAuthFailure(): Promise | undefined>; } /** * 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; } /** 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; /** 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; /** 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; 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?; /** * Tears down a JS-side transport that the native close cannot reach. Only set * for {@link connectBridge}, whose `BridgeServerTransport` is created * internally (the caller never sees it), so {@link close} must close it to let * the in-process `McpServer` observe the disconnect. The native-owned * stdio/HTTP connections and the caller-owned {@link connectBridgeTransport} * transports are `undefined` here — the latter is closed by its owner so the * intentional-disconnect/reconnect coordination is preserved. */ private readonly bridgeCleanup?; 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; /** * 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; /** * 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; /** * 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; /** * Races `connectPromise` against a bounded connect-timeout timer, returning a * session for the resolved handle. The timeout can derive from user-supplied * server config, so it is clamped to {@link MAX_CONNECT_TIMEOUT_MS} before * arming the timer — a hostile, non-finite, or unbounded value must not be * able to schedule a pathologically long timer (resource exhaustion). When * `connectTimeoutMs` is not a finite positive number, the connection is * awaited without a timeout. */ private static raceConnectTimeout; /** * Races a void initialize/handshake promise against a bounded connect-timeout * timer, rejecting if the timer wins. Unlike {@link raceConnectTimeout}, the * caller owns teardown of the underlying handle on timeout: the bridge * initialize resolves to nothing, so there is no orphaned handle for this * helper to close. The timeout is clamped to {@link MAX_CONNECT_TIMEOUT_MS} * (it can derive from user-supplied server config), and a non-finite or * non-positive value awaits the promise without a timeout. */ private static awaitWithConnectTimeout; /** * Connects to an in-process MCP server over a channel-backed bridge * transport and completes the initialize handshake. Unlike the stdio and * remote connects, the native client cannot reach the server directly: this * adapter relays JSON-RPC frames between the Rust client and the in-process * JS `server` (whose tools may wrap arbitrary consumer closures that can only * run here). When `onNotification`, `onSampling`, and/or `onElicitation` are * provided they behave exactly as for the other transports. * * The handshake is bootstrapped in two phases because the native client * starts sending (`initialize`) before the JS server is wired: the bridge * transport is created first so the `sendToServer` callback always has a * stable target (buffering frames until the server connects), the native * connection is started, the server is connected, and only then is the * handshake awaited. */ static connectBridge(server: McpServer_2, onNotification?: NativeMcpNotificationListener, onSampling?: NativeMcpSamplingResponder, onElicitation?: NativeMcpElicitationResponder, options?: NativeMcpCapabilityOptions, connectTimeoutMs?: number): Promise; /** * 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 — like * {@link connectBridge} — it relays JSON-RPC frames over the SAME napi bridge * surface, but against the GIVEN transport rather than an in-process * `McpServer`. 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; /** * 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`). With no timeout the wait is unbounded, matching the bare * `mcpBridgeAwaitInitialized` behavior. 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(): Promise; /** * 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, meta?: Record, options?: { timeoutMs?: number; resetTimeoutOnProgress?: boolean; onProgress?: NativeMcpProgressListener; signal?: AbortSignal; }): Promise; /** * 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; /** Reads the resource identified by `uri`, preserving arbitrary fields. */ readResource(uri: string): Promise; /** * 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, options?: { timeoutMs?: number; }): Promise; /** * 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): Promise; /** * 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, meta?: Record, task?: Record, options?: { timeoutMs?: number; }): Promise; /** Fetches a task's lifecycle status/metadata (`tasks/get`). */ getTask(taskId: string): Promise; /** * Retrieves a completed task's payload (`tasks/result`) — the original * call's result. */ getTaskResult(taskId: string): Promise; /** Requests cancellation of a task (`tasks/cancel`), returning the updated task. */ cancelTask(taskId: string): Promise; /** * Lists the server's known tasks (`tasks/list`), following the optional * pagination `cursor`. */ listTasks(cursor?: string): Promise; /** * 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; 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; /** 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; /** * 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; }; export declare function nativeProcessorRunEnv(): NativeProcessorRunEnv; 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; } export declare type NotificationHook = Hook; /** * Notification hook types - fires when the CLI shows a notification (permission, elicitation, completion) */ export declare interface NotificationHookInput extends BaseHookInput { message: string; title?: string; notificationType: string; } export declare interface NotificationHookOutput { additionalContext?: string; } declare interface OAuthClientInformation extends Record { 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 { 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; clientInformation(): OAuthClientInformationMixed | undefined | Promise; saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise; tokens(): OAuthTokens | undefined | Promise; saveTokens(tokens: OAuthTokens): void | Promise; redirectToAuthorization(authorizationUrl: URL): void | Promise; saveCodeVerifier(codeVerifier: string): void | Promise; codeVerifier(): string | Promise; addClientAuthentication?: AddClientAuthentication; validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; invalidateCredentials?(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): void | Promise; prepareTokenRequest?(scope?: string): URLSearchParams | Promise | undefined; saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise; discoveryState?(): OAuthDiscoveryState | undefined | Promise; } declare interface OAuthDiscoveryState extends OAuthServerInfo { resourceMetadataUrl?: string; } declare interface OAuthMetadata extends Record { 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; /** * 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; /** Tokens keyed by MCP server name. */ mcpServerTokens: Record; /** 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; /** 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; /** * Mirrors the namespaced type surface of the OpenAI SDK's top-level `OpenAI` * export that the runtime consumes (e.g. `OpenAI.Chat.Completions.*`, * `OpenAI.Responses.Response`, `OpenAI.ChatCompletion`). */ declare namespace OpenAI { import ChatCompletion = ChatCompletionsNs.ChatCompletion; import Responses = ResponsesNs.Responses; namespace Chat { import Completions = ChatCompletionsNs; } } /** 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; /** 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; } /** Schema for the `OptionsUpdateAdditionalContentExclusionPolicy` type. */ declare interface OptionsUpdateAdditionalContentExclusionPolicy { last_updated_at: unknown; rules: OptionsUpdateAdditionalContentExclusionPolicyRule[]; /** Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration. */ scope: OptionsUpdateAdditionalContentExclusionPolicyScope; [key: string]: unknown; } /** Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRule` type. */ declare interface OptionsUpdateAdditionalContentExclusionPolicyRule { ifAnyMatch?: string[]; ifNoneMatch?: string[]; paths: string[]; /** Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` type. */ source: OptionsUpdateAdditionalContentExclusionPolicyRuleSource; [key: string]: unknown; } /** Schema for the `OptionsUpdateAdditionalContentExclusionPolicyRuleSource` 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"; /** * Returns hooks in policy-first execution order. Policy hooks must observe * input before non-policy hooks and may produce terminal decisions that prevent * non-policy hooks from seeing sensitive data. */ export declare function orderPolicyHooksFirst(hooks: readonly THook[]): THook[]; /** * 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; /** 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; } /** 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. */ 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[]; /** * Check if a path is within any of the allowed directories */ isPathWithinAllowedDirectories(pathToCheck: string): Promise; /** * 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; /** * 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; /** * Add additional directories to the allowed list */ addDirectory(dir: string): Promise; } /** * 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; readonly toolCallId?: 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"; } /** Schema for the `PendingPermissionRequest` type. */ 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) => void, emit: (type: string, data: Record) => 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(permissionRequest: PermissionRequest_2, promptRequest: PermissionPromptRequest_2): Promise; /** Emit a user input request event and return a promise that resolves when responded to. */ requestUserInput(request: UserInputRequest): Promise; /** 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; requestElicitation(request: ElicitRequestParams, elicitationSource: string): Promise; /** Respond to a pending elicitation request by its ID. */ respondToElicitation(requestId: string, response: ElicitResult): void; /** * Try to respond to a pending elicitation request by its ID. * Returns true if the request was found and resolved, false if already resolved. */ tryRespondToElicitation(requestId: string, response: ElicitResult): boolean; /** Emit a sampling request event and return a promise that resolves when responded to. */ requestSampling(serverName: string, mcpRequestId: string | number, request: CreateMessageRequestParams): Promise; /** * 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, reason?: McpOAuthRequestReason): Promise; 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 | 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 | undefined): boolean; /** Emit an external tool request event and return a promise that resolves when responded to. */ requestExternalTool(request: ExternalToolRequest): Promise; /** 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; /** * 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; /** 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, 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; /** * 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; }; /** 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; /** * 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; /** * 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; } /** Schema for the `PermissionApproved` type. */ declare interface PermissionApproved { /** The permission request was approved */ kind: "approved"; } /** Schema for the `PermissionApprovedForLocation` type. */ 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; } /** Schema for the `PermissionApprovedForSession` type. */ 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"; } /** Schema for the `PermissionCancelled` type. */ 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; /** Schema for the `PermissionDecisionApproved` type. */ declare interface PermissionDecisionApproved { /** The permission request was approved */ kind: "approved"; } /** Schema for the `PermissionDecisionApprovedForLocation` type. */ 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; } /** Schema for the `PermissionDecisionApprovedForSession` type. */ 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"; } /** Schema for the `PermissionDecisionApproveForLocation` type. */ 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; /** Schema for the `PermissionDecisionApproveForLocationApprovalCommands` type. */ declare interface PermissionDecisionApproveForLocationApprovalCommands { /** Command identifiers covered by this approval. */ commandIdentifiers: string[]; /** Approval scoped to specific command identifiers. */ kind: "commands"; } /** Schema for the `PermissionDecisionApproveForLocationApprovalCustomTool` type. */ declare interface PermissionDecisionApproveForLocationApprovalCustomTool { /** Approval covering a custom tool. */ kind: "custom-tool"; /** Custom tool name. */ toolName: string; } /** Schema for the `PermissionDecisionApproveForLocationApprovalExtensionManagement` type. */ 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; } /** Schema for the `PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess` type. */ declare interface PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess { /** Extension name. */ extensionName: string; /** Approval covering an extension's request to access a permission-gated capability. */ kind: "extension-permission-access"; } /** Schema for the `PermissionDecisionApproveForLocationApprovalMcp` type. */ 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; } /** Schema for the `PermissionDecisionApproveForLocationApprovalMcpSampling` type. */ declare interface PermissionDecisionApproveForLocationApprovalMcpSampling { /** Approval covering MCP sampling requests for a server. */ kind: "mcp-sampling"; /** MCP server name. */ serverName: string; } /** Schema for the `PermissionDecisionApproveForLocationApprovalMemory` type. */ declare interface PermissionDecisionApproveForLocationApprovalMemory { /** Approval covering writes to long-term memory. */ kind: "memory"; } /** Schema for the `PermissionDecisionApproveForLocationApprovalRead` type. */ declare interface PermissionDecisionApproveForLocationApprovalRead { /** Approval covering read-only filesystem operations. */ kind: "read"; } /** Schema for the `PermissionDecisionApproveForLocationApprovalWrite` type. */ declare interface PermissionDecisionApproveForLocationApprovalWrite { /** Approval covering filesystem write operations. */ kind: "write"; } /** Schema for the `PermissionDecisionApproveForSession` type. */ 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; /** Schema for the `PermissionDecisionApproveForSessionApprovalCommands` type. */ declare interface PermissionDecisionApproveForSessionApprovalCommands { /** Command identifiers covered by this approval. */ commandIdentifiers: string[]; /** Approval scoped to specific command identifiers. */ kind: "commands"; } /** Schema for the `PermissionDecisionApproveForSessionApprovalCustomTool` type. */ declare interface PermissionDecisionApproveForSessionApprovalCustomTool { /** Approval covering a custom tool. */ kind: "custom-tool"; /** Custom tool name. */ toolName: string; } /** Schema for the `PermissionDecisionApproveForSessionApprovalExtensionManagement` type. */ 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; } /** Schema for the `PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess` type. */ declare interface PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess { /** Extension name. */ extensionName: string; /** Approval covering an extension's request to access a permission-gated capability. */ kind: "extension-permission-access"; } /** Schema for the `PermissionDecisionApproveForSessionApprovalMcp` type. */ 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; } /** Schema for the `PermissionDecisionApproveForSessionApprovalMcpSampling` type. */ declare interface PermissionDecisionApproveForSessionApprovalMcpSampling { /** Approval covering MCP sampling requests for a server. */ kind: "mcp-sampling"; /** MCP server name. */ serverName: string; } /** Schema for the `PermissionDecisionApproveForSessionApprovalMemory` type. */ declare interface PermissionDecisionApproveForSessionApprovalMemory { /** Approval covering writes to long-term memory. */ kind: "memory"; } /** Schema for the `PermissionDecisionApproveForSessionApprovalRead` type. */ declare interface PermissionDecisionApproveForSessionApprovalRead { /** Approval covering read-only filesystem operations. */ kind: "read"; } /** Schema for the `PermissionDecisionApproveForSessionApprovalWrite` type. */ declare interface PermissionDecisionApproveForSessionApprovalWrite { /** Approval covering filesystem write operations. */ kind: "write"; } /** Schema for the `PermissionDecisionApproveOnce` type. */ declare interface PermissionDecisionApproveOnce { /** Approve this single request only */ kind: "approve-once"; } /** Schema for the `PermissionDecisionApprovePermanently` type. */ declare interface PermissionDecisionApprovePermanently { /** URL domain to approve permanently */ domain: string; /** Approve and persist across sessions (URL prompts only) */ kind: "approve-permanently"; } /** Schema for the `PermissionDecisionCancelled` type. */ 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; } /** Schema for the `PermissionDecisionDeniedByContentExclusionPolicy` type. */ 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; } /** Schema for the `PermissionDecisionDeniedByPermissionRequestHook` type. */ 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; } /** Schema for the `PermissionDecisionDeniedByRules` type. */ declare interface PermissionDecisionDeniedByRules { /** Denied because approval rules explicitly blocked it */ kind: "denied-by-rules"; /** Rules that denied the request */ rules: PermissionRule_2[]; } /** Schema for the `PermissionDecisionDeniedInteractivelyByUser` type. */ 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"; } /** Schema for the `PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. */ 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"; } /** Schema for the `PermissionDecisionReject` type. */ 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; } /** Schema for the `PermissionDecisionUserNotAvailable` type. */ declare interface PermissionDecisionUserNotAvailable { /** No user is available to confirm the request */ kind: "user-not-available"; } /** Schema for the `PermissionDeniedByContentExclusionPolicy` type. */ 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; } /** Schema for the `PermissionDeniedByPermissionRequestHook` type. */ 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; } /** Schema for the `PermissionDeniedByRules` type. */ declare interface PermissionDeniedByRules { /** Denied because approval rules explicitly blocked it */ kind: "denied-by-rules"; /** Rules that denied the request */ rules: PermissionRule[]; } /** Schema for the `PermissionDeniedInteractivelyByUser` type. */ 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"; } /** Schema for the `PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser` type. */ 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 { /** 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; /** 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 { /** 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 { /** 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 { /** 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; /** 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; /** 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; /** 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 { /** 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 { /** Human-readable description of why the URL is being accessed */ intention: string; /** Prompt kind discriminator */ kind: "url"; /** Tool call ID that triggered this permission request */ toolCallId?: string; /** URL to be fetched */ url: string; } /** File write permission prompt */ declare interface PermissionPromptRequestWrite { /** 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 | 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_2 | 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; } export declare type PermissionRequestHook = Hook; /** Hook confirmation permission request */ declare interface PermissionRequestHook_2 { /** 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; } /** /** * PermissionRequest hook types - fires when a tool-level permission dialog is about to be shown */ export declare interface PermissionRequestHookInput extends BaseHookInput { hookName: "permissionRequest"; toolName: string; toolInput: unknown; permissionSuggestions: Array<{ kind: string; [key: string]: unknown; }>; } export declare interface PermissionRequestHookOutput { behavior?: "allow" | "deny"; message?: string; interrupt?: boolean; } /** 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; } | { readonly kind: "approved-for-location"; readonly approval: Extract; readonly locationKey: string; } | { readonly kind: "cancelled"; readonly reason?: string; } | { readonly kind: "denied-by-rules"; rules: ReadonlyArray; } | { 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; } /** Schema for the `PermissionRequestShellCommand` type. */ declare interface PermissionRequestShellCommand { /** Command identifier (e.g., executable name) */ identifier: string; /** Whether this command is read-only (no side effects) */ readOnly: boolean; } /** Schema for the `PermissionRequestShellPossibleUrl` type. */ 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"; /** 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; /** 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; }; /** Schema for the `PermissionRule` type. */ 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; } /** Schema for the `PermissionRule` type. */ 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[]; } /** Permissions change details carrying the aggregate allow-all boolean transition. */ declare interface PermissionsChangedData { /** Aggregate allow-all flag after the change */ allowAllPermissions: boolean; /** Aggregate allow-all flag before the change */ previousAllowAllPermissions: boolean; } /** Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all boolean 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 boolean 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; }; /** Schema for the `PermissionsConfigureAdditionalContentExclusionPolicy` type. */ declare interface PermissionsConfigureAdditionalContentExclusionPolicy { last_updated_at: unknown; rules: PermissionsConfigureAdditionalContentExclusionPolicyRule[]; /** Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` enumeration. */ scope: PermissionsConfigureAdditionalContentExclusionPolicyScope; [key: string]: unknown; } /** Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRule` type. */ declare interface PermissionsConfigureAdditionalContentExclusionPolicyRule { ifAnyMatch?: string[]; ifNoneMatch?: string[]; paths: string[]; /** Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` type. */ source: PermissionsConfigureAdditionalContentExclusionPolicyRuleSource; [key: string]: unknown; } /** Schema for the `PermissionsConfigureAdditionalContentExclusionPolicyRuleSource` 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; denied: ReadonlyArray; }; pathManager?: PathManager; urlManager?: UrlManager; }) => void; resetSessionToolApprovals: () => void; setApproveAllToolPermissionRequests: (value: boolean, source?: AllowAllSource) => void; /** Returns the current state of the approve-all-tool flag for this service. */ getApproveAllToolPermissionRequests: () => boolean; addApprovedRules: (newRules: ReadonlyArray) => void; removeApprovedRules: (rulesToRemove: ReadonlyArray) => void; /** Add rules that came from location permissions (can be removed separately). */ addLocationApprovedRules: (newRules: ReadonlyArray) => 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; }; /** 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; /** Schema for the `PermissionsLocationsAddToolApprovalDetailsCommands` type. */ declare interface PermissionsLocationsAddToolApprovalDetailsCommands { /** Command identifiers covered by this approval. */ commandIdentifiers: string[]; /** Approval scoped to specific command identifiers. */ kind: "commands"; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsCustomTool` type. */ declare interface PermissionsLocationsAddToolApprovalDetailsCustomTool { /** Approval covering a custom tool. */ kind: "custom-tool"; /** Custom tool name. */ toolName: string; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionManagement` type. */ 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; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess` type. */ declare interface PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess { /** Extension name. */ extensionName: string; /** Approval covering an extension's request to access a permission-gated capability. */ kind: "extension-permission-access"; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsMcp` type. */ 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; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsMcpSampling` type. */ declare interface PermissionsLocationsAddToolApprovalDetailsMcpSampling { /** Approval covering MCP sampling requests for a server. */ kind: "mcp-sampling"; /** MCP server name. */ serverName: string; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsMemory` type. */ declare interface PermissionsLocationsAddToolApprovalDetailsMemory { /** Approval covering writes to long-term memory. */ kind: "memory"; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsRead` type. */ declare interface PermissionsLocationsAddToolApprovalDetailsRead { /** Approval covering read-only filesystem operations. */ kind: "read"; } /** Schema for the `PermissionsLocationsAddToolApprovalDetailsWrite` type. */ 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; } /** Whether to enable full allow-all permissions for the session. */ declare interface PermissionsSetAllowAllRequest { /** Whether to enable full allow-all permissions */ enabled: boolean; /** 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; /** 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; } /** Schema for the `Plugin` type. */ 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 to register. */ 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; } /** 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; 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; } /** Schema for the `PluginUpdateAllEntry` type. */ 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; } /** Batch of spawn events plus a cursor for follow-up polls. */ declare interface PollSpawnedSessionsResult { /** Opaque cursor to pass back to receive only events after this batch. */ cursor: string; /** Spawn events emitted since the supplied cursor. */ events: SessionsPollSpawnedSessionsEvent[]; } /** * This is just a type to warn that there's a good chance it's not a real path, because * it was _very_ heuristically parsed out of a command. */ declare type PossiblePath = string; /** * A possible URL that was heuristically parsed from a command. */ declare type PossibleUrl = { readonly url: string; }; declare type PostEditHookContext = { /** * The path of the file that was edited. */ readonly path: string; /** * Whether the edit was successful. */ readonly editWasSuccessful: boolean; } & CommonHookContext; declare type PostEditHookResult = { /** * A hint to be given to the agent during the next turn about the edit * it made, or about something done to the file during the hook's execution. */ postEditHint?: string; } | void; 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; declare type PostResultHookContext = { /** * The current commit hash. */ postResultCommitHash: string; } & CommonHookContext; declare type PostResultHookResult = { /** * A message to be given to the agent about the result of its work. This will be given to the agent * as a start to performing another round of work on the same problem. If no message is provided, * work on the problem will not continue. */ nextIterationMessage: string | undefined; } | void; 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; /** * The client handling the request. Used when post-tool processing needs to * normalize outputs for a client-specific wire format. */ readonly client?: Pick; }; export declare type PostToolUseFailureHook = Hook; export declare interface PostToolUseFailureHookInput extends BaseHookInput { toolName: string; toolArgs: unknown; error: string; } export declare interface PostToolUseFailureHookOutput { additionalContext?: string; } export declare type PostToolUseHook = Hook; /** * Post-tool use hook types * * Multiple hooks may be registered. They are invoked in registration order * (sequentially with `await` between each). When more than one hook returns * `additionalContext`, the strings are joined with `\n\n` in registration * order, capped at {@link MAX_POST_TOOL_USE_CONTEXT_LENGTH}, wrapped in a * labelled block, and appended to `toolResult.textResultForLlm` so the LLM * sees them on its next turn. */ export declare interface PostToolUseHookInput extends BaseHookInput { toolName: string; toolArgs: unknown; toolResult: ToolResultExpanded; } export declare interface PostToolUseHookOutput { modifiedResult?: ToolResultExpanded; additionalContext?: string; suppressOutput?: boolean; /** * If "block", the tool result is blocked. The original result payload should * be scrubbed and replaced with the reason text. */ decision?: HookBlockDecision; /** Human-readable explanation for why the tool result was blocked. */ reason?: string; } declare type PreCommitHookContext = { /** Commit messages from all report_progress tool calls in this turn, keyed by tool call ID. */ commitMessagesByCallId: ReadonlyMap; } & CommonHookContext; declare type PreCommitHookResult = { /** Whether or not the commit should proceed. */ proceedWithCommit: boolean; /** The reason for stopping the commit, if applicable. Will be provided to the agent during the next turn. */ reason?: string; /** If set, replaces commit messages for the matching report_progress tool call IDs. */ redactedCommitMessagesByCallId?: ReadonlyMap; }; export declare type PreCompactHook = Hook; /** * Pre-compact hook types - fires before context compaction begins */ export declare interface PreCompactHookInput extends BaseHookInput { transcriptPath: string; trigger: "manual" | "auto"; customInstructions: string; } export declare type PreCompactHookOutput = Record; /** Call the Auto Intent proxy (`POST /models/session/intent`) for the given prompt. */ export declare function predictAutoIntent(args: PredictIntentArgs): Promise; declare type PredictIntentArgs = AcquireArgs & { sessionToken: string; prompt: string; availableModels: string[]; hasImage: boolean; }; declare type PreEditsHookContext = { /** * The paths of files the agent is about to edit. */ readonly pathsBeingEdited: Set; } & CommonHookContext; export declare type PreMcpToolCallHook = Hook; /** * Pre-MCP tool call hook types */ export declare interface PreMcpToolCallHookInput extends BaseHookInput { toolCallId?: string; serverName: string; toolName: string; arguments: unknown; _meta?: Record; } export declare interface PreMcpToolCallHookOutput { /** * Hook-controlled metadata to use for the outgoing MCP request, before * runtime-owned trace metadata is added: * - omitted: preserve the current request `_meta` * - object: use this object as request `_meta` * - null: omit `_meta` */ metaToUse?: Record | null; } /** * Validates and normalizes the arguments of a client-executed `tool_search_call` * into the `{ pattern, limit }` shape. Throws when the arguments are invalid. */ declare function prepareClientToolSearchInput(args: unknown): { pattern: string; limit: number; }; declare type PrePRDescriptionHookContext = CommonHookContext & { /** * The staged pull request description that hooks can inspect or modify. */ readonly prDescription: 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[]; /** * Disable tool definitions for the current request only. Use this instead * of mutating `toolDefinitions` when a processor needs a no-tools model call. */ readonly disableTools?: () => void; /** * Append a message to the outbound model request without adding it to the * session conversation history. */ readonly addRequestMessage?: (message: ChatCompletionMessageParam) => void; /** * Append a hidden message to the in-flight model-loop history without * emitting a session message event. Future model requests in the same tool * loop will include it, but the durable session transcript will not. */ readonly addHiddenHistoryMessage?: (message: ChatCompletionMessageParam) => void; /** * Omit matching messages from the outbound model request without removing * them from the session conversation history. */ readonly omitRequestMessages?: (predicate: (message: ChatCompletionMessageParam) => boolean) => void; /** * Information about the model being called. */ readonly modelInfo: CompletionWithToolsModel; /** * Additional headers to send with the request. If adding additional headers * then simply add to this object. */ readonly additionalRequestHeaders: Record; /** * The current {@link GetCompletionWithToolsOptions} */ readonly getCompletionWithToolsOptions: GetCompletionWithToolsOptions | undefined; /** Opaque partition key for native token-count caches. */ readonly tokenCacheScope?: string; /** Whether stored assistant output-token counts are authoritative for this request. */ readonly useStoredOutputTokens?: boolean; /** * 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_2[]; }; /** * 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; }; /** * 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; export declare type PreToolUseHook = Hook; /** * Builds the model-visible denial message for a `preToolUse` hook that errored * (fail-closed). Includes the hook's {@link Hook.source} label when one is set * so a brittle plugin/hook can be identified. The source is always config-derived * (file paths, plugin names, admin policy labels, or hardcoded strings) and never * influenced by tool arguments or hook output. The native implementation still * sanitizes control chars / quotes and middle-truncates long paths to 200 chars. * * @internal Not intended for use by SDK consumers. */ export declare function preToolUseHookErroredMessage(hook: { readonly source?: string; }): string; /** * Pre-tool use hook types */ export declare interface PreToolUseHookInput extends BaseHookInput { toolName: string; toolArgs: unknown; } export declare interface PreToolUseHookOutput { permissionDecision?: "allow" | "deny" | "ask"; permissionDecisionReason?: string; modifiedArgs?: unknown; additionalContext?: string; suppressOutput?: boolean; } /** * Processor that executes preToolUse hooks and can deny tool execution or modify arguments. * Returns denied results for tools that hooks block. * Mutates tool call arguments in place when hooks return modifiedArgs. */ export declare class PreToolUseHooksProcessor implements IPreToolsExecutionProcessor { private readonly hooks; private readonly workingDir; private readonly sessionId; private readonly requestHookPermission?; private readonly emitter?; private readonly onToolCallAllowed?; private readonly onAdditionalContext?; private readonly onBatchStart?; constructor(hooks: QueryHooks | undefined, workingDir: string, sessionId: string, requestHookPermission?: RequestHookPermissionFn | undefined, emitter?: HookEventEmitter | undefined, onToolCallAllowed?: ((toolCallId: string) => void) | undefined, onAdditionalContext?: ((toolCallId: string, context: string) => void) | undefined, onBatchStart?: (() => void) | undefined); toJSON(): string; preToolsExecution(context: PreToolsExecutionContext): Promise | void>; } declare interface PrimitiveArrayAnyOfSchema extends Record { type: "array"; title?: string; description?: string; minItems?: number; maxItems?: number; items: { anyOf: Array<{ const: string; title: string; }>; }; default?: string[]; } declare interface PrimitiveArrayEnumSchema extends Record { type: "array"; title?: string; description?: string; minItems?: number; maxItems?: number; items: { type: "string"; enum: string[]; }; default?: string[]; } declare interface PrimitiveBooleanSchema extends Record { type: "boolean"; title?: string; description?: string; default?: boolean; } declare interface PrimitiveNumberSchema extends Record { 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 { type: "string"; title?: string; description?: string; enum: string[]; enumNames?: string[]; default?: string; } declare interface PrimitiveStringOneOfSchema extends Record { type: "string"; title?: string; description?: string; oneOf: Array<{ const: string; title: string; }>; default?: string; } declare interface PrimitiveStringSchema extends Record { type: "string"; title?: string; description?: string; minLength?: number; maxLength?: number; format?: "email" | "uri" | "date" | "date-time"; default?: string; } /** * Processes a tool result, writing it to a file if it exceeds the size threshold. */ declare function processLargeOutput(result: ToolResultExpanded, options?: LargeOutputOptions): Promise; /** * 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; /** 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; /** Custom HTTP headers to include in all outbound requests to the provider. */ headers?: Record; /** * 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 ` 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 ` 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; /** 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; /** 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_2; /** Provider-local model id, unique within its provider. The session-wide selection id (shown in the model list and passed to switchTo) is the provider-qualified `provider/id`. */ id: string; /** Maximum context window tokens for the model. */ maxContextWindowTokens?: number; /** Maximum output tokens for the model. */ maxOutputTokens?: number; /** Maximum prompt/input tokens for the model. */ maxPromptTokens?: number; /** Well-known base model id used for behavior/capability/config lookup. Defaults to `id`. */ modelId?: string; /** Display name for model pickers. Defaults to the provider-qualified selection id (`provider/id`). */ name?: string; /** Name of the NamedProviderConfig that serves this model. */ provider: string; /** The model name sent to the provider API for inference. Defaults to `id`. */ wireModel?: string; } /** * 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; } /** 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 ` 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; } /** Schema for the `PushAttachment` type. */ 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; } /** * Hook system with arrays of specific hook callbacks */ export declare interface QueryHooks { preToolUse?: PreToolUseHook[]; preMcpToolCall?: PreMcpToolCallHook[]; postToolUse?: PostToolUseHook[]; postToolUseFailure?: PostToolUseFailureHook[]; userPromptSubmitted?: UserPromptSubmittedHook[]; sessionStart?: SessionStartHook[]; sessionEnd?: SessionEndHook[]; errorOccurred?: ErrorOccurredHook[]; agentStop?: AgentStopHook[]; subagentStop?: SubagentStopHook[]; subagentStart?: SubagentStartHook[]; preCompact?: PreCompactHook[]; permissionRequest?: PermissionRequestHook[]; notification?: NotificationHook[]; } /** Schema for the `QueuedCommandHandled` type. */ 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; } /** Schema for the `QueuedCommandNotHandled` type. */ 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 | 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 queued model change to be applied after the current turn. */ export declare interface QueuedModelChangeItem { kind: "model_change"; model: string; reasoningEffort?: ReasoningEffort_3; reasoningSummary?: ReasoningSummary; modelCapabilitiesOverrides?: ModelCapabilitiesOverride; contextTier?: ContextTier_3; /** * Optional completion callback used when a caller needs to wait for the * deferred model change to be applied after the current turn. */ onApplied?: () => void; } /** * 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"; } /** Schema for the `QueuePendingItems` type. */ 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. */ flush(): Promise; /** Alias for Disposable interface */ dispose(): Promise; 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; /** * 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; /** * The pay-as-you-go (PAYGO) overage budget cap, denominated in AI credits * (1 credit = $0.01), so the client can show how much of the additional-usage * budget remains. * * Value semantics (mirrors the Rust source of truth in `src/runtime/src/quota.rs`): * - A finite positive number is the budget cap. * - `Infinity` when the budget is unlimited (CAPI emits `ovEnt=Infinity`); it * is propagated unchanged rather than collapsed to `undefined`. * - `undefined` when CAPI omits the field or it is empty/unparseable. * * Because an unlimited budget surfaces as `Infinity`, consumers must guard * with `Number.isFinite()` before rendering or dividing (see * `hasAdditionalUsageBudget`) so an unlimited budget never renders as * "Infinity AIC". */ overageEntitlement?: number; }; declare type QuotaSnapshotsByType = Record; declare function readDirectoryListing(directoryPath: string, softMaxBytes: number | undefined, hardMaxBytes: number, abortSignal?: AbortSignal): Promise; 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; }; /** * **gpt-5 and o-series models only** * * Configuration options for * [reasoning models](https://platform.openai.com/docs/guides/reasoning). */ declare interface Reasoning { /** * Constrains effort on reasoning for * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning * effort can result in faster responses and fewer tokens used on reasoning in a * response. */ effort?: ReasoningEffort | null; /** * @deprecated **Deprecated:** use `summary` instead. * * A summary of the reasoning performed by the model. This can be useful for * debugging and understanding the model's reasoning process. One of `auto`, * `concise`, or `detailed`. */ generate_summary?: "auto" | "concise" | "detailed" | null; /** * A summary of the reasoning performed by the model. This can be useful for * debugging and understanding the model's reasoning process. One of `auto`, * `concise`, or `detailed`. */ summary?: "auto" | "concise" | "detailed" | null; } /** * Well-known reasoning effort levels for models that support reasoning configuration. * Custom providers may accept additional values beyond these. */ declare const REASONING_EFFORT_LEVELS: readonly ["none", "low", "medium", "high", "xhigh", "max"]; declare const REASONING_SUMMARY_LEVELS: readonly ["none", "concise", "detailed"]; /** * Constrains effort on reasoning for * [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently * supported values are `minimal`, `low`, `medium`, and `high`. Reducing reasoning * effort can result in faster responses and fewer tokens used on reasoning in a * response. */ declare type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; /** * 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_2 = string; /** * Reasoning effort level to request. Well-known values are listed in * {@link REASONING_EFFORT_LEVELS}; custom providers may accept additional values. */ declare type ReasoningEffort_3 = KnownReasoningEffort | (string & {}); /** Re-export ReasoningEffortOption as ReasoningEffortLevel for backwards compatibility */ declare type ReasoningEffortLevel = ReasoningEffort_3; 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 ReasoningSummary = (typeof REASONING_SUMMARY_LEVELS)[number]; /** Reasoning summary mode used for model calls, if applicable (e.g. "none", "concise", "detailed") */ declare type ReasoningSummary_2 = "none" | "concise" | "detailed"; /** Reasoning summary mode to request for supported model clients */ declare type ReasoningSummary_3 = "none" | "concise" | "detailed"; declare type RefreshArgs = AcquireArgs & { existingToken: string; }; /** Refresh an existing session token via `POST /models/session` with the token in the header. */ export declare function refreshAutoModeSession(args: RefreshArgs): Promise; /** * 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 the full interactive OAuth flow to the consumer; when no interest is registered the runtime installs a browserless fallback that silently reuses cached tokens). 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; } /** * Registers a sessionFs-based temp file for cleanup tracking. * Use this when creating temp files outside of processLargeOutput (e.g., from StreamingOutputBuffer). */ declare function registerTempFile(sessionFs: SessionFs, filePath: string): void; declare type RejectedToolResult = ToolResultExpanded & { resultType: "rejected"; }; declare type RejectedToolResult_2 = 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; }; } /** 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; } | { 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; /** 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; } /** 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"; export declare function replayNativeLogs(logger: RunnerLogger, logs: readonly NativeProcessorLogMessage[]): void; declare const reply_to_comment: (config: ToolConfig, logger: RunnerLogger) => Tool_2; declare const REPLY_TO_COMMENT_TOOL_NAME = "reply_to_comment"; declare type ReplyToCommentInput = z_2.infer; declare const replyToCommentInputSchema: z_2.ZodObject<{ reply: z_2.ZodString; comment_id: z_2.ZodUnion<[z_2.ZodNumber, z_2.ZodString]>; }, "strip", z_2.ZodTypeAny, { comment_id: string | number; reply: string; }, { comment_id: string | number; reply: string; }>; /** * Immutable snapshot of the repository's diff state at a point in time. * * Eagerly computes git diff data and per-file range hashes during `create()`. * All public methods are synchronous. * */ declare class RepoChangeSet { private readonly files; private constructor(); /** * Creates a fully-initialized RepoChangeSet. * Stages all changes, retrieves changed paths (including deletions) and diff ranges, * then hashes each changed file's contents. * * Uses `getChangedPaths()` as the authoritative file list so that deleted files * and pure-deletion edits are included. `getDiffRanges()` provides hunk-level * line ranges where available (it intentionally omits deleted files and * deletion-only hunks). */ static create(git: GitHandler, repoLocation: string, baseCommit: string, abortSignal?: AbortSignal): Promise; /** Full diff with hunk line ranges (needed for CodeQL diff-informed analysis and alert filtering). */ getFileRanges(): FileRange[]; /** Set of changed file paths. */ getChangedFiles(): Set; /** * Returns the set of files that changed between a previous change set and this one. * Includes files that are new, modified (different hash), or deleted (in previous but not in current). */ getChangedFilesSince(previous: RepoChangeSet): Set; } declare type RepoHostType = "github" | "ado"; declare const report_progress: (config: ToolConfig, settings: RuntimeSettings, logger: RunnerLogger, exec: RunnerExec) => Tool_2; declare const REPORT_PROGRESS_ONLY_PUSH_FEATURE_FLAG = "sweagentd_report_progress_only_push"; declare const REPORT_PROGRESS_TOOL_NAME = "report_progress"; declare type ReportProgressInput = z_2.infer; declare const reportProgressInputSchema: z_2.ZodObject<{ commitMessage: z_2.ZodString; prDescription: z_2.ZodString; }, "strip", z_2.ZodTypeAny, { prDescription: string; commitMessage: string; }, { prDescription: string; commitMessage: string; }>; declare const reportProgressLegacyToolDescription = "Report progress on the task. Call when you complete a meaningful unit of work. Commits and pushes changes that are pending in the repo, then updates the PR description.\n* Use only when you have meaningful progress to report (you need to update the plan in the checklist, you have code changes to commit, or you have completed a new item in the checklist)\n* Use markdown checklists to show progress (- [x] for completed items, - [ ] for pending items).\n* Keep the checklist structure as consistent as you can between updates, while still being accurate and useful.\n* Only include the checklist in the prDescription, DO NOT include any headers, a summary, or any other information besides the checklist.\n* If there are changes in the repo this tool will run `git add .`, `git commit -m `, and `git push`."; declare const reportProgressPushOnlyToolDescription = "Report progress on the task. Call when you complete a meaningful unit of work. Updates the PR description and shares progress for code already committed locally.\n* Use only when you have meaningful progress to report (you need to update the plan in the checklist, you have code progress to share, or you have completed a new item in the checklist)\n* Use markdown checklists to show progress (- [x] for completed items, - [ ] for pending items).\n* Keep the checklist structure as consistent as you can between updates, while still being accurate and useful.\n* Only include the checklist in the prDescription, DO NOT include any headers, a summary, or any other information besides the checklist."; /** * 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; 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; /** * Function type for requesting user input from the UI. * Returns a promise that resolves when the user responds. */ declare type RequestUserInputFn = (request: AskUserRequest) => Promise; declare type ResolveArgs = { authInfo: AuthInfo; integrationId: string; sessionId: string; logger: RunnerLogger; settings?: RuntimeSettings; }; /** * 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; /** * Best-effort auto-mode discount % (0–100) for {@link AcquireArgs.authInfo}: the live {@link manager} session value * when that session belongs to the requesting identity, else a one-shot cold `POST /models/session`. `undefined` when * auto-mode is unavailable (no CAPI URL or auth token; e.g. BYOK), there is no discount, or the acquire fails. The {@link manager} is * server-scoped and may hold a *different* account's session (e.g. a per-call `gitHubToken` override), so its warm * value is trusted only when {@link AutoModeSessionManager.isOwnedBy} confirms ownership — otherwise we resolve cold * so one account can't read another's discount (#10973). Intentionally uncached so the displayed discount stays * fresh; the cold path runs once per `models.list`, in parallel with the model-list fetch (no added serial latency). */ export declare function resolveAutoDiscountPercent(args: AcquireArgs & { manager?: AutoModeSessionManager; }): Promise; /** * 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; } /** * 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 enqueue for 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 enqueued message. */ readonly mode?: SessionMode; } /** * Resolve an ExP-backed feature flag. * * When `featureFlagService` is available, waits for the ExP-backed resolution. * Otherwise falls back to the static feature flag. */ export declare function resolveExpFlag(featureFlagService: IFeatureFlagService | undefined, expFlag: ExpFlagKey, featureFlag: FeatureFlag, featureFlags?: Readonly>>): Promise; /** * Resolves feature flag availability to boolean values based on user status and team membership. * * @param isStaff Whether the user is a staff member * @param isExperimental Whether experimental mode is enabled * @param isTeam Whether the current repository is considered a team repo (enabling "team" tier flags) * @param options Optional env/config/explicit overrides to apply after base resolution * @returns Feature flags with boolean values */ export declare function resolveFeatureFlags(isStaff: boolean, isExperimental: boolean, isTeam: boolean, options?: FeatureFlagResolutionOptions): FeatureFlags; /** * Resolves whether Anthropic's built-in server-side tool search should be used * instead of the client-side `tool_search_tool_regex` implementation. * * When enabled, the Anthropic API handles tool search via `server_tool_use` / * `tool_search_tool_result` blocks — no client-side tool execution is needed. * Controlled by the `TOOL_SEARCH_BUILTIN_ANTHROPIC` feature flag / ExP. */ declare function resolveIsBuiltinToolSearchEnabled(model: string, featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly>>): Promise; /** * Resolves whether OpenAI's client-executed tool search should be used instead * of the hosted server-side Responses tool search. * * When enabled, the runtime sends `{ type: "tool_search", execution: "client" }` * and services the resulting `tool_search_call` items itself instead of the * Responses API running the search. Controlled by the `TOOL_SEARCH_CLIENT_OPENAI` * feature flag. */ declare function resolveIsClientToolSearchEnabled(model: string, featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly>>): Promise; /** * Resolves whether tool search is enabled for the given model, checking * the general TOOL_SEARCH override flag plus the model-family-specific * ExP flags (TOOL_SEARCH_ANTHROPIC / TOOL_SEARCH_OPENAI). * * Shared between the main session (getToolsForExecution) and subagent * tool preparation (getToolsForTaskAgents in config.ts). */ declare function resolveIsToolSearchEnabled(model: string, featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly>>): Promise; export declare function resolveNoPlanningFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly>>): Promise; export declare function resolveNoViewLineNumbersFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly>>): Promise; /** * Resolves the `SKILLS_LIST_IN_SYSTEM_PROMPT` experiment, which moves the skills * list out of the skill tool definition and into the dynamic part of the system * prompt. Awaits the ExP assignment for `copilot_cli_skills_list_in_system_prompt`; * falls back to the static `SKILLS_LIST_IN_SYSTEM_PROMPT` feature flag when ExP * has no assignment. */ export declare function resolveSkillsListInSystemPromptFlag(featureFlagService: IFeatureFlagService | undefined, featureFlags?: Readonly>>): Promise; /** * 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; }; /** * JSON object response format. An older method of generating JSON responses. Using * `json_schema` is recommended for models that support it. Note that the model * will not generate JSON without a system or user message instructing it to do so. */ declare interface ResponseFormatJSONObject { /** * The type of response format being defined. Always `json_object`. */ type: "json_object"; } /** * JSON Schema response format. Used to generate structured JSON responses. Learn * more about * [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs). */ declare interface ResponseFormatJSONSchema { /** * Structured Outputs configuration options, including a JSON Schema. */ json_schema: ResponseFormatJSONSchema.JSONSchema; /** * The type of response format being defined. Always `json_schema`. */ type: "json_schema"; } declare namespace ResponseFormatJSONSchema { /** * Structured Outputs configuration options, including a JSON Schema. */ interface JSONSchema { /** * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores * and dashes, with a maximum length of 64. */ name: string; /** * A description of what the response format is for, used by the model to determine * how to respond in the format. */ description?: string; /** * The schema for the response format, described as a JSON Schema object. Learn how * to build JSON schemas [here](https://json-schema.org/). */ schema?: { [key: string]: unknown; }; /** * Whether to enable strict schema adherence when generating the output. If set to * true, the model will always follow the exact schema defined in the `schema` * field. Only a subset of JSON Schema is supported when `strict` is `true`. To * learn more, read the * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). */ strict?: boolean | null; } } /** * Default response format. Used to generate text responses. */ declare interface ResponseFormatText { /** * The type of response format being defined. Always `text`. */ type: "text"; } /** * A custom grammar for the model to follow when generating text. Learn more in the * [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars). */ declare interface ResponseFormatTextGrammar { /** * The custom grammar for the model to follow. */ grammar: string; /** * The type of response format being defined. Always `grammar`. */ type: "grammar"; } /** * Configure the model to generate valid Python code. See the * [custom grammars guide](https://platform.openai.com/docs/guides/custom-grammars) * for more details. */ declare interface ResponseFormatTextPython { /** * The type of response format being defined. Always `python`. */ type: "python"; } declare type ResponseLimitsEventState = "active" | "final" | "exhausted" | "blocked"; declare type ResponseLimitsExhaustedHandler = (status: ResponseLimitsStatus) => boolean | Promise; declare class ResponseLimitsPreRequestProcessor implements IPreRequestProcessor { private readonly getResponseLimits; private readonly getUsageMetrics; private readonly onLimitsStatus?; private readonly onLimitsExhausted?; private scope; constructor(getResponseLimits: () => SessionLimitsConfig_3 | undefined, getUsageMetrics: () => UsageMetrics, onLimitsStatus?: ((status: ResponseLimitsStatus, state: ResponseLimitsEventState) => void) | undefined, onLimitsExhausted?: ResponseLimitsExhaustedHandler | undefined, scope?: ResponseLimitsScope); forkForSession(): ResponseLimitsPreRequestProcessor; preRequest(context: PreRequestContext): AsyncGenerator; reconcileAfterUsage(): ResponseLimitsStatus | undefined; getCurrentStatus(): ResponseLimitsStatus | undefined; toJSON(): string; private applyRequestEffects; private getRequestEffects; private setRequestEffects; private clearRequestEffects; private getRequestKey; private markNewlyCrossedUsageThresholds; private getThresholdKey; private emitBlockedLimitsStatus; private emitReconciledLimitsStatus; } declare type ResponseLimitsRequestEffects = { readonly disableTools: boolean; readonly message: ChatCompletionUserMessageParam; readonly messagePersistence: "request" | "history"; }; declare type ResponseLimitsScope = { baseline: ResponseLimitsUsageBaseline; hasEmittedExhausted: boolean; lastReconciledStatusKey: string | undefined; lastBlockedRequestKey: string | undefined; emittedUsageThresholdKeys: Set; requestEffects: WeakMap>; }; 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; } declare interface ResponseLimitsUsageBaseline { readonly nanoAiu: number; } declare namespace Responses { export { ComputerTool, CustomTool, EasyInputMessage, FileSearchTool, FunctionTool, Response, ResponseAudioDeltaEvent, ResponseAudioDoneEvent, ResponseAudioTranscriptDeltaEvent, ResponseAudioTranscriptDoneEvent, ResponseCodeInterpreterCallCodeDeltaEvent, ResponseCodeInterpreterCallCodeDoneEvent, ResponseCodeInterpreterCallCompletedEvent, ResponseCodeInterpreterCallInProgressEvent, ResponseCodeInterpreterCallInterpretingEvent, ResponseCodeInterpreterToolCall, ResponseCompletedEvent, ResponseComputerToolCall, ResponseComputerToolCallOutputItem, ResponseComputerToolCallOutputScreenshot, ResponseContent, ResponseContentPartAddedEvent, ResponseContentPartDoneEvent, ResponseConversationParam, ResponseCreatedEvent, ResponseCustomToolCall, ResponseCustomToolCallInputDeltaEvent, ResponseCustomToolCallInputDoneEvent, ResponseCustomToolCallOutput, ResponseError, ResponseErrorEvent, ResponseFailedEvent, ResponseFileSearchCallCompletedEvent, ResponseFileSearchCallInProgressEvent, ResponseFileSearchCallSearchingEvent, ResponseFileSearchToolCall, ResponseFormatTextConfig, ResponseFormatTextJSONSchemaConfig, ResponseFunctionCallArgumentsDeltaEvent, ResponseFunctionCallArgumentsDoneEvent, ResponseFunctionToolCall, ResponseFunctionToolCallItem, ResponseFunctionToolCallOutputItem, ResponseFunctionWebSearch, ResponseImageGenCallCompletedEvent, ResponseImageGenCallGeneratingEvent, ResponseImageGenCallInProgressEvent, ResponseImageGenCallPartialImageEvent, ResponseInProgressEvent, ResponseIncludable, ResponseIncompleteEvent, ResponseInput, ResponseInputAudio, ResponseInputContent, ResponseInputFile, ResponseInputImage, ResponseInputItem, ResponseInputMessageContentList, ResponseInputMessageItem, ResponseInputText, ResponseItem, ResponseMcpCallArgumentsDeltaEvent, ResponseMcpCallArgumentsDoneEvent, ResponseMcpCallCompletedEvent, ResponseMcpCallFailedEvent, ResponseMcpCallInProgressEvent, ResponseMcpListToolsCompletedEvent, ResponseMcpListToolsFailedEvent, ResponseMcpListToolsInProgressEvent, ResponseOutputAudio, ResponseOutputItem, ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent, ResponseOutputMessage, ResponseOutputRefusal, ResponseOutputText, ResponseOutputTextAnnotationAddedEvent, ResponsePrompt, ResponseQueuedEvent, ResponseReasoningItem, ResponseReasoningSummaryPartAddedEvent, ResponseReasoningSummaryPartDoneEvent, ResponseReasoningSummaryTextDeltaEvent, ResponseReasoningSummaryTextDoneEvent, ResponseReasoningTextDeltaEvent, ResponseReasoningTextDoneEvent, ResponseRefusalDeltaEvent, ResponseRefusalDoneEvent, ResponseStatus, ResponseStreamEvent, ResponseTextConfig, ResponseTextDeltaEvent, ResponseTextDoneEvent, ResponseUsage, ResponseWebSearchCallCompletedEvent, ResponseWebSearchCallInProgressEvent, ResponseWebSearchCallSearchingEvent, Tool, ToolChoiceAllowed, ToolChoiceCustom, ToolChoiceFunction, ToolChoiceMcp, ToolChoiceOptions, ToolChoiceTypes, WebSearchPreviewTool, WebSearchTool, ResponseCreateParams, ResponseCreateParamsBase, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming, ResponseRetrieveParams, ResponseRetrieveParamsBase, ResponseRetrieveParamsNonStreaming, ResponseRetrieveParamsStreaming, }; } declare type ResponsesMessageStatus = "in_progress" | "completed" | "incomplete"; declare type ResponsesModel = (string & {}) | ChatModel | "o1-pro" | "o1-pro-2025-03-19" | "o3-pro" | "o3-pro-2025-06-10" | "o3-deep-research" | "o3-deep-research-2025-06-26" | "o4-mini-deep-research" | "o4-mini-deep-research-2025-06-26" | "computer-use-preview" | "computer-use-preview-2025-03-11"; /** * 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 `, `--continue`, single-session interactive startup) * where `cliSessionDefaults()` pinned `workingDirectory` to the * launching shell's incidental cwd. 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 ` 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_2; /** 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; } /** 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, preserving prior behavior. This is what virtually * all consumers (the `/model` picker, `--model` validation, custom-agent/SDK * selection) should use. * - `unfilteredModels`: the **whole** filtered list (picker-disabled models included), * used for utility-model selection (e.g. `findSmallModel` session naming). * `EXCLUDED_MODELS` and subscription-tier filtering still apply; 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 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 exit code */ exec(commandLine: string, args?: string[], options?: RunnerExecOptions, filteredCmdArgs?: string[]): Promise; /** * 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 exit code, stdout, and stderr */ execReturn(commandLine: string, args?: string[], options?: RunnerExecOptions, filteredCmdArgs?: string[]): Promise; } /** * 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; 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; } declare type RuntimeSettings = DeepPartial; /** * Indicates the safety level of the assessed script. * * There may some cases where a script cannot be assessed (e.g. unparseable), * in which case we bail with a failure. */ declare type SafetyAssessment = { readonly result: "failed"; /** * A human-readable reason why the safety assessment could not be completed. */ readonly reason: string; } | { readonly result: "completed"; readonly commands: ReadonlyArray; /** * Possible absolute file paths that the script might operate on, based on heuristic parsing. */ readonly possiblePaths: ReadonlyArray; /** * Possible URLs that the script might access, based on heuristic parsing. */ readonly possibleUrls: ReadonlyArray; /** * Indicates whether any command in the script has redirection to write to a file. */ readonly hasWriteFileRedirection: boolean; /** * Indicates whether a command can be approved for the rest of the running session. * * Simple commands like `git status` or `npm test` can be session approved * because their impact is predictable. Complex commands with substitutions, * variables, or side effects require per-invocation approval. * * Examples of session-approvable: `ls`, `git log`, `command1 && command2` * Examples requiring per-invocation: `rm -rf $DIR`, `find -exec` */ readonly canOfferSessionApproval: boolean; /** * Whether the script contains shell expansion patterns that could enable * remote code execution (e.g., ${var@P}, ${!var}, nested command substitution * inside parameter expansion). When true, the command should be unconditionally * blocked regardless of permission mode. */ readonly hasDangerousExpansion: boolean; /** * Optional warning message to display to the user (e.g., when parser is unavailable). * This should be shown in the permission dialog and/or timeline. */ 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; } 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; /** User-managed sandbox policy fragment merged into the auto-discovered base policy. */ userPolicy?: SandboxConfigUserPolicy; } declare type SandboxConfig_2 = { enabled: boolean; userPolicy?: StoredSandboxUserPolicy; } & Omit; /** 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; /** Hosts allowed in addition to the base policy. */ allowedHosts?: string[]; /** Hosts explicitly blocked. */ blockedHosts?: string[]; } /** macOS seatbelt-specific options. */ declare interface SandboxConfigUserPolicySeatbelt { /** Whether the macOS seatbelt profile may access the keychain. */ keychainAccess?: boolean; } declare type SandboxExperimentalPolicy = { seatbelt?: SandboxSeatbeltPolicy; [key: string]: unknown; }; declare type SandboxNetworkPolicy = { allowOutbound?: boolean; allowLocalNetwork?: boolean; allowedHosts?: string[]; blockedHosts?: string[]; [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; }; /** Options for {@link ScheduleApi.add}, {@link ScheduleApi.addCron}, and {@link ScheduleApi.addAt}. */ declare interface ScheduleAddOptions { /** Whether the schedule re-arms after each tick. Defaults to `true`. */ recurring?: boolean; /** * Optional user-facing label shown in the timeline instead of the actual * prompt. See {@link ScheduleEntry.displayPrompt}. */ displayPrompt?: string; /** * IANA timezone for evaluating a cron schedule (e.g. "Europe/Prague"). * Only meaningful for {@link ScheduleApi.addCron}; defaults to the host's * timezone. */ tz?: string; } /** * Narrow interface for tools that need to inspect or manage schedules * without depending on the full ScheduleRegistry implementation. */ declare interface ScheduleApi { /** Snapshot of the currently active entries. */ list(): ScheduleEntry_2[]; /** * Whether this session currently owns an active (non-cancelled) self-paced loop. * Used by the `wakeup` handler to steer a mis-fired re-arm when there is nothing to re-arm. */ hasSelfPaced(): boolean; /** Parse, validate, and register a relative-interval scheduled prompt (e.g. "5m"). */ add(interval: string, prompt: string, options?: ScheduleAddOptions): { entry: ScheduleEntry_2; } | { error: string; }; /** Validate and register a recurring calendar (cron) scheduled prompt. */ addCron(cron: string, prompt: string, options?: ScheduleAddOptions): { entry: ScheduleEntry_2; } | { error: string; }; /** Register a one-shot scheduled prompt that fires at an absolute time (epoch millis). */ addAt(at: number, prompt: string, options?: ScheduleAddOptions): { entry: ScheduleEntry_2; } | { error: string; }; /** * Register a self-paced ("dynamic") scheduled prompt: no fixed cadence. The * first run fires immediately; each subsequent run is armed by the model via * {@link rearmSelfPaced} (the `manage_schedule` `wakeup` action). The schedule * ends when the model stops re-arming (or it is stopped). */ addSelfPaced(prompt: string, options?: ScheduleAddOptions): { entry: ScheduleEntry_2; } | { error: string; }; /** * Re-arm an existing self-paced schedule to fire next at `at` (epoch millis). * Returns the updated entry, or an error if the id is unknown or the entry * is not self-paced. Used by the `manage_schedule` `wakeup` action. */ rearmSelfPaced(id: number, at: number): { entry: ScheduleEntry_2; } | { error: string; }; /** Stop a schedule by id. Returns the removed entry, or undefined if not found. */ 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; /** Schema for the `ScheduleEntry` type. */ 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; } /** * A single scheduled prompt entry. * * Exactly one schedule kind is set: {@link intervalMs} (relative interval), * {@link cron} (recurring calendar), or {@link at} (one-shot absolute time). */ declare interface ScheduleEntry_2 { /** Sequential id within the session, starting at 1. Stable across resumes. */ readonly id: number; /** Interval between ticks in milliseconds. Set for relative-interval schedules. */ readonly intervalMs?: number; /** Recurring calendar expression (5-field cron), evaluated in {@link tz}. */ readonly cron?: string; /** IANA timezone the {@link cron} is evaluated in (e.g. "Europe/Prague"). */ readonly tz?: string; /** One-shot absolute fire time, epoch millis. Set for calendar `/after` schedules. */ readonly at?: number; /** The prompt text that gets enqueued on every tick. */ readonly prompt: string; /** Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`). */ readonly recurring: boolean; /** * True for a self-paced ("dynamic") schedule: one created by `/every` with a * freeform prompt and no explicit time. It has no fixed cadence * ({@link intervalMs}/{@link cron}/{@link at} are all unset); the model arms * each next run via the `manage_schedule` `wakeup` action, and the schedule * ends when the model stops re-arming. {@link nextRunAt} is therefore * model-controlled rather than auto-computed. */ readonly selfPaced?: boolean; /** * Optional user-facing label shown in the timeline instead of {@link prompt}. * Used when the prompt is a model-facing expansion of a slash command (e.g. * a skill invocation), so the user sees `/skill-name` rather than the * verbose "Use the skill tool…" instruction. */ readonly displayPrompt?: string; /** * Epoch milliseconds at which the next tick is scheduled to fire. Updated * each time the registry arms a new timer. While a tick is in flight (the * timer has expired but the prompt is still being delivered) this stays * at the previous value, so callers should clamp `nextRunAt - Date.now()` * to a non-negative number when displaying a countdown. */ readonly nextRunAt: number; } /** Narrowed payload of the events the registry subscribes to. */ declare type ScheduleHostEventPayload = Extract; /** 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 a queued prompt is dequeued and run, not when enqueued). * 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 enqueued 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-`, 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; /** * 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 enqueues the resolved prompt, so the command's deferred * delivery is fine even when the user has an in-flight turn. */ invokeCommand?(name: string, input: string): Promise; 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 { session: T; score: RelevanceScore; } export declare type SdkCommandsChangedEvent = WireTypes.SdkCommandsChangedEvent; /** * A single FTS5 search result. */ declare interface SearchResult { session_id: string; source_type: string; content: string; rank: number; } /** * Searches `allTools` for tools whose name, description, or parameters match * `regex`, returning matching tool names ordered by match quality (name, then * description, then parameter) and capped at `limit`. The tool_search tool * itself is always excluded. * * Shared matcher for the Anthropic and the OpenAI client-executed tool search paths. * Callers compile `regex` themselves so they can surface invalid-pattern errors in their * own result shape. */ declare function searchToolNamesByPattern(allTools: ReadonlyArray, regex: RegExp, limit: number): string[]; /** 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) => Promise>; 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; }; /** Callback that encapsulates per-launch inbox publishing state (send count, freshness, inbox write). */ declare type SendInboxPublisher = (input: { summary: string; content: string; }) => Promise; declare type SendInboxResult = { status: "published"; entryId: string; } | { status: "rejected"; reason?: 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; /** * 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; /** * 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; /** * How this message was delivered relative to the agent loop's state — * `idle` (starts a fresh run), `steering` (injected into an in-flight run), * or `queued` (deferred behind busy work). The timing axis only; origin is * carried by {@link SendOptions.source}. Persisted on the `user.message` * event and emitted in telemetry for attribution. * * @internal Classified by {@link Session.send}; any caller-supplied value is overwritten. */ delivery?: UserMessageDelivery; } /** * 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; /** 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-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` 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; getCurrentAuth(): AccountGetCurrentAuthResult | Promise; getQuota(params?: AccountGetQuotaRequest): AccountGetQuotaResult | Promise; login(params: AccountLoginRequest): AccountLoginResult | Promise; logout(params: AccountLogoutRequest): AccountLogoutResult | Promise; }; agentRegistry: { spawn(params: AgentRegistrySpawnRequest): AgentRegistrySpawnResult | Promise; }; agents: { discover(params: AgentsDiscoverRequest): ServerAgentList | Promise; getDiscoveryPaths(params: AgentsGetDiscoveryPathsRequest): AgentDiscoveryPathList | Promise; }; connect(params: ConnectRequest): ConnectResult | Promise; instructions: { discover(params: InstructionsDiscoverRequest): ServerInstructionSourceList | Promise; getDiscoveryPaths(params: InstructionsGetDiscoveryPathsRequest): InstructionDiscoveryPathList | Promise; }; llmInference: { httpResponseChunk(params: LlmInferenceHttpResponseChunkRequest): LlmInferenceHttpResponseChunkResult | Promise; httpResponseStart(params: LlmInferenceHttpResponseStartRequest): LlmInferenceHttpResponseStartResult | Promise; setProvider(): LlmInferenceSetProviderResult | Promise; }; mcp: { config: { add(params: McpConfigAddRequest): void | Promise; disable(params: McpConfigDisableRequest): void | Promise; enable(params: McpConfigEnableRequest): void | Promise; list(): McpConfigList | Promise; reload(): void | Promise; remove(params: McpConfigRemoveRequest): void | Promise; update(params: McpConfigUpdateRequest): void | Promise; }; discover(params: McpDiscoverRequest): McpDiscoverResult | Promise; }; models: { list(params?: ModelsListRequest): ModelList | Promise; }; ping(params: PingRequest): PingResult | Promise; plugins: { disable(params: PluginsDisableRequest): void | Promise; enable(params: PluginsEnableRequest): void | Promise; install(params: PluginsInstallRequest): PluginInstallResult | Promise; list(): PluginListResult | Promise; marketplaces: { add(params: PluginsMarketplacesAddRequest): MarketplaceAddResult | Promise; browse(params: PluginsMarketplacesBrowseRequest): MarketplaceBrowseResult | Promise; list(): MarketplaceListResult | Promise; refresh(params?: PluginsMarketplacesRefreshRequest): MarketplaceRefreshResult | Promise; remove(params: PluginsMarketplacesRemoveRequest): MarketplaceRemoveResult | Promise; }; uninstall(params: PluginsUninstallRequest): void | Promise; update(params: PluginsUpdateRequest): PluginUpdateResult | Promise; updateAll(): PluginUpdateAllResult | Promise; }; runtime: { shutdown(): void | Promise; }; secrets: { addFilterValues(params: SecretsAddFilterValuesRequest): SecretsAddFilterValuesResult | Promise; }; sessionFs: { setProvider(params: SessionFsSetProviderRequest): SessionFsSetProviderResult | Promise; }; sessions: { bulkDelete(params: SessionsBulkDeleteRequest): SessionBulkDeleteResult | Promise; checkInUse(params: SessionsCheckInUseRequest): SessionsCheckInUseResult | Promise; close(params: SessionsCloseRequest): SessionsCloseResult | Promise; configureSessionExtensions(params: ConfigureSessionExtensionsParams): void | Promise; connect(params: ConnectRemoteSessionParams): RemoteSessionConnectionResult | Promise; enrichMetadata(params: SessionsEnrichMetadataRequest): SessionEnrichMetadataResult | Promise; findByPrefix(params: SessionsFindByPrefixRequest): SessionsFindByPrefixResult | Promise; findByTaskId(params: SessionsFindByTaskIDRequest): SessionsFindByTaskIDResult | Promise; fork(params: SessionsForkRequest): SessionsForkResult | Promise; getBoardEntryCount(params: SessionsGetBoardEntryCountRequest): SessionsGetBoardEntryCountResult | Promise; getEventFilePath(params: SessionsGetEventFilePathRequest): SessionsGetEventFilePathResult | Promise; getLastForContext(params: SessionsGetLastForContextRequest): SessionsGetLastForContextResult | Promise; getPersistedRemoteSteerable(params: SessionsGetPersistedRemoteSteerableRequest): SessionsGetPersistedRemoteSteerableResult | Promise; getRemoteControlStatus(): RemoteControlStatusResult | Promise; getSizes(): SessionSizes | Promise; list(params?: SessionsListRequest): SessionList | Promise; loadDeferredRepoHooks(params: SessionsLoadDeferredRepoHooksRequest): SessionLoadDeferredRepoHooksResult | Promise; open(params: SessionOpenParams): SessionOpenResult | Promise; pollSpawnedSessions(params?: SessionsPollSpawnedSessionsRequest): PollSpawnedSessionsResult | Promise; pruneOld(params: SessionsPruneOldRequest): SessionPruneResult | Promise; registerExtensionToolsOnSession(params: RegisterExtensionToolsParams): RegisterExtensionToolsResult | Promise; releaseLock(params: SessionsReleaseLockRequest): SessionsReleaseLockResult | Promise; reloadPluginHooks(params: SessionsReloadPluginHooksRequest): SessionsReloadPluginHooksResult | Promise; save(params: SessionsSaveRequest): SessionsSaveResult | Promise; setAdditionalPlugins(params: SessionsSetAdditionalPluginsRequest): SessionsSetAdditionalPluginsResult | Promise; setRemoteControlSteering(params: SessionsSetRemoteControlSteeringRequest): RemoteControlStatusResult | Promise; startRemoteControl(params: SessionsStartRemoteControlRequest): RemoteControlStatusResult | Promise; stopRemoteControl(params?: SessionsStopRemoteControlRequest): RemoteControlStopResult | Promise; transferRemoteControl(params: SessionsTransferRemoteControlRequest): RemoteControlTransferResult | Promise; }; skills: { config: { setDisabledSkills(params: SkillsConfigSetDisabledSkillsRequest): void | Promise; }; discover(params: SkillsDiscoverRequest): ServerSkillList | Promise; getDiscoveryPaths(params: SkillsGetDiscoveryPathsRequest): SkillDiscoveryPathList | Promise; }; tools: { list(params: ToolsListRequest): ToolList | Promise; }; user: { settings: { get(): UserSettingsGetResult | Promise; reload(): void | Promise; set(params: UserSettingsSetRequest): UserSettingsSetResult | Promise; }; }; } 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[]; } /** Schema for the `ServerSkill` type. */ 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 { /** 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"; }; /** * Neutral, provider-agnostic representation of server-side ("hosted") tool use * that must be round-tripped verbatim on subsequent turns. * * This is the single concept the session format persists for hosted tool use * (tool search, advisor, and future hosted tools such as web search). It * replaces the previous provider-specific fields that leaked wire-format names * into the message and session schemas (`responses_tool_search_items`, * `responses_function_call_namespaces`, `anthropic_advisor_blocks`, * `anthropic_advisor_model`). * * The payload is intentionally a provider-tagged opaque blob: the two providers * have structurally different round-trip requirements (OpenAI carries a small * set of sidecar items, while Anthropic requires the entire assistant content * array verbatim because block ordering and `thinking` signatures are * validated across the whole array), so a purely semantic shape cannot * losslessly reconstruct both. The conversion layers switch on `provider`. */ declare type ServerToolData = { provider: "openai-responses"; /** * Raw OpenAI Responses API tool_search items (`tool_search_call`, * `tool_search_output`), echoed verbatim and replayed before the * dependent `function_call` items. */ items?: unknown[]; /** * Maps Responses `function_call` call_id to its namespace so * namespaced MCP tool calls keep their namespace on round-trip. */ functionCallNamespaces?: Record; } | { provider: "anthropic-messages"; /** * The entire raw Anthropic assistant content-block array, echoed * verbatim. Contains the server-side blocks (`server_tool_use`, * `advisor_tool_result`, `tool_search_tool_result`) interleaved with * `text` / `thinking` / `tool_use` blocks — all of which must be * preserved for Anthropic to accept the round-tripped turn. */ rawContentBlocks: unknown[]; /** Advisor model ID used for this response (e.g. "claude-opus-4-7"), for timeline display on replay. */ 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 at {@link MAX_SERVICE_LOG_LINES}: 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 the session API dispatch table is * verified at test time by `test/core/sharedApi/sessionSchemaImplValidation.test.ts`, * which walks every entry in `SESSION_API_ENTRIES` and asserts that the resolved * impl member exists on `LocalSession.prototype`. Per-namespace conformance is * enforced statically via the typed factory return on each * `readonly X = sessionXApi(this)` assignment below, where each `sessionXApi` * factory returns the matching generated `SessionApi[...]` namespace type. */ declare abstract class Session { /** * 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. * * Local sessions rename in the local session store; the AHP relay (`RelaySession`) forwards the * rename to the host, which owns the canonical title. Other remote targets (cloud REST, * `--connect`) have no host name round-trip, so `name.set()` is a silent base no-op there. The * `/rename` command consults this so it reports "not available" on those targets instead of * claiming a success it cannot deliver. */ 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(_name: string, localFactory: () => T): T; readonly gitHubAuth: SessionGitHubAuthApi; readonly canvas: SessionCanvasRuntimeApi; /** * Durable open-canvas set, keyed by `instanceId`, rebuilt during replay from * the `session.canvas.recorded` / `instance_removed` companion * events. Used to restore open canvases on cold resume. Structurally never * holds the transient canvas `url` — restore always re-derives it via * provider rehydrate. */ 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; }; readonly plugins: SessionPluginsApi; 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; readonly permissions: SessionPermissionsApi; readonly log: SessionLogApi["log"]; readonly metadata: SessionMetadataApi; 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=` flow). Construction-time injection via * `SessionOptions.remoteDelegate` is preferred for fresh sessions. */ setRemoteDelegate(delegate: SessionRemoteDelegate): 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 | undefined; protected permissionServiceOptions: { approveAllToolPermissionRequests: boolean; approveAllReadPermissionRequests?: boolean; rules: { approved: ReadonlyArray; denied: ReadonlyArray; }; pathManager?: PathManager; urlManager?: UrlManager; }; private allowAllPermissionOverride; /** Whether the session may emit permission.requested events and await a user response. */ protected permissionRequestEventsEnabled: boolean; /** Configure how a lazily created session-owned permission service should behave. */ configurePermissionService(options: { approveAllToolPermissionRequests?: boolean; approveAllReadPermissionRequests?: boolean; rules?: { approved: ReadonlyArray; denied: ReadonlyArray; }; pathManager?: PathManager; urlManager?: UrlManager; }): void; getPathManager(): Promise; setAllowAllPermissions(enabled: boolean, source?: AllowAllSource): Promise; /** * 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; isAllowAllPermissionsActive(): boolean; /** 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; /** 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; /** * 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; /** * 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; /** Flush any pending writes to disk. No-op if no flush callback is registered. */ flushPendingWrites(options?: { force?: boolean; }): Promise; /** 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; /** Tracks the current user-message turn number for turn-scoped session state. */ protected currentTurn: number; /** * The interaction ID used by the most recent agentic-loop run, sent as `X-Interaction-Id`. * A run reuses this value instead of minting a new one whenever it continues an existing * logical interaction rather than starting a fresh human turn: * - a non-human (system) message re-entering the loop — e.g. a background-subagent or shell * completion notification — continues the same interaction in any auth mode; and * - under HMAC auth (no user identity: CCA / Actions / benchmarks) the whole session is one * interaction, because CAPI then keys cache/backend affinity on `X-Interaction-Id` alone. * Churning it there can swap the Anthropic backend mid-conversation and break the prompt * cache (issue #10458). With a user identity, affinity keys on the user, so churning across * human turns is harmless. * Applies to outer agents and subagents alike (each is its own session with its own value). */ protected lastInteractionId?: string; /** 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; /** 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 ` 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; /** * 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; /** 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; }>; /** * 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; /** 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; /** Disable an MCP server (runtime-only, not persisted). */ disableMcpServer(serverName: string): Promise; /** * Build the event-based handler options (elicitation, sampling, OAuth) for McpHost. * * Elicitation is gated on `supportsElicitation()` (checks the session capability set) * rather than `hasEventListeners()`, because in the SDK path the wildcard event forwarder * handles event dispatch without registering per-type listeners. * * Sampling is gated on `hasEventListeners()` since it is only * wired in the CLI path which registers explicit listeners. * * OAuth delegates to `buildMcpOAuthHandler()` which uses an event-based * handler when listeners are registered and falls back to browserless * OAuth otherwise. */ protected getMcpEventHandlers(): Pick; /** * 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; /** * 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 | undefined, options: { originServerName: string; }): Promise; private callMcpAppToolWithOAuthRetry; /** * Fetch an MCP resource (typically a `ui://` MCP App bundle) from a connected server. * Wraps the underlying `Client.readResource` so SDK consumers can pull resolved * UI bundles on demand without going through the HTTP `/mcp-app/resources/read` * proxy endpoint. Errors are surfaced via {@link formatError}. * * Requires the `mcp-apps` session capability. */ readMcpResource(serverName: string, uri: string): Promise<{ contents: Array<{ uri: string; mimeType?: string; text?: string; blob?: string; _meta?: Record; }>; }>; /** * 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; disabledServers?: string[]; enabledServers?: string[]; mcp3pEnabled?: boolean; configFilter?: McpConfigFilter; statusCallback?: ServerStatusCallback; githubMcpToolOptions?: Required; /** Optional secret store for resolving ${secret:...} placeholders (CLI only). */ secretStore?: McpSecretStoreInterface; }): Promise; /** * 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; /** * Remove GitHub MCP server configuration (e.g., on logout). * @returns true if GitHub server was removed, false if no action taken */ removeGitHubMcp(): Promise; /** 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 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; 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 -> 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-` source string) can recover the plugin attribution. */ private _skillPluginByName; private compactionCheckpointLength; private compactionCheckpointMessageRef; private compactionCheckpointEventIndex; private eventProcessingQueue; private processUserRequestedShellContextPartForLlm; private eventHandlers; private wildcardEventHandlers; private usageMetricsTracker; private readonly binaryAssetRegistry; protected integrationId: string; protected availableTools?: string[]; protected excludedTools?: string[]; protected toolFilterPrecedence?: ToolFilterPrecedence; protected defaultAgentExcludedTools?: string[]; protected excludedBuiltinAgents?: string[]; 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; protected mcpHost?: McpHost; protected allowAllMcpServerInstructions: boolean; protected inheritedMcpTools?: readonly Tool_2[]; protected inheritedMcpServers?: Readonly>; 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; protected hasUserNamedGitHubServer: boolean; protected hasUserConfiguredGitHubServer: boolean; protected lastGitHubAuthInfo: AuthInfo | null; protected githubMcpToken: string | undefined; protected githubMcpToolOptions?: Required; protected selectedAgentMcpServerNames: Set; protected lastInitializedAgentMcpServers?: Record; protected hooks?: QueryHooks; /** Ad-hoc hooks added dynamically at runtime, keyed by an owner ID */ protected adHocHooks: Map; protected customAgents?: SweCustomAgent[]; /** 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; protected coauthorEnabled?: boolean; protected systemMessageConfig?: SystemMessageConfig; protected sectionTransformFn?: SectionTransformFn; protected workingDir: string; 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; /** * Per-invocation agent id (typically the dispatching task tool's `toolCallId`) * when this session represents a subagent invocation. Undefined on outer * sessions. Distinct from `sessionId` (which identifies the CLI session as a * whole and is shared by all subagent invocations under the same root). * * Used to surface the per-invocation id on hook payloads via * `this.agentId ?? this.sessionId`, preserving the existing hook contract * after the McpHost/CAPI/OAuth consumers were moved to read the root * `sessionId` directly. */ protected readonly agentId?: string; protected ifcEngine?: IFCEngine; 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; protected disabledMcpServers?: string[]; protected _loadedSkills: Skill_2[]; protected _skillsLoaded: boolean; protected _skillsLoadingPromise?: Promise; /** 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; private _reloadAvailableModels?; protected _mcpLoadingPromise?: Promise; /** * 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; protected installedPlugins?: InstalledPlugin[]; protected _pluginInstructionSourcesPromise?: Promise; protected askUserDisabled?: boolean; protected onExitPlanMode?: (request: ExitPlanModeRequest) => Promise; private _directAutoModeSwitchHandlerCount; private _autopilotObjectiveRegistry?; protected requestedTools?: string[]; protected deferredToolLoading?: boolean; 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; protected additionalContentExclusionPolicies?: ContentExclusionApiResponse[]; /** Handler that delegates permission requests to a parent session. */ protected permissionRequestHandler?: (request: PermissionRequest_2) => Promise; /** 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; /** Virtual filesystem for session-scoped storage (events, workspace, temp files). */ readonly sessionFs: SessionFs; /** Per-session MCP OAuth token/registration store. */ readonly mcpOAuthStore: MCPOAuthStoreInterface; protected onMcpHeadersRefresh?: HeadersRefreshCallback; protected authInfo?: AuthInfo; protected copilotUrl?: string; 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; /** BYOK model registry, keyed by the provider-qualified selection id (`provider/id`). */ protected byokModels: Map; /** Synthesized {@link Model} metadata per provider-qualified selection id (`billing.multiplier = 0`). */ protected byokModelMetadata: Map; /** Auto-mode session manager; provided by `coreServices.autoModeManager` and used to resolve the virtual `"auto"` model selection. */ protected autoModeManager: AutoModeSessionManager; protected modelCapabilitiesOverrides?: ModelCapabilitiesOverride; protected contextTier?: ContextTier_3; protected enableCitations?: boolean; protected sessionLimits?: SessionLimitsConfig_3; protected reasoningEffort?: ReasoningEffort_3; protected reasoningSummary?: ReasoningSummary; 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; /** 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; /** * Creation-time snapshot of the raw option fields a runtime-spawned * remote session inherits from its foreground parent. Runtime-internal; * exposed via {@link getSpawnInheritableOptions}. Not part of the wire schema. */ private readonly spawnInheritableOptions; protected largeOutputConfig?: LargeToolOutputConfig; protected enableWebSocketResponses?: boolean; protected runtimeSettings?: RuntimeSettings; protected configDir?: string; protected repositoryName?: string; protected workspaceContext?: WorkspaceContextInfo; readonly taskRegistry: TaskRegistry; /** Agent task ID in the TaskRegistry for the current multi-turn agent. */ protected taskRegistryAgentId?: string; /** Session-root concurrency limiter shared with child subagent sessions. */ private readonly subAgentLimiter; /** * True when this session created (and therefore owns) the sub-agent limiter. * Child/subagent sessions inherit the limiter by reference and must not * recompute its concurrency/depth policy from their own auth/settings. */ private readonly ownsSubAgentLimiter; /** Shell tool context owned by this session, created lazily during tool init. */ protected readonly shellContextHolder: NonNullable; /** 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; /** * 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; private _currentSystemMessageContent?; private _currentSystemMessageFlat?; private _currentCustomInstructionsMessage?; private _currentToolMetadata?; protected currentNonExternalToolMetadata?: ToolMetadata[]; protected currentTools?: Tool_2[]; /** 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_2[]; protected previousModelUsed?: 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; /** 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; 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`. * * When a consumer subscribes to `mcp.oauth_required`, delegate the full * interactive flow to them. Otherwise install a browserless fallback * that silently reuses cached tokens from the shared OAuth store — so a * server whose tokens are still valid connects immediately instead of * round-tripping through `needs-auth`. When the fallback finds no * cached tokens it throws `MCPOAuthBrowserRequiredError`, which the * processor converts to `needs-auth` for the caller to drive * interactively (via `session.mcp.oauth.login` or `/mcp auth`). */ protected buildMcpOAuthHandler(): NonNullable; private resolveMcpOAuthStaticClientConfig; /** * Browserless MCP OAuth: resolves with a provider only when fresh tokens are * obtainable WITHOUT user interaction (cached tokens, refresh, or the * `client_credentials` grant), and throws `MCPOAuthBrowserRequiredError` * otherwise. Shared by the no-listener fallback and the non-interactive * re-auth path (copilot-mcp-core#1761). */ private runBrowserlessMcpOAuth; /** * Non-interactive OAuth re-auth handler for mid-session tool-call retry and * per-turn recovery (copilot-mcp-core#1761). Returns a provider only when it * can re-auth without user interaction, or `undefined` so the host defers to * `needs-auth` instead of blocking the tool call. */ protected buildMcpOAuthReauthHandler(): NonNullable; protected buildMcpHeadersRefreshHandler(): McpHostOptions["onHeadersRefresh"]; /** 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; /** * Sandbox-bypass shell execution is privilege escalation, so it must never * be short-circuited by a hook `allow`, a resumed permission result, or a * preToolUse pre-approval — the user always re-confirms it at the prompt. * Single source of truth for that gate so the two permission entry points * (`requestPermissionWithHooks` and the subagent `permissions.request` * closure) and `evaluatePermissionHooks` can't drift apart. */ protected isSandboxBypassShellRequest(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; 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; /** * 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; /** 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; /** * 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; 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; /** * 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; /** 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, reason?: McpOAuthRequestReason): Promise; /** 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 dynamic headers refresh request by its ID. */ respondToMcpHeadersRefresh(requestId: string, headers: Record | undefined): boolean; /** Request a UI elicitation dialog. Used by session.ui.* API methods. */ requestUiElicitation(request: ElicitRequestFormParams): Promise; /** * 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; /** * 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; /** 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; /** Reject pending command executions for specific command names (e.g., on client disconnect). */ rejectCommandExecutionsForNames(commandNames: Set, 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 enqueues the resulting prompt (deferred delivery is safe even * during an in-flight turn). * * Dispatch order: runtime command marked `schedulable: true` → CLI * fallback resolver (when set) → null (registry skips the tick). */ invokeCommand(name: string, input: string): Promise; 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; abstract abort(params?: { reason?: AbortReason; }): Promise; /** * 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 abort} invoked by the JSON-RPC * dispatcher. Adapts the `Promise` 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; }>; /** * Returns the creation-time snapshot of option fields that a * runtime-spawned remote session must inherit from this (foreground) * session. Runtime-internal accessor consumed by * `LocalSessionManager.spawnRemoteSession`; not part of the wire schema. */ getSpawnInheritableOptions(): SpawnInheritableSessionOptions; abstract suspend(): Promise; abstract ephemeralQuery(question: string, onChunk: (text: string) => void, abortSignal?: AbortSignal): Promise; /** * 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; executeUserRequestedShellCommand(command: string, options?: UserRequestedShellCommandOptions): Promise; 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 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; /** * 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; /** Pre-recorded permission results consumed while continuing resumable orphans. */ protected readonly _resumePermissionResultsByToolCallId: Map; /** * 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; /** * 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; /** * 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?: SessionEndHookInput["reason"]; error?: Error; }): Promise; /** * 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; protected disposeOwnedFeatureFlagService(): Promise; private _performShutdown; static fromEvents(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; /** * Returns the current authentication information for this session, if set. */ getAuthInfo(): AuthInfo | undefined; /** * Whether the session authenticates to CAPI with no user identity. Only HMAC auth (first-party * integration signing: CCA / Actions / benchmarks) is identity-less. CAPI keys cache/backend * affinity on the user when one exists, and on `X-Interaction-Id` otherwise — so the interaction * ID must stay stable across the whole HMAC session (issue #10458). Note `copilot-api-token` is * deliberately excluded: it is a user-scoped Copilot API token (it carries a `copilotUser`), so * it has a user identity for affinity purposes. */ protected hasNoUserIdentityForCapi(): boolean; /** Returns the last concrete model auto-mode resolved to, if any. */ 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; /** * Adds ad-hoc hooks that are dynamically registered at runtime (e.g., from SDK extension connections). * These are merged with config-based hooks (`this.hooks`) at execution time via `getEffectiveHooks()`. * @param ownerId - Unique key for this hook set (e.g., connection ID). Replaces any existing hooks for this owner. */ addAdHocHooks(ownerId: string, hooks: QueryHooks): void; /** * Removes ad-hoc hooks previously registered with `addAdHocHooks`. */ removeAdHocHooks(ownerId: string): void; /** * Returns the effective hooks: config/plugin/policy hooks (loaded as native * declarative hook specs and executed in Rust) merged with all ad-hoc hooks * (e.g. SDK consumers' callback hooks dispatched out-of-proc over JSON-RPC). * This is the single source of truth for hook execution. */ protected getEffectiveHooks(): QueryHooks | undefined; /** * 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, 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 the additive BYOK registry from session options at construction * (after {@link updateOptions} has set `this.byokProvider`). Delegates to * {@link registerByokEntries}, which performs all validation. */ private initByokRegistry; /** * Adds providers and/or models to the additive BYOK registry, validating the * whole batch before any mutation so a single bad entry leaves the registry * unchanged. Used both at construction (via {@link initByokRegistry}) and at * runtime by the `session.provider.add` shared API. * * Validation (throws on violation, before mutating anything): * - the legacy singular `provider` may not be combined with the `providers`/`models` registry; * - a provider `name` must not contain `/` and must be unique across the registry * (counting providers already registered and others in this same call); * - every `model.provider` must reference a provider that is already registered * or included in this same call; * - model selection ids (provider-qualified `provider/id`) must be unique across * the registry (counting models already registered and others in this same call). * * Within a call, providers are committed before models so a model may reference a * provider introduced in the same call. Provider credentials are registered with the * global {@link SecretFilter} so they are redacted from agent output, logs, and * telemetry like other secrets. * * @returns the synthesized selectable {@link Model} entries for the newly added * models, in input order (empty when only providers were added). */ 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; /** * 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): 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; /** * 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; /** * Get all tracked task summaries for this session. * Returns a unified array with type discriminator for each task. * * NOTE: Despite the name, this returns both sync and background tasks. * Consider renaming to `getTrackedTasks` (along with the `BackgroundTask` * type and `session.background_tasks_changed` event) in a follow-up. */ getBackgroundTasks(): BackgroundTask[]; /** * Inject a factory on the shared {@link LSPClientFactory} singleton that * records each spawned LSP server's lifecycle as a `service` task in this * session's {@link TaskRegistry}. Wired once at construction so it is in * place before any LSP client is created (including by the CLI's warmup hook). */ private wireLspServiceReporterFactory; /** * Tear down the LSP service reporter factory wired in * {@link wireLspServiceReporterFactory}, so a finished session stops * recording new LSP `service` tasks into its (now defunct) registry. */ private unwireLspServiceReporterFactory; /** * Live snapshot of long-lived background services (e.g. LSP servers) tracked * in the {@link TaskRegistry}. Kept separate from {@link getBackgroundTasks} * so services do not appear in `/tasks` or inflate task counts; the `/lsp logs` * panel consumes this instead. Refreshed by CLI consumers on * `session.background_tasks_changed`. */ getServiceTasks(): ServiceTask[]; /** * Cheap count of LSP services still initializing (registry status * `running`), without materializing or copying any server logs. Backs the * "N LSP servers initializing" statusbar hint, which refreshes on every * forwarded log line during a chatty startup — {@link getServiceTasks} would * deep-copy every service's (growing) log on each of those events. */ getInitializingServiceCount(): number; /** * Whether a tracked task can currently be promoted into background mode. */ canPromoteTaskToBackground(taskId: string): boolean; /** * Get the currently-promotable sync task, if any. */ getCurrentPromotableTask(): PromotableTask | undefined; /** * Promote a tracked task into background mode. * * Returns false for unknown tasks or tasks that are not * currently eligible for promotion. */ promoteTaskToBackground(taskId: string): boolean; /** * Promote the currently-awaited sync task into background mode. */ promoteCurrentTaskToBackground(): BackgroundTask | undefined; /** * Returns the current set of available tools as {@link ToolMetadata} objects. * This strips non-serializable properties (callback, shutdown, summariseIntention) * from the full Tool objects. */ getToolDefinitions(): ToolMetadata[]; /** * Emits a notification that the current tool definitions changed. */ notifyToolDefinitionsChanged(): void; protected getExternalToolMetadata(definitions: readonly ExternalToolDefinition[] | undefined): ToolMetadata[]; private getEnabledExternalToolMetadata; protected getValidOverridingExternalToolNames(): Set; protected filterToolsForSelectedAgent(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; protected emitAssistantIntent(intent: string): void; protected refreshIntentFromSessionSql(toolName: string | undefined, toolArgs: unknown, parentToolCallId?: string): Promise; /** * 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; /** * 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; /** * 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; updateSubagentSettings(subagentSettings: UserSettings["subagents"] | undefined): void; /** * Recompute and apply the effective sub-agent concurrency + depth limits to * the shared limiter, based on current auth (plan tier + token-based billing) * and the user's `subagents.maxConcurrency` / `subagents.maxDepth` settings. * * The user-configured limits only apply to usage-based billing (UBB) users; * for everyone else the plan-based defaults are used (so switching away from * UBB resets a previously-applied custom limit). Only the owning session may * mutate the shared limiter — child/subagent sessions inherit it by reference. * * When auth is not yet resolved (no `copilotUser`) we cannot tell whether the * user is UBB, but the configured limits are already known. Rather than fall * back to the permissive default — which would let a first-turn sub-agent * dispatch exceed a configured cap before billing status arrives — we apply * the configured limits **conservatively** (honoring them as if UBB). If auth * later resolves to non-UBB, the auth-change path relaxes them to plan * defaults. This keeps a configured cap from being transiently bypassed and * makes enforcement deterministic regardless of auth-resolution timing. */ protected applyResolvedSubAgentLimits(): void; /** * Start a background agent task from the SDK/shared API layer. * * Delegates to {@link registerBackgroundAgent} which is shared with the * task tool, avoiding duplication of agent-launch / multi-turn wiring. * * @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; }): Promise; /** * 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; /** Public accessor for the effective runtime settings. Merges session-level * feature flags into the returned settings so downstream consumers (e.g., * MCP host initialization, OAuth store, capability checks) see a unified * view that includes CLI `--experimental`, env-var, and config overrides * resolved by the FeatureFlagService — not just server-provided flags. */ resolvedRuntimeSettings(): RuntimeSettings; /** * 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; /** * 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; /** * 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(eventType: K, handler: EventHandler, 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(eventType: EventPayload["ephemeral"] extends true ? never : K, data: EventData, 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(eventType: EventPayload["ephemeral"] extends false ? never : K, data: EventData, agentId?: string): string; /** * The interaction ID of the most recent agentic-loop run, if any. Used by * {@link ImmediatePromptProcessor} so a steering message drained into an * in-flight run continues that run's interaction rather than minting a new * ID — keeping the per-event ID (events.jsonl) and telemetry's interaction * ID aligned with the `X-Interaction-Id` actually sent for the run (issue * #10458). Undefined before the first loop run. */ getActiveInteractionId(): string | undefined; protected emitModelCallFailure(event: ModelCallFailureEvent_2, source: ModelCallFailureSource, agentId?: string): void; /** Adapter that bridges session emit to the HookEventEmitter interface for executeHooks. */ protected readonly hookEventEmitter: HookEventEmitter; /** Returns the loaded hooks configuration, if any. */ getHooks(): QueryHooks | undefined; /** Returns the hook event emitter for hook telemetry. */ getHookEventEmitter(): HookEventEmitter; /** * 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_2[]; /** * 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; /** * 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; /** * 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; /** * 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; /** * Returns the current reasoning effort level for this session. * * @returns The reasoning effort level, or undefined if not set */ getReasoningEffort(): ReasoningEffort_3 | 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 configured session limits. * * @returns The session limits, or undefined if no limits are configured. */ getSessionLimits(): SessionLimitsConfig_3 | undefined; /** * Returns the current reasoning summary mode for this session. * * @returns The reasoning summary mode, or undefined if not set */ getReasoningSummary(): ReasoningSummary | 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 (images and native documents) into the shared binary-asset * registry and emits the * resulting `session.binary_asset` events FIRST (so a reference never * precedes its asset), returning the rewritten attachments (carrying asset * references instead of inline/disk bytes) to persist on the `user.message` * event. Pass-through when there are no attachments. The inline cap is * per-attachment-type (at least each type's model send limit), with the * session's {@link getMaxInlineBinaryBytes} acting as a floor. * * The returned attachments are always fresh objects (never the caller's * input references); tagged file/directory attachments are additionally * stamped with a frozen `taggedFilesEntry` (see {@link freezeTaggedFileEntries}). */ protected internAttachmentsAndEmitAssets(attachments: Attachment[] | undefined, ctx?: { supportedNativeDocumentMimeTypes?: ReadonlySet; nativeDocumentPathFallbackPaths?: ReadonlySet; }, agentId?: string): Promise; /** * Intern + freeze `user.message` attachments for emit sites outside the main * send path (e.g. {@link ImmediatePromptProcessor}). Routes through the same * chokepoint as the CLI/hook paths so tagged-files entries are frozen * consistently. These sites carry no native-document context, so attachments * are interned/frozen with an empty context (a native doc renders as a * `` fallback at both capture and rebuild — see the * context-consistency rule in the §3 plan). */ internAndFreezeAttachmentsForEmit(attachments: Attachment[] | undefined, agentId?: string): Promise; /** * 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; /** Loads and caches instruction sources derived from installed plugin rules. */ protected getPluginInstructionSources(): Promise; /** * 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; /** * 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; /** * 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; /** * 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; /** * Update workspace metadata (cwd, repo, branch) for this session. * Base implementation does nothing - LocalSession overrides. */ updateWorkspaceMetadata(_context: WorkspaceContext, _name?: string): Promise; /** * 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; /** * Check if a plan.md file exists in the workspace. */ hasPlan(): Promise; /** * 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; /** * 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; /** * 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; /** * 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; /** * Write the machine-managed autopilot objective state file. */ writeAutopilotObjective(_content: string): Promise<"create" | "update">; /** * Delete the machine-managed autopilot objective state file. */ deleteAutopilotObjective(): Promise; /** * Check if the machine-managed autopilot objective state file exists. */ autopilotObjectiveExists(): Promise; /** * List files in the workspace files directory. */ listWorkspaceFiles(): Promise; /** * Read a file from the workspace files directory. */ readWorkspaceFile(_path: string): Promise; /** * Write a file to the workspace files directory. */ writeWorkspaceFile(_path: string, _content: string): Promise; /** * 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; /** * 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_3, modelCapabilitiesOverrides?: ModelCapabilitiesOverride, reasoningSummary?: ReasoningSummary, contextTier?: ContextTier_3): Promise; protected applyModelChange(model: string, options?: { reasoningEffort?: ReasoningEffort_3; reasoningSummary?: ReasoningSummary; modelCapabilitiesOverrides?: ModelCapabilitiesOverride; contextTier?: ContextTier_3; cause?: string; }): Promise; /** * 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; /** * 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(fn: () => T | PromiseLike): Promise; /** * 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_2[], settings: RuntimeSettings): Promise; protected hasAwaitingResumeOrphans(): boolean; private resolveInterruptedResumeOrphansOnExplicitResume; private emitInterruptedOrphan; private emitResumeWarning; private emitPermissionResolvedOrphan; private emitCompletedExternalToolOrphan; private continueApprovedExternalToolOrphan; private emitSyntheticToolResult; private emitSyntheticToolFailure; protected emitSessionLimitsSkippedToolResults(toolRequests: NonNullable["data"]["toolRequests"]>, currentModel: string, interactionId: string, turnId?: string): Promise; private getInterruptedToolMessage; protected rewriteChatHistoryForModel(newModel: string): void; protected maybeRewriteChatHistoryForEffectiveModel(newModel: string): void; /** * Recovers the tool name for a tool call from the rebuilt chat history. The * `tool.execution_complete` event doesn't carry the tool name, but the * assistant message that issued the call (already in `_chatMessages` when a * tool result is processed) does. Handles both function and custom tool * calls (via {@link getToolCallName}) so name-based screenshot detection * stays consistent with the live image path on rebuild/resume. Returns * `undefined` if no matching assistant tool call is present. */ private findToolNameForToolCallId; /** * Process event to update internal state (_chatMessages, _selectedModel, etc.) */ private processEventForState; /** * Returns the durable open-canvas set rebuilt from the event log (via * `instance_recorded`/`instance_removed` replay), shaped as seedable * `OpenCanvasInstance` snapshots. The registry's `seed_open_instances` * restores every entry as `stale`, and the transient `url` is intentionally * absent until a provider rehydrates. Used by the resume path to restore * open canvases from the runtime's own durable records. */ getDurableOpenCanvases(): OpenCanvasInstance[]; 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; /** * 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 splitting at the checkpoint and creating * post-compaction messages. Updates _chatMessages and returns the compacted and new messages. * * @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): { 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[0], featureFlag: FeatureFlag): Promise; /** Memoized NO_OUTER_LOOP_TRUNCATION experiment arm; resolved once per session, immutable. */ private noOuterLoopTruncationArmPromise?; /** * Resolves the NO_OUTER_LOOP_TRUNCATION experiment arm once per session and caches it, so the arm * is stable for the whole session (compaction work spans turns, and a mid-session flip could start * a compaction under one arm and apply it under the other). Subagents resolve the same arm as their * parent: `createSubagentSession` shares the parent's `featureFlagService` and `sessionId`, so the * ExP assignment matches, keeping subagents aligned with the outer agent. */ protected getNoOuterLoopTruncationArm(): Promise; /** * 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; } /** 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; agent: { deselect(): void | Promise; getCurrent(): AgentGetCurrentResult | Promise; list(): AgentList | Promise; reload(): AgentReloadResult | Promise; select(params: AgentSelectRequest): AgentSelectResult | Promise; }; canvas: { action: { invoke(params: CanvasActionInvokeRequest): CanvasActionInvokeResult | Promise; }; close(params: CanvasCloseRequest): void | Promise; list(): CanvasList | Promise; listOpen(): CanvasListOpenResult | Promise; open(params: CanvasOpenRequest): OpenCanvasInstance | Promise; }; commands: { enqueue(params: EnqueueCommandParams): EnqueueCommandResult | Promise; execute(params: ExecuteCommandParams): ExecuteCommandResult | Promise; handlePendingCommand(params: CommandsHandlePendingCommandRequest): CommandsHandlePendingCommandResult | Promise; invoke(params: CommandsInvokeRequest): SlashCommandInvocationResult | Promise; list(params?: CommandsListRequest): CommandList | Promise; respondToQueuedCommand(params: CommandsRespondToQueuedCommandRequest): CommandsRespondToQueuedCommandResult | Promise; }; completions: { getTriggerCharacters(): CompletionsGetTriggerCharactersResult | Promise; request(params: CompletionsRequestRequest): CompletionsRequestResult | Promise; }; eventLog: { read(params: EventLogReadRequest): EventsReadResult | Promise; registerInterest(params: RegisterEventInterestParams): RegisterEventInterestResult | Promise; releaseInterest(params: ReleaseEventInterestParams): EventLogReleaseInterestResult | Promise; tail(): EventLogTailResult | Promise; }; extensions: { disable(params: ExtensionsDisableRequest): void | Promise; enable(params: ExtensionsEnableRequest): void | Promise; list(): ExtensionList | Promise; reload(): void | Promise; sendAttachmentsToMessage(params: SendAttachmentsToMessageParams): void | Promise; }; fleet: { start(params: FleetStartRequest): FleetStartResult | Promise; }; gitHubAuth: { getStatus(): SessionAuthStatus | Promise; setCredentials(params: SessionSetCredentialsParams): SessionSetCredentialsResult | Promise; }; history: { abortManualCompaction(): HistoryAbortManualCompactionResult | Promise; cancelBackgroundCompaction(): HistoryCancelBackgroundCompactionResult | Promise; compact(params?: HistoryCompactRequest): HistoryCompactResult | Promise; summarizeForHandoff(): HistorySummarizeForHandoffResult | Promise; truncate(params: HistoryTruncateRequest): HistoryTruncateResult | Promise; }; instructions: { getSources(): InstructionsGetSourcesResult | Promise; }; log(params: LogRequest): LogResult | Promise; lsp: { initialize(params: LspInitializeRequest): void | Promise; }; mcp: { apps: { callTool(params: McpAppsCallToolRequest): Record | Promise>; diagnose(params: McpAppsDiagnoseRequest): McpAppsDiagnoseResult | Promise; getHostContext(): McpAppsHostContext | Promise; listTools(params: McpAppsListToolsRequest): McpAppsListToolsResult | Promise; readResource(params: McpAppsReadResourceRequest): McpAppsReadResourceResult | Promise; setHostContext(params: McpAppsSetHostContextRequest): void | Promise; }; cancelSamplingExecution(params: McpCancelSamplingExecutionParams): McpCancelSamplingExecutionResult | Promise; configureGitHub(params: McpConfigureGitHubRequest): McpConfigureGitHubResult | Promise; disable(params: McpDisableRequest): void | Promise; enable(params: McpEnableRequest): void | Promise; executeSampling(params: McpExecuteSamplingParams): McpSamplingExecutionResult | Promise; headers: { handlePendingHeadersRefreshRequest(params: McpHeadersHandlePendingHeadersRefreshRequestRequest): McpHeadersHandlePendingHeadersRefreshRequestResult | Promise; }; isServerRunning(params: McpIsServerRunningRequest): McpIsServerRunningResult | Promise; list(): McpServerList | Promise; listTools(params: McpListToolsRequest): McpListToolsResult | Promise; oauth: { handlePendingRequest(params: McpOauthHandlePendingRequest): McpOauthHandlePendingResult | Promise; login(params: McpOauthLoginRequest): McpOauthLoginResult | Promise; respond(params: McpOauthRespondRequest): McpOauthRespondResult | Promise; }; registerExternalClient(params: McpRegisterExternalClientRequest): void | Promise; reload(): void | Promise; reloadWithConfig(params: McpReloadWithConfigRequest): McpStartServersResult | Promise; removeGitHub(): McpRemoveGitHubResult | Promise; restartServer(params: McpRestartServerRequest): void | Promise; setEnvValueMode(params: McpSetEnvValueModeParams): McpSetEnvValueModeResult | Promise; startServer(params: McpStartServerRequest): void | Promise; stopServer(params: McpStopServerRequest): void | Promise; unregisterExternalClient(params: McpUnregisterExternalClientRequest): void | Promise; }; metadata: { activity(): SessionActivity | Promise; contextInfo(params: MetadataContextInfoRequest): MetadataContextInfoResult | Promise; isProcessing(): MetadataIsProcessingResult | Promise; recomputeContextTokens(params: MetadataRecomputeContextTokensRequest): MetadataRecomputeContextTokensResult | Promise; recordContextChange(params: MetadataRecordContextChangeRequest): MetadataRecordContextChangeResult | Promise; setWorkingDirectory(params: MetadataSetWorkingDirectoryRequest): MetadataSetWorkingDirectoryResult | Promise; snapshot(): SessionMetadataSnapshot | Promise; }; mode: { get(): SessionMode_2 | Promise; set(params: ModeSetRequest): void | Promise; }; model: { getCurrent(): CurrentModel | Promise; list(params?: ModelListRequest): SessionModelList | Promise; setReasoningEffort(params: ModelSetReasoningEffortRequest): ModelSetReasoningEffortResult | Promise; switchTo(params: ModelSwitchToRequest): ModelSwitchToResult | Promise; }; name: { get(): NameGetResult | Promise; set(params: NameSetRequest): void | Promise; setAuto(params: NameSetAutoRequest): NameSetAutoResult | Promise; }; options: { update(params: SessionUpdateOptionsParams): SessionUpdateOptionsResult | Promise; }; permissions: { configure(params: PermissionsConfigureParams): PermissionsConfigureResult | Promise; folderTrust: { addTrusted(params: FolderTrustAddParams): PermissionsFolderTrustAddTrustedResult | Promise; isTrusted(params: FolderTrustCheckParams): FolderTrustCheckResult | Promise; }; getAllowAll(params: PermissionsGetAllowAllRequest): AllowAllPermissionState | Promise; handlePendingPermissionRequest(params: PermissionDecisionRequest): PermissionRequestResult | Promise; locations: { addToolApproval(params: PermissionLocationAddToolApprovalParams): PermissionsLocationsAddToolApprovalResult | Promise; apply(params: PermissionLocationApplyParams): PermissionLocationApplyResult | Promise; resolve(params: PermissionLocationResolveParams): PermissionLocationResolveResult | Promise; }; modifyRules(params: PermissionsModifyRulesParams): PermissionsModifyRulesResult | Promise; notifyPromptShown(params: PermissionPromptShownNotification): PermissionsNotifyPromptShownResult | Promise; paths: { add(params: PermissionPathsAddParams): PermissionsPathsAddResult | Promise; isPathWithinAllowedDirectories(params: PermissionPathsAllowedCheckParams): PermissionPathsAllowedCheckResult | Promise; isPathWithinWorkspace(params: PermissionPathsWorkspaceCheckParams): PermissionPathsWorkspaceCheckResult | Promise; list(params: PermissionsPathsListRequest): PermissionPathsList | Promise; updatePrimary(params: PermissionPathsUpdatePrimaryParams): PermissionsPathsUpdatePrimaryResult | Promise; }; pendingRequests(params: PermissionsPendingRequestsRequest): PendingPermissionRequestList | Promise; resetSessionApprovals(params: PermissionsResetSessionApprovalsRequest): PermissionsResetSessionApprovalsResult | Promise; setAllowAll(params: PermissionsSetAllowAllRequest): AllowAllPermissionSetResult | Promise; setApproveAll(params: PermissionsSetApproveAllRequest): PermissionsSetApproveAllResult | Promise; setRequired(params: PermissionsSetRequiredRequest): PermissionsSetRequiredResult | Promise; urls: { setUnrestrictedMode(params: PermissionUrlsSetUnrestrictedModeParams): PermissionsUrlsSetUnrestrictedModeResult | Promise; }; }; plan: { delete(): void | Promise; read(): PlanReadResult | Promise; readSqlTodos(): PlanReadSqlTodosResult | Promise; readSqlTodosWithDependencies(): PlanReadSqlTodosWithDependenciesResult | Promise; update(params: PlanUpdateRequest): void | Promise; }; plugins: { list(): PluginList | Promise; reload(params?: PluginsReloadRequest): void | Promise; }; provider: { add(params: ProviderAddRequest): ProviderAddResult | Promise; getEndpoint(params?: ProviderGetEndpointRequest): ProviderEndpoint | Promise; }; queue: { clear(): void | Promise; pendingItems(): QueuePendingItemsResult | Promise; removeMostRecent(): QueueRemoveMostRecentResult | Promise; }; remote: { disable(): void | Promise; enable(params: RemoteEnableRequest): RemoteEnableResult | Promise; notifySteerableChanged(params: RemoteNotifySteerableChangedRequest): RemoteNotifySteerableChangedResult | Promise; }; schedule: { list(): ScheduleList | Promise; stop(params: ScheduleStopRequest): ScheduleStopResult | Promise; }; send(params: SendRequest): SendResult | Promise; shell: { cancelUserRequested(params: ShellCancelUserRequestedRequest): CancelUserRequestedShellCommandResult | Promise; exec(params: ShellExecRequest): ShellExecResult | Promise; executeUserRequested(params: ShellExecuteUserRequestedRequest): UserRequestedShellCommandResult | Promise; kill(params: ShellKillRequest): ShellKillResult | Promise; }; shutdown(params: ShutdownRequest): void | Promise; skills: { disable(params: SkillsDisableRequest): void | Promise; enable(params: SkillsEnableRequest): void | Promise; ensureLoaded(): void | Promise; getInvoked(): SkillsGetInvokedResult | Promise; list(): SkillList | Promise; reload(): SkillsLoadDiagnostics | Promise; }; suspend(): void | Promise; tasks: { cancel(params: TasksCancelRequest): TasksCancelResult | Promise; getCurrentPromotable(): TasksGetCurrentPromotableResult | Promise; getProgress(params: TasksGetProgressRequest): TasksGetProgressResult | Promise; list(): TaskList | Promise; promoteCurrentToBackground(): TasksPromoteCurrentToBackgroundResult | Promise; promoteToBackground(params: TasksPromoteToBackgroundRequest): TasksPromoteToBackgroundResult | Promise; refresh(): TasksRefreshResult | Promise; remove(params: TasksRemoveRequest): TasksRemoveResult | Promise; sendMessage(params: TasksSendMessageRequest): TasksSendMessageResult | Promise; startAgent(params: TasksStartAgentRequest): TasksStartAgentResult | Promise; waitForPending(): TasksWaitForPendingResult | Promise; }; telemetry: { getEngagementId(): SessionTelemetryEngagement | Promise; setFeatureOverrides(params: TelemetrySetFeatureOverridesRequest): void | Promise; }; tools: { getCurrentMetadata(): ToolsGetCurrentMetadataResult | Promise; handlePendingToolCall(params: HandlePendingToolCallRequest): HandlePendingToolCallResult | Promise; initializeAndValidate(): ToolsInitializeAndValidateResult | Promise; updateSubagentSettings(params: UpdateSubagentSettingsRequest): ToolsUpdateSubagentSettingsResult | Promise; }; ui: { elicitation(params: UIElicitationRequest): UIElicitationResponse | Promise; ephemeralQuery(params: UIEphemeralQueryRequest): UIEphemeralQueryResult | Promise; handlePendingAutoModeSwitch(params: UIHandlePendingAutoModeSwitchRequest): UIHandlePendingResult | Promise; handlePendingElicitation(params: UIHandlePendingElicitationRequest): UIElicitationResult | Promise; handlePendingExitPlanMode(params: UIHandlePendingExitPlanModeRequest): UIHandlePendingResult | Promise; handlePendingSampling(params: UIHandlePendingSamplingRequest): UIHandlePendingResult | Promise; handlePendingSessionLimitsExhausted(params: UIHandlePendingSessionLimitsExhaustedRequest): UIHandlePendingResult | Promise; handlePendingUserInput(params: UIHandlePendingUserInputRequest): UIHandlePendingResult | Promise; registerDirectAutoModeSwitchHandler(): UIRegisterDirectAutoModeSwitchHandlerResult | Promise; unregisterDirectAutoModeSwitchHandler(params: UIUnregisterDirectAutoModeSwitchHandlerRequest): UIUnregisterDirectAutoModeSwitchHandlerResult | Promise; }; usage: { getMetrics(): UsageGetMetricsResult | Promise; }; visibility: { get(): VisibilityGetResult | Promise; set(params: VisibilitySetRequest): VisibilitySetResult | Promise; }; workspaces: { createFile(params: WorkspacesCreateFileRequest): void | Promise; diff(params: WorkspacesDiffRequest): WorkspaceDiffResult | Promise; getWorkspace(): WorkspacesGetWorkspaceResult | Promise; listCheckpoints(): WorkspacesListCheckpointsResult | Promise; listFiles(): WorkspacesListFilesResult | Promise; readCheckpoint(params: WorkspacesReadCheckpointRequest): WorkspacesReadCheckpointResult | Promise; readFile(params: WorkspacesReadFileRequest): WorkspacesReadFileResult | Promise; saveLargePaste(params: WorkspacesSaveLargePasteRequest): WorkspacesSaveLargePasteResult | Promise; }; } /** A session approval that can be persisted and restored. */ declare type SessionApproval = z.infer; /** * 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 = Extract; /** * Zod schema for SessionApproval - the source of truth for the type. * Used for validation when loading from persistence. */ declare const SessionApprovalSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{ kind: z.ZodLiteral<"commands">; commandIdentifiers: z.ZodReadonly>; }, "strip", z.ZodTypeAny, { kind: "commands"; commandIdentifiers: readonly string[]; }, { kind: "commands"; commandIdentifiers: readonly string[]; }>, z.ZodObject<{ kind: z.ZodLiteral<"read">; }, "strip", z.ZodTypeAny, { kind: "read"; }, { kind: "read"; }>, z.ZodObject<{ kind: z.ZodLiteral<"write">; }, "strip", z.ZodTypeAny, { kind: "write"; }, { kind: "write"; }>, z.ZodObject<{ kind: z.ZodLiteral<"mcp">; serverName: z.ZodString; toolName: z.ZodNullable; }, "strip", z.ZodTypeAny, { serverName: string; kind: "mcp"; toolName: string | null; }, { serverName: string; kind: "mcp"; toolName: string | null; }>, z.ZodObject<{ kind: z.ZodLiteral<"mcp-sampling">; serverName: z.ZodString; }, "strip", z.ZodTypeAny, { serverName: string; kind: "mcp-sampling"; }, { serverName: string; kind: "mcp-sampling"; }>, z.ZodObject<{ kind: z.ZodLiteral<"memory">; }, "strip", z.ZodTypeAny, { kind: "memory"; }, { kind: "memory"; }>, z.ZodObject<{ kind: z.ZodLiteral<"custom-tool">; toolName: z.ZodString; }, "strip", z.ZodTypeAny, { kind: "custom-tool"; toolName: string; }, { kind: "custom-tool"; toolName: string; }>, z.ZodObject<{ kind: z.ZodLiteral<"extension-management">; operation: z.ZodOptional; }, "strip", z.ZodTypeAny, { kind: "extension-management"; operation?: string | undefined; }, { kind: "extension-management"; operation?: string | undefined; }>, z.ZodObject<{ kind: z.ZodLiteral<"extension-permission-access">; extensionName: z.ZodString; }, "strip", z.ZodTypeAny, { kind: "extension-permission-access"; extensionName: string; }, { kind: "extension-permission-access"; extensionName: string; }>]>; /** 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; } 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 opt-in across all client types. 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; } 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; 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; /** * 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; /** * 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; /** * 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; closeAll(): Promise; private get sessionStatePath(); private get handler(); private get sessionId(); } export declare type SessionEndHook = Hook; /** * Session end hook types */ export declare interface SessionEndHookInput extends BaseHookInput { reason: "complete" | "error" | "abort" | "timeout" | "user_exit"; finalMessage?: string; error?: Error; } export declare interface SessionEndHookOutput { suppressOutput?: boolean; cleanupActions?: string[]; sessionSummary?: string; } /** 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 | WorkspaceFileChangedEvent | HandoffEvent | TruncationEvent | SnapshotRewindEvent | ShutdownEvent | UsageCheckpointEvent | ContextChangedEvent | UsageInfoEvent | CompactionStartEvent | CompactionCompleteEvent | TaskCompleteEvent | UserMessageEvent_2 | PendingMessagesModifiedEvent_2 | AssistantTurnStartEvent_2 | AssistantIntentEvent_2 | AssistantReasoningEvent_2 | AssistantReasoningDeltaEvent_2 | AssistantStreamingDeltaEvent_2 | AssistantMessageEvent_2 | AssistantMessageStartEvent_2 | AssistantMessageDeltaEvent_2 | AssistantTurnEndEvent_2 | AssistantIdleEvent_2 | AssistantUsageEvent_2 | ModelCallFailureEvent | AbortEvent_2 | ToolUserRequestedEvent_2 | ToolExecutionStartEvent_2 | ToolExecutionPartialResultEvent_2 | ToolExecutionProgressEvent_2 | ToolExecutionCompleteEvent_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 | CommandsChangedEvent | CapabilitiesChangedEvent_2 | ExitPlanModeRequestedEvent_2 | ExitPlanModeCompletedEvent_2 | ToolsUpdatedEvent | BackgroundTasksChangedEvent | SkillsLoadedEvent | CustomAgentsUpdatedEvent | McpServersLoadedEvent | McpServerStatusChangedEvent | 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; 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; /** 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; /** 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; /** Append a string to a file, creating it if it doesn't exist. */ abstract appendFile(path: string, content: string, options?: { mode?: number; }): Promise; /** Check whether a path exists. */ abstract exists(path: string): Promise; /** Get metadata for a file or directory. */ abstract stat(path: string): Promise; /** Create a directory. */ abstract mkdir(path: string, options?: { recursive?: boolean; mode?: number; }): Promise; /** List entries in a directory (names only, not full paths). */ abstract readdir(path: string): Promise; /** List entries in a directory with type information. */ abstract readdirWithTypes(path: string): Promise; /** Remove a file or directory. */ abstract rm(path: string, options?: { recursive?: boolean; force?: boolean; }): Promise; /** Rename/move a file or directory. Used for atomic writes. */ abstract rename(src: string, dest: string): Promise; /** * 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; /** Execute a SQLite query against this session's database. */ abstract sqliteQuery(queryType: SqliteQueryType, query: string, params?: Record): Promise; /** Check whether the session database already exists (without creating it). */ abstract sqliteExists(): Promise; /** * 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; } /** Schema for the `SessionFsReaddirWithTypesEntry` 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; /** 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[]; /** 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[]; /** 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; /** Schema for the `SessionInstalledPlugin` type. */ 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; /** Schema for the `SessionInstalledPluginSourceGitHub` type. */ declare interface SessionInstalledPluginSourceGitHub { path?: string; ref?: string; repo: string; /** Constant value. Always "github". */ source: "github"; } /** Schema for the `SessionInstalledPluginSourceLocal` type. */ declare interface SessionInstalledPluginSourceLocal { path: string; /** Constant value. Always "local". */ source: "local"; } /** Schema for the `SessionInstalledPluginSourceUrl` type. */ 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; 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 SessionLogsContent = SessionsChatCompletionMessageParam | SessionsChatCompletionChunk; declare type SessionLogsContents = SessionLogsContent[]; declare type SessionLspApi = SessionApi["lsp"]; /** * SessionManager interface */ export declare interface SessionManager = Session> { createSession(sessionOptions: SessionOptions): Promise; getSession(options: { sessionId: string; }): Promise; getLastSession(): Promise; getLastSessionId(): Promise; listSessions(): Promise; saveSession(session: TSession): Promise; deleteSession(sessionId: string): Promise; closeSession(sessionId: string): Promise; } /** * SessionManager options - same as SessionOptions but used for creating the manager */ export declare type SessionManagerOptions = { logger?: RunnerLogger; integrationId?: string; }; declare type SessionMcpApi = Omit; declare type SessionMcpAppsApi = SessionApi["mcp"]["apps"]; declare type SessionMcpHeadersApi = SessionApi["mcp"]["headers"]; declare type SessionMcpOauthApi = SessionApi["mcp"]["oauth"]; export declare type SessionMcpServersResolvedEvent = WireTypes.SessionMcpServersResolvedEvent; export declare type SessionMcpServerStatusChangedEvent = WireTypes.SessionMcpServerStatusChangedEvent; 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[]; /** Per-quota snapshots returned alongside the model list, keyed by quota type. */ quotaSnapshots?: Record; } 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; /** 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; /** 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_2; /** 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; /** Working directory to anchor the session. */ workingDirectory?: string; /** Pre-resolved working-directory context for session startup. */ workingDirectoryContext?: SessionContext_2; } /** Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicy` type. */ declare interface SessionOpenOptionsAdditionalContentExclusionPolicy { last_updated_at: unknown; rules: SessionOpenOptionsAdditionalContentExclusionPolicyRule[]; /** Allowed values for the `SessionOpenOptionsAdditionalContentExclusionPolicyScope` enumeration. */ scope: SessionOpenOptionsAdditionalContentExclusionPolicyScope; [key: string]: unknown; } /** Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRule` type. */ declare interface SessionOpenOptionsAdditionalContentExclusionPolicyRule { ifAnyMatch?: string[]; ifNoneMatch?: string[]; paths: string[]; /** Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` type. */ source: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource; [key: string]: unknown; } /** Schema for the `SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource` 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 { 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_3; /** * Reasoning summary mode for models that support it. * When omitted, the client uses model/runtime defaults. */ reasoningSummary?: ReasoningSummary; /** * 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, preserving SDK/query behavior. * - `interactive`: defer sessionEnd hooks until explicit session shutdown. */ sessionLifecycleMode?: "per-turn" | "interactive"; /** SDK-supplied overrides for model capabilities, deep-merged over runtime defaults. */ modelCapabilitiesOverrides?: ModelCapabilitiesOverride; /** * Context tier selected for models with tiered context pricing. The session * uses this to derive an effective `modelCapabilitiesOverrides` field-wise, * so that compaction, truncation, token-display, and request limits all * honor the selected tier. Persisted in `session.start` (and refreshed in * `session.resume`) so resume restores the exact tier without app-level * repair logic. */ contextTier?: "default" | "long_context"; /** * Experimental: when true, enables native model citations (Anthropic models * today). Citable tool output (e.g. web-search results) is materialized into * `search_result` blocks and citation emission is turned on, with results * normalized onto `assistant.message` events. Off by default. May change or * be removed while the citations surface is experimental. */ enableCitations?: boolean; 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 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; /** * When true, enables loading of `.github/hooks/` filesystem hooks. * Separate from the `hooks` option (which provides SDK callback hook handlers). * SDK sessions default to false; CLI sessions set their own defaults. */ enableFileHooks?: boolean; /** * When true, enables host git operations (context resolution, child repo scanning, * git info in system prompt). SDK sessions default to false. */ enableHostGitOperations?: boolean; /** * When true, enables cross-session store writes and reads. * SDK sessions default to false. */ enableSessionStore?: boolean; /** * When true, enables skill directory scanning and loading. * Falls back to enableConfigDiscovery when not explicitly set. */ enableSkills?: boolean; installedPlugins?: InstalledPlugin[]; mcpServers?: Record; 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; /** * 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; hooks?: QueryHooks; externalToolDefinitions?: ExternalToolDefinition[]; 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; 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; /** * 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; 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; /** * 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; /** * 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?: RuntimeSettings; /** * 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; /** * Per-invocation agent 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 per-invocation id so that * hook payloads, which contract to surface the per-invocation id as their * `sessionId` field, can read `this.agentId ?? this.sessionId`. */ agentId?: 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; } declare type SessionOptionsApi = SessionApi["options"]; declare type SessionPermissionsApi = SessionApi["permissions"]; export declare type SessionPermissionsChangedEvent = WireTypes.SessionPermissionsChangedEvent; 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; } 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[]; } declare type SessionsChatCompletionChunk = CopilotChatCompletionChunk & AgentIdBag; declare type SessionsChatCompletionMessageParam = (SessionsUserMessageParam | ChatCompletionToolMessageParam) & AgentIdBag; /** 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 { } /** 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; } /** 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; } 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 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`; 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"; /** Schema for the `SessionsOpenProgress` type. */ 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"; /** Schema for the `SessionsPollSpawnedSessionsEvent` type. */ declare interface SessionsPollSpawnedSessionsEvent { /** Session id of the newly-spawned session. */ sessionId: string; } /** Cursor and optional long-poll wait for polling runtime-spawned sessions. */ declare type SessionsPollSpawnedSessionsRequest = { cursor?: string; waitMs?: number; }; /** 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; export declare type SessionStartHook = Hook; /** * Session start hook types */ export declare interface SessionStartHookInput extends BaseHookInput { source: "startup" | "resume" | "new"; initialPrompt?: string; } export declare interface SessionStartHookOutput { additionalContext?: string; modifiedConfig?: Record; } /** * 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; /** * Get Forge trajectory events for a session in insertion order. */ getForgeTrajectoryEvents(sessionId: string): Promise; /** * Get Forge trajectory events across recent sessions matching the provided repository/branch scope. */ getForgeTrajectoryEventsForScope(scope?: ForgeTrajectoryScope): Promise; private forgeProposalScopeInput; private parseForgeProposalManifest; private parseForgeProposalSummary; private toForgeProposalRecord; getForgeSkillProposalById(id: string): ForgeSkillProposalRecord | undefined; listForgeSkillProposals(scope: ForgeSkillProposalScope, statuses?: readonly ForgeSkillProposalStatus[]): Promise; getForgeSkillProposalByFingerprint(scope: ForgeSkillProposalScope, fingerprint: string, statuses?: readonly ForgeSkillProposalStatus[]): ForgeSkillProposalRecord | undefined; beginForgeSkillProposalGeneration(input: { id: string; scope: ForgeSkillProposalScope; triggerMode: ForgeSkillProposalTriggerMode; workspaceBeforeByPath?: Record; createdAt?: string; }): ForgeSkillProposalRecord; getForgeSkillProposalWorkspaceBefore(id: string): Record | 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; /** * 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; /** * 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; /** * 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(sql: string): Record[]; executeReadOnlyWithCap(sql: string, limit: number): LocalQueryResult; /** * 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; /** * 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; } declare type SessionsUserMessageParam = 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; }; 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): 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"]; 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; /** Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. */ installedPlugins?: SessionInstalledPlugin[]; /** Stable integration identifier used for analytics and rate-limit attribution. */ integrationId?: string; /** Whether experimental capabilities are enabled. */ isExperimentalMode?: boolean; /** Whether interactive shell sessions are logged. */ logInteractiveShells?: boolean; /** Identifier sent to LSP-style integrations. */ lspClientName?: string; /** Whether to expose the `manage_schedule` tool to the agent. The runtime always owns the per-session schedule registry; this flag only controls tool exposure (typically gated to staff users). */ manageScheduleEnabled?: boolean; /** Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. */ maxInlineBinaryBytes?: number; /** The model ID to use for assistant turns. */ model?: string; /** Per-property model capability overrides for the selected model. */ modelCapabilitiesOverrides?: ModelCapabilitiesOverride_2; /** Organization-level custom instructions to inject into the system prompt. */ organizationCustomInstructions?: string; /** Custom model-provider configuration (BYOK). */ provider?: ProviderConfig_2; /** Reasoning effort for the selected model (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; /** Absolute working-directory path for shell tools. */ workingDirectory?: string; } /** Indicates whether the session options patch was applied successfully. */ declare interface SessionUpdateOptionsResult { /** 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 function settingsFilePath(subDir?: string, settings?: RuntimeSettings): string; declare namespace Shared { export { AllModels, ChatModel, ComparisonFilter, CompoundFilter, CustomToolInputFormat, ErrorObject, FunctionDefinition, FunctionParameters, Metadata, Reasoning, ReasoningEffort, ResponseFormatJSONObject, ResponseFormatJSONSchema, ResponseFormatText, ResponseFormatTextGrammar, ResponseFormatTextPython, ResponsesModel } } 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; } /** * Callback invoked when a shell command completes in the background. * This includes async commands and sync commands that were timed out or * explicitly released into the background. */ declare type ShellCommandCompletionCallback = (shellId: string, output: ShellOutput, description?: string) => void; declare class ShellConfig { /** * Used to vary behavior programmatically for different shell implementations. */ readonly shellType: ShellType; /** * Used when describing the shell type to users or in prompts. */ readonly displayName: string; /** * Name of a tool that invokes a shell command. */ readonly shellToolName: string; /** * Name of a tool that reads output from a shell session. */ readonly readShellToolName: string; /** * Name of a tool that terminates a shell session. */ readonly stopShellToolName: string; /** * Name of a tool that lists all active shell sessions. */ readonly listShellsToolName: string; /** * Additional information to add to the tool description. */ readonly descriptionLines: string[]; /** * A function that assesses the safety of a script to be run in the shell. * This is pluggable so shell tools can share the same configuration shape * while different hosts provide the safety implementation. */ readonly assessScriptSafety: (script: string, onWarning?: (message: string) => void) => Promise; /** * Sandbox configuration for shell commands. */ readonly sandbox: SandboxConfig_2; /** * Controls which profile/startup scripts the shell sources during initialization. */ readonly initProfile: ShellInitProfile; /** * Flags passed to the shell process on startup (e.g. `-NoProfile`, `-NoLogo` for PowerShell, * `--norc`, `--noprofile` for Bash). These are prepended before any structural flags * like `-NoExit` or `-Command`. */ readonly processFlags: readonly string[]; constructor( /** * Used to vary behavior programmatically for different shell implementations. */ shellType: ShellType, /** * Used when describing the shell type to users or in prompts. */ displayName: string, /** * Name of a tool that invokes a shell command. */ shellToolName: string, /** * Name of a tool that reads output from a shell session. */ readShellToolName: string, /** * Name of a tool that terminates a shell session. */ stopShellToolName: string, /** * Name of a tool that lists all active shell sessions. */ listShellsToolName: string, /** * Additional information to add to the tool description. */ descriptionLines: string[], /** * A function that assesses the safety of a script to be run in the shell. * This is pluggable so shell tools can share the same configuration shape * while different hosts provide the safety implementation. */ assessScriptSafety?: (script: string, onWarning?: (message: string) => void) => Promise, /** * Sandbox configuration for shell commands. */ sandbox?: SandboxConfig_2, /** * Controls which profile/startup scripts the shell sources during initialization. */ initProfile?: ShellInitProfile, /** * Flags passed to the shell process on startup (e.g. `-NoProfile`, `-NoLogo` for PowerShell, * `--norc`, `--noprofile` for Bash). These are prepended before any structural flags * like `-NoExit` or `-Command`. */ processFlags?: readonly string[]); withScriptSafetyAssessor(assessor: (shellType: ShellType, script: string, onWarning?: (message: string) => void) => Promise): ShellConfig; withSandbox(sandbox: SandboxConfig_2): ShellConfig; withInitProfile(profile: ShellInitProfile): ShellConfig; withProcessFlags(flags: readonly string[]): ShellConfig; static readonly bash: ShellConfig; static readonly powerShell: ShellConfig; } /** Session-owned shell context holder shared across concurrent tool builds. */ declare type ShellContextHolder = GenerationalHolder; /** 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"; /** Options for creating a new shell execution session via the factory. */ declare type ShellExecutionSessionCreateOptions = { shellId: string; shellConfig: ShellConfig; cwd: string; env: NodeJS.ProcessEnv; largeOutputOptions: LargeOutputOptions; shellLogFile?: string; }; /** A point-in-time snapshot of a shell execution session's status. */ declare type ShellExecutionSessionSnapshot = { pid?: number; isRunning: boolean; hasUnreadOutput: boolean; status: TaskStatus_2; exitCode?: number; stats: ShellSessionStats; }; 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; } /** * Controls which profile/startup scripts the shell sources during initialization. * Shell-agnostic in concept; each shell type interprets the profile concretely. */ declare const ShellInitProfile: { /** Skip all profile/rc scripts (default). */ readonly None: "none"; /** * Load non-interactive profile scripts if the shell supports them. * Bash: sources BASH_ENV if set. PowerShell: no-op. */ 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; } /** * Output from a shell command execution. Backend-neutral. */ declare type ShellOutput = { /** The output text (may be preview if large output was written to file) */ output: string; exitCode?: number; /** If set, large output was written to this file */ largeOutputFilePath?: string; /** Total bytes of output (set when large output was written to file) */ 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; } /** Callback invoked when partial output changes during command execution. */ declare type ShellPartialOutputChangedCallback = (output: ShellOutput) => void; /** * 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; /** * Possible file paths that the command might access. * * This is entirely heuristic, so it's pretty untrustworthy. */ readonly possiblePaths: ReadonlyArray; /** * Possible URLs that the command might access. * * This is entirely heuristic, so it's pretty untrustworthy. */ readonly possibleUrls: ReadonlyArray; /** * 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 function shellPolicy(mode: ShellAttachmentMode): { readonly survivesContextShutdown: false; readonly stopOnTurnCancellation: true; readonly blocksSessionIdle: true; readonly waitForSessionDrain: true; readonly retainAfterStop: false; } | { readonly survivesContextShutdown: true; readonly stopOnTurnCancellation: false; readonly blocksSessionIdle: false; readonly waitForSessionDrain: false; readonly retainAfterStop: true; }; declare type ShellReadOptions = { flush?: boolean; view?: "full" | "recent"; }; declare type ShellSessionStats = { createdAtMs: number; lastUsedAtMs: number; }; declare type ShellStopOutcome = "stopped" | "already-terminal" | "process-unavailable"; /** * 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; /** 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; } /** * 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 = "bash" | "powershell"; declare type ShellWaitResult = { kind: "completed" | "timeout"; output: ShellOutput; status: TaskStatus_2; }; /** * Checks if a tool result should be written to a file based on its size. */ declare function 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; /** 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; /** 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"; } /** Schema for the `ShutdownModelMetric` type. */ declare interface ShutdownModelMetric { /** Request count and cost metrics */ requests: ShutdownModelMetricRequests; /** Token count details per type */ tokenDetails?: Record; /** 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; } /** Schema for the `ShutdownModelMetricTokenDetail` type. */ 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; } /** Schema for the `ShutdownTokenDetail` type. */ 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; private readonly firedTriggers; private readonly unsubscribers; private initPromise?; private sessionContext?; private readonly _registeredAgentNames; /** * 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; /** * Returns whether any sidekick agents registered during initialization. * Awaits initialization so the answer is final. */ hasSidekickAgents(): Promise; 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; /** Forcefully cancel all running sidekick agents. */ cancelAll(): void; /** Send notification for an inbox entry. */ private sendInboxNotification; /** Flush any unread/unnotified inbox entries as system notifications. */ flushPendingNotifications(): Promise; 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; /** * Whether this agent+trigger pair should fire at most once per session. * Only the one-shot `user.message` event is gated by `triggerOnce`; all other * trigger types (e.g. `session.context_changed`) keep firing on every occurrence. */ private shouldTriggerOnlyOnce; /** * Single owner of firedTriggers — check and mark live together, both inside * the per-name serialized chain, so two enqueued events can't both proceed. * Only marks the trigger as fired when launchAgent commits (launched or * delivered) AND the trigger is the one-shot `user.message` event; all other * triggers (e.g. session.context_changed) 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; memoryApiCache?: MemoryApiCache; getDynamicContextConfig?(): LaunchCheckDynamicContextConfig | null; getRuntimeSettings(): RuntimeSettings | undefined; getResponseLimitsStatus?(): ResponseLimitsStatus | undefined; getCachedTools(): Tool_2[]; 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; }; /** Schema for the `Skill` type. */ 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; } /** Schema for the `SkillDiscoveryPath` type. */ 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"; /** * Metadata about a skill invocation, used for event emission and compaction tracking. */ declare interface SkillInvocation { /** The skill name */ name: string; /** Path to the SKILL.md file */ path: string; /** The body of the skill file (YAML frontmatter stripped) */ content: string; /** Tools that should be auto-approved when this skill is active */ allowedTools?: string[]; /** Source identifier for where the skill was discovered (project, inherited, personal-*, custom, plugin, builtin, remote, ...). */ source?: 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; /** Description of what the skill does (from frontmatter) */ description?: string; /** * The trigger that caused the skill to be invoked. Defaults to * `"agent-invoked"` when the producer does not specify one. */ trigger?: SkillInvocationTrigger; } /** * The trigger that caused a skill to be invoked. Used for telemetry and audit. * * - `user-invoked`: explicit user action, such as via a slash command or UI affordance. * - `agent-invoked`: the agent requested the skill. * - `context-load`: the skill was loaded as part of another context, such as * preloading skills configured on a custom agent or subagent. * * The skill tool reports `agent-invoked`; skills preloaded into a custom-agent * prompt report `context-load`. Future user-facing invocation paths can report * `user-invoked` once session-level state plumbing can distinguish them. */ 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; /** 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[]; } /** Schema for the `SkillsInvokedSkill` type. */ 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[]; } /** Schema for the `SkillsLoadedData` type. */ declare interface SkillsLoadedData { /** Array of resolved skill metadata */ skills: SkillsLoadedSkill[]; } /** Session event "session.skills_loaded". */ declare interface SkillsLoadedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `SkillsLoadedData` type. */ 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"; } /** Schema for the `SkillsLoadedSkill` type. */ 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"; /** Schema for the `SlashCommandAgentPromptResult` type. */ 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; /** Prompt to submit to the agent */ prompt: string; /** True when the invocation mutated user runtime settings; consumers caching settings should refresh */ runtimeSettingsChanged?: boolean; } /** Schema for the `SlashCommandCompletedResult` type. */ 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; } /** Schema for the `SlashCommandInfo` type. */ 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 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; } /** 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"; /** Schema for the `SlashCommandSelectSubcommandOption` type. */ 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; } /** Schema for the `SlashCommandSelectSubcommandResult` type. */ 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; } /** Schema for the `SlashCommandTextResult` type. */ 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"; } /** * Creation-time snapshot of the raw {@link SessionOptions} fields that a * runtime-spawned remote session must inherit from the foreground session * that triggered the spawn (see `LocalSessionManager.spawnRemoteSession`). * * This is **runtime-internal**: it is read in-process by the session manager * and is intentionally NOT part of the wire/JSON-RPC schema surface. The * snapshot captures the *raw* option values supplied at construction (in * particular, `model` is preserved as `undefined` when the caller selected * auto mode — we deliberately do not substitute the later-resolved concrete * model, and we do not reflect mid-session model switches). */ declare type SpawnInheritableSessionOptions = Pick; /** * Split a SQL string into statements while respecting semicolons inside * single-quoted string literals and SQL comments. */ declare function splitSqlStatements(query: string): string[]; declare type SqlInput = z_2.infer; /** * Zod schema for sql tool input with database selector (session + session_store). */ declare const sqlInputSchemaWithDb: z_2.ZodObject<{ description: z_2.ZodString; query: z_2.ZodString; } & { database: z_2.ZodDefault>>; }, "strip", z_2.ZodTypeAny, { query: string; description: string; database: "session" | "session_store"; }, { query: string; description: string; database?: "session" | "session_store" | undefined; }>; 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.ZodObject<{ type: z.ZodLiteral<"file">; path: z.ZodString; displayName: z.ZodString; lineRange: z.ZodOptional>; }, "strip", z.ZodTypeAny, { path: string; type: "file"; displayName: string; lineRange?: { start: number; end: number; } | undefined; }, { path: string; type: "file"; displayName: string; lineRange?: { start: number; end: number; } | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"directory">; path: z.ZodString; displayName: z.ZodString; }, "strip", z.ZodTypeAny, { path: string; type: "directory"; displayName: string; }, { path: string; type: "directory"; displayName: string; }>, z.ZodObject<{ type: z.ZodLiteral<"selection">; filePath: z.ZodString; displayName: z.ZodString; text: z.ZodString; selection: z.ZodObject<{ start: z.ZodObject<{ line: z.ZodNumber; character: z.ZodNumber; }, "strip", z.ZodTypeAny, { line: number; character: number; }, { line: number; character: number; }>; end: z.ZodObject<{ line: z.ZodNumber; character: z.ZodNumber; }, "strip", z.ZodTypeAny, { line: number; character: number; }, { line: number; character: number; }>; }, "strip", z.ZodTypeAny, { start: { line: number; character: number; }; end: { line: number; character: number; }; }, { start: { line: number; character: number; }; end: { line: number; character: number; }; }>; }, "strip", z.ZodTypeAny, { text: string; selection: { start: { line: number; character: number; }; end: { line: number; character: number; }; }; type: "selection"; displayName: string; filePath: string; }, { text: string; selection: { start: { line: number; character: number; }; end: { line: number; character: number; }; }; type: "selection"; displayName: string; filePath: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_reference">; number: z.ZodNumber; title: z.ZodString; referenceType: z.ZodEnum<["issue", "pr", "discussion"]>; state: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { number: number; url: string; type: "github_reference"; title: string; referenceType: "issue" | "pr" | "discussion"; state: string; }, { number: number; url: string; type: "github_reference"; title: string; referenceType: "issue" | "pr" | "discussion"; state: string; }>, z.ZodObject<{ type: z.ZodLiteral<"blob">; data: z.ZodString; mimeType: z.ZodString; displayName: z.ZodOptional; }, "strip", z.ZodTypeAny, { type: "blob"; data: string; mimeType: string; displayName?: string | undefined; }, { type: "blob"; data: string; mimeType: string; displayName?: string | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"github_commit">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; oid: z.ZodString; message: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { message: string; url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_commit"; oid: string; }, { message: string; url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_commit"; oid: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_release">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; tagName: z.ZodString; name: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { url: string; name: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_release"; tagName: string; }, { url: string; name: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_release"; tagName: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_actions_job">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; jobId: z.ZodNumber; jobName: z.ZodString; workflowName: z.ZodString; url: z.ZodString; conclusion: z.ZodOptional; }, "strip", z.ZodTypeAny, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_actions_job"; jobId: number; jobName: string; workflowName: string; conclusion?: string | undefined; }, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_actions_job"; jobId: number; jobName: string; workflowName: string; conclusion?: string | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"github_repository">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; url: z.ZodString; description: z.ZodOptional; ref: z.ZodOptional; }, "strip", z.ZodTypeAny, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_repository"; description?: string | undefined; ref?: string | undefined; }, { url: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_repository"; description?: string | undefined; ref?: string | undefined; }>, z.ZodObject<{ type: z.ZodLiteral<"github_file_diff">; url: z.ZodString; head: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; }, "strip", z.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.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; }, "strip", z.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.ZodTypeAny, { url: string; type: "github_file_diff"; 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; }, { url: string; type: "github_file_diff"; 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.ZodObject<{ type: z.ZodLiteral<"github_tree_comparison">; url: z.ZodString; base: z.ZodObject<{ repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; revision: z.ZodString; }, "strip", z.ZodTypeAny, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }>; head: z.ZodObject<{ repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; revision: z.ZodString; }, "strip", z.ZodTypeAny, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }, { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }>; }, "strip", z.ZodTypeAny, { url: string; type: "github_tree_comparison"; head: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; base: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; }, { url: string; type: "github_tree_comparison"; head: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; base: { repo: { name: string; owner: string; id?: number | undefined; }; revision: string; }; }>, z.ZodObject<{ type: z.ZodLiteral<"github_url">; url: z.ZodString; }, "strip", z.ZodTypeAny, { url: string; type: "github_url"; }, { url: string; type: "github_url"; }>, z.ZodObject<{ type: z.ZodLiteral<"github_file">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; url: z.ZodString; }, "strip", z.ZodTypeAny, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_file"; ref: string; }, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_file"; ref: string; }>, z.ZodObject<{ type: z.ZodLiteral<"github_snippet">; repo: z.ZodObject<{ id: z.ZodOptional; name: z.ZodString; owner: z.ZodString; }, "strip", z.ZodTypeAny, { name: string; owner: string; id?: number | undefined; }, { name: string; owner: string; id?: number | undefined; }>; ref: z.ZodString; path: z.ZodString; url: z.ZodString; lineRange: z.ZodObject<{ start: z.ZodNumber; end: z.ZodNumber; }, "strip", z.ZodTypeAny, { start: number; end: number; }, { start: number; end: number; }>; }, "strip", z.ZodTypeAny, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_snippet"; lineRange: { start: number; end: number; }; ref: string; }, { url: string; path: string; repo: { name: string; owner: string; id?: number | undefined; }; type: "github_snippet"; lineRange: { start: number; end: 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_2; /** 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; /** 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[]; } /** * 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; declare type StoredSandboxUserPolicy = NonNullable; declare type StoreStats = { sessions: number; turns: number; checkpoints: number; files: number; refs: number; }; declare const str_replace_editor: (config: ToolConfig, logger: RunnerLogger, _settings?: RuntimeSettings) => Tool_2 & { shutdown: NonNullable; summariseIntention: NonNullable; }; /** * 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 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; /** * 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: "streaming_size"; totalResponseSizeBytes?: number; }; 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; } | { source: "npm"; package: string; } | { source: "file"; path: string; } | { source: "directory"; path: string; } | { source: "hostPattern"; hostPattern: string; } | { source: "pathPattern"; pathPattern: string; }; export declare function stringifyHookJson(value: unknown, label: string): 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 StrReplaceArgs = EditInput & { command: "str_replace" | "edit"; }; declare type StrReplaceEditorArgs = ViewArgs | CreateArgs | StrReplaceArgs | InsertArgs; declare type StrReplaceEditorOptions = { /** * What to base the truncation of the output of the tool on. Defaults to `"strLen"`. */ truncateBasedOn?: "strLen" | "tokenCount"; /** * How to style the truncation of the output of the tool. Defaults to `"middle"`. */ truncateStyle?: "end" | "middle"; }; declare type StrReplaceEditorResult = Omit & { toolTelemetry: StrReplaceEditorTelemetry; }; declare type StrReplaceEditorShutdownTelemetry = TelemetryEvent_2<"str_replace_editor_shutdown", { properties: { trackedEdits: string; }; metrics: Record; restrictedProperties: Record; }>; declare type StrReplaceEditorTelemetry = { properties: { command: "invalid" | StrReplaceEditorArgs["command"]; resolvedPathAgainstCwd: string; /** * Stringified copy of {@link StrReplaceEditorOptions}. */ options: string; /** * Stringified list of the input names passed to the tool. */ inputs: string; /** * JSON-encoded array of file extensions edited (e.g. '[".ts"]'). * Extensions are safe-for-telemetry values; unknown extensions appear as "not-safe". */ fileExtension?: string; /** * JSON-encoded array of language IDs corresponding to the file extensions edited. * Format: '["typescript"]'. */ languageId?: string; /** * JSON-encoded array of code blocks with LOC per file extension. * Format: '[{"fileExt":".ts","languageId":"typescript","linesAdded":10,"linesRemoved":2}]'. */ codeBlocks?: string; }; restrictedProperties: { initFeedbackError?: string; getEditFeedbackError?: string; editFeedback?: string; } & Partial; metrics: { responseTokenLimit: number | undefined; resultLength: number; resultForLlmLength: number; } & Partial; }; declare const stubAssessScriptSafety: (script: string) => Promise; /** 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. */ declare class SubAgentLimiter { private _runningCount; private _maxConcurrent; private _maxDepth; 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; /** 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; /** * 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; /** * 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; /** * 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; } /** Subagent settings to apply, or null to clear the live session override */ declare type SubagentSettings = { agents?: Record; 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"; } export declare type SubagentStartHook = Hook; /** * Subagent start hook types — fires when a subagent is spawned via the Task tool. * Cannot block subagent creation. Can inject additionalContext into the subagent. */ export declare interface SubagentStartHookInput extends BaseHookInput { transcriptPath: string; agentName: string; agentDisplayName?: string; agentDescription?: string; } export declare interface SubagentStartHookOutput { additionalContext?: string; } export declare type SubagentStopHook = Hook; /** * Subagent stop hook types - fires when a subagent completes, before returning result to parent */ export declare interface SubagentStopHookInput extends BaseHookInput { transcriptPath: string; agentName: string; agentDisplayName?: string; stopReason: "end_turn"; } export declare interface SubagentStopHookOutput { /** If "block", the subagent will continue with another turn using the reason. Undefined means "allow". */ decision?: HookBlockDecision; reason?: string; } /** * 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"; /** * Telemetry-specific overrides that subagents pass when requesting tools * for their own sub-agents, so that the nested task tool captures the * correct parent agent context for CAPI header propagation. */ declare type SubAgentToolConfigOverrides = Pick; /** * Produces a human-readable summary of a tool call's intention. * * Resolution order: * 1. `tool.summariseIntention(args)` when the tool instance is available * 2. Shell-specific fallback: `description || command` for shell tools * 3. Generic fallback: first non-empty string among common arg field names * 4. `null` — caller decides what to show * * @param toolName The name of the tool being called * @param args The raw arguments passed to the tool * @param tools Optional list of available tools (accepts both {@link Tool} and {@link ToolMetadata}) */ 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/models_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}. */ 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.5", "gpt-5.4", "gpt-5.3-codex", "gpt-5.4-mini", "gpt-5-mini", "gemini-3.1-pro-preview", "gemini-3.5-flash"]; 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; mcpServers?: Record; 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; }; /** 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`. */ 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_2[], cwd: string, consolidationContext?: ConsolidationContext, options?: { splitSystemMessage?: boolean; }) => Promise; /** * 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; /** * 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; } /** * 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. */ content: string; /** * Structured system message blocks for providers that support split cache * breakpoints. When provided, `content` remains the flattened fallback. */ 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; /** Schema for the `SystemNotificationAgentCompleted` type. */ 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"; /** Schema for the `SystemNotificationAgentIdle` type. */ 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 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"; } /** Schema for the `SystemNotificationInstructionDiscovered` type. */ 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; /** Schema for the `SystemNotificationNewInboxMessage` type. */ 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"; } /** Schema for the `SystemNotificationShellCompleted` type. */ 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"; } /** Schema for the `SystemNotificationShellDetachedCompleted` type. */ 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"; /** Schema for the `TaskAgentInfo` type. */ 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"; } /** Schema for the `TaskAgentProgress` type. */ 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"; /** Schema for the `TaskInfo` type. */ 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; /** Schema for the `TaskProgressLine` type. */ 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 readonly tasks; 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; 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(executeAgent: () => Promise): Promise; /** * 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; /** * 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; /** * List tasks with optional filters. Every agent can see every task. */ list(options?: TaskListOptions): TaskEntry[]; listAgents(options?: AgentListOptions): ListedAgentTask[]; findAgent(agentId: string, options?: AgentLookupOptions): AgentLookupResult | undefined; private getAgentEntries; private getRegistryAgentEntries; private findAnchorAgent; private withAgentRelation; private getAllAgentEntries; private getDescendantAgentEntries; /** * 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; /** * 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; /** * 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, options?: { modelOverride?: string; toolCallId?: string; ownerId?: string; parentId?: string; preGeneratedAgentId?: string; executionMode?: AgentExecutionMode; }): 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>; /** * Append a line to a service's bounded log, evicting the oldest lines (and * bumping {@link ServiceTaskFields.droppedLogCount}) once the cap is hit. * Keeping the cap here — rather than at the reporter or UI — bounds memory * for chatty servers that forward their whole log for the life of the * session, while preserving absolute read cursors across eviction. */ private pushServiceLogLine; /** * 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 * `` 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; /** * 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; /** * 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; /** 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): 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; /** * 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; /** Flush any in-progress active period into the accumulated total. */ private finalizeActiveTime; private releaseAgentLimiterSlot; /** Resolve all waitForAgents() waiters blocked on a given task. */ private resolveStatusWaiters; /** * Recursively cancel a task and all its descendants. */ private cancelRecursive; /** * 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; } /** Schema for the `TaskShellInfo` type. */ 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"; /** Schema for the `TaskShellProgress` type. */ 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; /** * 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; /** * The name of the telemetry event associated with the emitted runtime event. */ metrics: Record; }; /** * 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; /** Restricted properties (may contain sensitive data like PII, file paths, ...) */ restrictedProperties?: Record; /** Numeric metrics */ metrics?: Record; /** 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 = { kind: "telemetry"; telemetry: EventTelemetry; }; 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; /** * 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; }, 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; } declare type TelemetryTags = { [key: string]: string; }; export declare type TerminalContent = WireTypes.TerminalContent; declare interface TestInjectedScopedMemories { repoMemories?: string; userMemories?: string; repoName?: string; userLogin?: string; /** * Test-only: store_memory tool definition version to inject. When set to a * scope-aware version (>= 1.1.0), `getMemoryTools` registers the scope-aware * `store_memory` schema, allowing evals to assert that the agent picked the * correct memory scope. Has no effect on production paths. */ storeToolDefinitionVersion?: string; } 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; 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; }; /** Schema for the `TokenAuthInfo` type. */ 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-07-01). `max_prompt_tokens` is the prompt * token budget; the total context window is `max_prompt_tokens + max_output_tokens`. * * The `max_prompt_tokens` and `cache_read_price` fields were named `context_max` * and `cache_price` in API versions 2026-06-01 through 2026-06-30 and were * renamed by github/copilot-api#34988. */ declare type TokenPriceTier = { input_price?: number; output_price?: number; /** Price for reading cached tokens (was `cache_price` before 2026-07-01). */ cache_read_price?: number; /** * Price per billing batch of cache-write (cache creation) tokens at this * tier. Omitted when the model does not charge for cache writes. */ cache_write_price?: number; /** * Prompt token budget for this tier (was `context_max` before 2026-07-01). * The model reserves `max_output_tokens` on top, so the total context window * equals `max_prompt_tokens + max_output_tokens`. */ max_prompt_tokens?: number; }; export declare function toNativeProcessorHook(hook: NativeDeclarativeHook): NativeProcessorHook; declare type Tool = { name: string; namespacedName: string; /** Original/display name for the MCP server */ mcpServerName?: string; /** Raw MCP tool name as reported by the server. */ mcpToolName?: string; /** Intended for UI and end-user contexts — optimized to be human-readable * and easily understood, even by those unfamiliar with domain-specific terminology. * * If not provided, the name should be used for display (except for Tool, where * annotations.title should be given precedence over using name, if present). */ title: string; description: string; input_schema: ToolInputSchema; readOnly?: boolean; /** When true, tool output should always be displayed expanded in the CLI timeline. */ displayVerbatim?: boolean; safeForTelemetry: { name: boolean; inputsNames: boolean; }; filterMode?: ContentFilterMode; disableSecretMasking?: boolean; /** Tool-search deferral policy inherited from the server's `deferTools` config. */ defer?: "auto" | "never"; /** * MCP Apps (SEP-1865) tool metadata, populated from the server's * `tools/list` response when the tool declares an `_meta.ui` block. * Only carried when MCP Apps is enabled for the session. */ _meta?: { ui?: McpUiToolMeta; }; /** MCP task support level declared by the tool via `execution.taskSupport`. */ taskSupport?: "required" | "optional" | "forbidden"; }; declare type Tool_2 = ToolMetadata & { /** * A human readable string summary of what this command intends to do if executed. * * If not set, no summarised intention should be assumed by the caller. */ summariseIntention?: (input: unknown) => string; callback: CallbackT; shutdown?: ToolShutdown; }; /** Schema for the `Tool` type. */ declare interface Tool_3 { /** 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; } /** * @param input The input to the tool * @param options Options for the tool, includes the standard `ToolCallbackOptions` as well as any additional options that were set for the tool in settings. */ declare type ToolCallback = (input: unknown, options?: ToolCallbackOptions) => Promise; declare type ToolCallbackOptions = { /** * The ID of the LLM tool call which initiated this tool invocation. */ toolCallId: string; truncationOptions?: { /** * The number of tokens that the tool's response should ideally be limited to. */ tokenLimit: number; /** * A function to count the number of tokens in a string. */ countTokens: (input: string) => number; }; /** * A client that the tool can use to make chat completion calls. */ client?: Client; /** * Other options specific to the tool. Passed in from settings. */ toolOptions?: OptionsT; /** * Global runtime settings. */ settings: RuntimeSettings; /** * An optional AbortSignal to allow cancellation of tool execution. */ abortSignal?: AbortSignal; /** * Options for handling large tool outputs. */ largeOutputOptions?: LargeOutputOptions; /** * Pre-computed diff snapshot, shared across tools in a single validation pass. * When present, tools should use this instead of running their own git diff commands. */ repoChangeSet?: RepoChangeSet; multiTurnConfig?: { /** The background agent registry to check for messages */ registry: TaskRegistry; /** The agent ID in the registry */ agentId: string; /** * Optional hook fired after a follow-up message is dequeued and before the * next turn runs. Persistent sidekicks use this to advance per-turn state. */ onTurnStart?: (message: AgentMessage) => void | Promise; /** * Optional formatter for the continuation prompt, replacing the default * delivery formatting (e.g. to match a sidekick's first-turn envelope). */ formatContinuationPrompt?: (message: AgentMessage) => string; }; /** Agent task ID in the TaskRegistry for the current multi-turn agent. */ taskRegistryAgentId?: string; /** * The model's original tool-call `arguments` as raw JSON text, when this * invocation originated from a model tool call. * * Rust-backed builtin tools forward this text straight to the runtime so the * arguments are parsed exactly once in Rust, without rebuilding and * re-serializing a JavaScript object. It is absent for programmatic callers * that invoke a tool callback with an in-memory object. */ rawArgumentsJson?: string; }; declare interface ToolChoice { mode?: "required" | "auto" | "none"; } declare type ToolConfig = { /** * Where a tool should initially set its current working directory. */ location: string; /** * Session ID for the current session. Used by hooks. */ sessionId?: string; /** * When set, identifies a parent session whose trajectory subagents * should consolidate (e.g., when this session is a detached headless * child spawned on the parent's interactive shutdown). Mirrors * {@link Session.detachedFromSpawningParentSessionId}; flows into `ConsolidationContext` * so the rem-agent reads the parent's turns/checkpoints rather than * this session's empty trajectory. */ detachedFromSpawningParentSessionId?: string; /** * Path to the session transcript (events.jsonl file). Used by hooks. */ transcriptPath?: string; /** * Timeout in milliseconds. */ timeout?: number; /** * Optional callback for progress events. */ callback?: IAgentCallback; /** * Native Rust callback runtime. New callback behavior should flow through this * handle instead of TypeScript callback objects. */ callbackRuntime?: CallbackRuntimeSink; /** * Whether to push changes to remote. */ push?: boolean; /** * The branch name our work will be done within. */ branchName?: string; /** * Use separate tools for file editing. * @default false */ splitEditingTools?: boolean; /** * Whether view tool output should omit line number prefixes. * @default false */ noViewLineNumbers?: boolean; /** * The style of editing tools to use. Apply patch uses the Codex Apply Patch tool to apply changes to the file. * @default "replace" */ editingToolsStyle?: "replace" | "apply-patch"; /** * Grep tool name * @default "grep" */ grepToolName?: string; /** * Glob tool name * @default "glob" */ globToolName?: string; /** * A callback that is called when a tool call is in progress, allowing for * partial output to be sent back to the user. */ toolPartialResultCallback?: ToolPartialOutputCallback; /** * A callback that is called when a tool reports progress (e.g., from MCP servers). */ toolProgressCallback?: ToolProgressCallback; /** * Factory to create a sub-agent callback that properly emits session events. * Used by tools like the task tool that run sub-agents. * * The optional `isByokExecutor` hint tells the bridge that the calling * executor has resolved a BYOK model for this sub-agent. The bridge uses it * to attribute a multiplier of 0 to the sub-agent's model calls even when * the parent session's own selection is a CAPI model (i.e. cross-provider * sub-agent invocations). */ createSubAgentCallback?: (agentId: string, options?: { isByokExecutor?: boolean; }) => IAgentCallback; /** * Custom API provider configuration (BYOK - Bring Your Own Key). * When set, sub-agents use this provider instead of defaulting to Copilot API authentication. * Propagated from the parent session's provider config. */ 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; /** The current interaction ID (GUID), shared across parent and sub-agents for the same user message. */ interactionId?: string; }; /** * List of available models for the current user (based on policy). * Used by tools like the task tool to validate model overrides. */ availableModels?: AvailableModelInfo[]; /** * The parent session's selected model id when it is a registry BYOK model. * Used so that a subagent which *inherits* the session model receives the BYOK * selection id (not the behavior model id embedded in the agent-model setting * string), ensuring the inheriting subagent routes to the same BYOK backend. * Undefined when the session's selected model is a CAPI model. */ sessionModelSelectionId?: string; /** * Whether the current user is on usage-based (token-based) billing. * When `true`, the subagent cost-multiplier guard is bypassed because * subagent usage is billed directly rather than drawn from a quota. */ tokenBasedBilling?: boolean; /** * If the codeql tool should be included. Default is false. */ includeCodeQLTool?: boolean; /** * If the dependency checker tool should be included in security prompt snippets. Default is false. */ includeDependencyChecker?: boolean; /** * If the secret scanning tool should be included in security prompt snippets. Default is false. */ includeSecretScanning?: boolean; /** * Configuration for the shell tool. */ shellConfig?: ShellConfig; /** * Returns the session's current sandbox config, read live at command time. * * The shell tool is constructed once per turn and captures `shellConfig` * (including its `sandbox`) at that point. This getter lets the in-flight * tool honor a mid-turn sandbox change — e.g. the user disabling the * sandbox from a bypass prompt — for the remaining commands of the current * turn, instead of only taking effect on the next turn's tool rebuild. * * When omitted (e.g. direct tool construction in tests), or when it returns * `undefined`, the tool falls back to the static `shellConfig.sandbox` * snapshot so behavior is unchanged. */ getLiveSandboxConfig?: () => SandboxConfig_2 | undefined; /** * Request permission from the permissions service. */ permissions: PermissionsConfig; /** * Options for handling large outputs (used by shell tool for streaming). */ largeOutputOptions?: LargeOutputOptions; /** * Session filesystem for session-scoped file I/O. * Available when running within a session context. */ sessionFs?: SessionFs; /** Session canvas API for renderer-capable sessions. */ canvasApi?: SessionCanvasApi; /** * Optional callback invoked by the `sql` tool when a successful statement * writes to (or schema-modifies) the `todos` or `todo_deps` tables in the * session SQLite database. Used by the runtime to emit the ephemeral * `session.todos_changed` event so SDK clients can refresh their structured * todo-list rendering. Signal only — no payload is supplied. */ onTodosChanged?: () => void; /** * Custom skill directories to search for skills. */ skillDirectories?: string[]; /** * Whether ambient repo/user capability discovery is enabled. */ enableConfigDiscovery?: boolean; /** * Whether embedding-based instruction retrieval is active. * When true, at least one index type is enabled for dynamic retrieval. */ embeddingRetrievalEnabled?: boolean; /** * Set of enabled embedding index types. * Each entry indicates which instruction source should be indexed and * retrieved dynamically via embeddings. Extensible for future index types. * - "skill": enabled when skills count > 25 * - "mcp-server": enabled when deferred MCP instructions exist */ embeddingRetrievalIndexTypes?: Set; /** * Set of skill names that are disabled. */ disabledSkills?: Set; /** * Set of instruction source IDs that are disabled. * Used by sub-agents to respect session-scoped instruction toggles. */ disabledInstructionSources?: ReadonlySet; /** * List of installed plugins from user config. * Used for loading plugin skills. */ installedPlugins?: InstalledPlugin[]; /** * Current working directory for skill traversal. * When provided along with `location` (git root), enables loading skills * from parent directories between cwd and the git root (monorepo support). */ cwd?: string; /** * Remote skills from Job DTO. These are merged with locally * loaded skills, with local taking precedence. */ remoteSkills?: Skill_2[]; /** * Skills loaded for the current session. * Used by sub-agent eager skill injection to resolve skill names to Skill objects. */ loadedSkills?: readonly Skill_2[]; /** * Emits audit metadata for skills that are loaded outside the skill tool lifecycle * (for example, custom-agent configured skills injected directly into context). */ skillInvocationEmitter?: (invocation: SkillInvocation, agentId?: string) => void; /** * User-defined custom agents. If a tool exists which orchestrates the execution of * sub-agents, it should make these agents available for execution. */ customAgents?: SweCustomAgent[]; /** * Built-in subagents excluded by the session/integrator configuration. * Custom agents with the same name remain available. */ excludedBuiltinAgents?: readonly string[]; /** * MCP tools available to whoever is initializing built-in tools. If a tool exists which * orchestrates the execution of sub-agents, it should make these tools available to * those sub-agents. */ mcpTools?: Tool_2[]; /** * Session-level external tools (registered by SDK clients or extensions at runtime). * If a tool exists which orchestrates the execution of sub-agents, it should make * these tools available to those sub-agents. */ externalTools?: Tool_2[]; /** * Filter function to determine if a tool should be enabled. If a tool exists which * orchestrates the execution of sub-agents, it should use this to filter the * tools made available to those sub-agents. */ filterTool?: (tool: ToolMetadata) => boolean; /** * Function to get an MCP server provider for a specific agent. If a tool exists which orchestrates the * execution of sub-agents, it can use this to get MCP server providers for those agents. */ getMcpServerProviderForAgent?: (agentName: string, agentMcpServers: Record) => Promise; /** * Callback invoked when a new file is created. Can be used to refresh file search caches. */ onFileCreated?: (path: string) => void; /** * Callback invoked after a successful file access. Can be used to discover * additional instruction sources near the accessed path. * * @param path The file path that was accessed * @param tool The tool command that triggered the access * @returns Newly discovered instruction sources, or undefined if none were found */ onFileAccessed?: (path: string, tool: string) => Promise; /** * Callback invoked when a tool wants to emit a warning to the session timeline. * Used for non-fatal issues that the user should be aware of. */ onWarning?: (message: string) => void; /** * Function to request user input from the UI (CLI only). * When provided, enables the ask_user tool for interactive clarification. */ requestUserInput?: (request: { question: string; choices?: string[]; allowFreeform?: boolean; }) => Promise<{ answer: string; wasFreeform: boolean; }>; /** * Function to request structured form-based input from the UI via the elicitation framework. * When provided alongside the ASK_USER_ELICITATION feature flag, replaces the standard ask_user tool. */ requestElicitation?: (request: ElicitRequestFormParams) => Promise; /** * Path to the workspace directory for infinite sessions. * Used by tools that need to access session-specific storage (e.g., SQL tool). * Only available when INFINITE_SESSIONS feature flag is enabled. */ workspacePath?: string; /** * Feature flags for the current session. * Used by tools to check experimental/staff features. */ featureFlags?: FeatureFlags; /** * Whether the user's enterprise/org policy allows session search features. * When false, cloud session store queries and session sync prompts are disabled. * Derived from the `cloud_session_storage_enabled` field on the /copilot_internal/user response. */ cloudSessionStorageEnabled?: boolean; /** * Feature flag service for accessing ExP-driven flags. * Used by tools that need to await ExP assignments before checking flags. */ featureFlagService?: IFeatureFlagService; /** * Callback for subagentStart hook. Called when a subagent is about to be spawned. * Returns additionalContext to inject into the subagent. */ onSubagentStart?: (input: { sessionId: string; transcriptPath: string; agentName: string; agentDisplayName?: string; agentDescription?: string; }) => Promise<{ additionalContext?: string; } | undefined | void>; /** * Callback for subagentStop hook. Called when a subagent is about to complete. * Returns a decision to block (continue) or allow the stop. */ onSubagentStop?: (input: { sessionId: string; transcriptPath: string; agentName: string; agentDisplayName?: string; }) => Promise<{ decision?: "block" | "allow"; reason?: string; } | undefined | void>; /** * Builds a HooksProcessor for the legacy sub-agent executor path so inner * tool calls run user preToolUse / postToolUse hooks. Returns undefined when * no hooks are configured. Session-based sub-agents build their own hook * pipeline inside the child LocalSession and do not consume this factory. */ createSubagentHooksProcessor?: (toolCallId: string) => Promise; /** * 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; /** * Languages that have LSP support available in the current project. * Used by sub-agents to include LSP guidance in their prompts. */ lspLanguages?: string[]; /** * Whether automatic completion notifications are enabled for background tasks. * When true, the agent will be notified when background agents or shell commands complete. * This should only be enabled in environments that support immediate prompts (e.g., CLI). */ backgroundTaskNotificationsEnabled?: boolean; /** * Removes queued system notifications that have already been consumed by a blocking read tool. */ consumePendingSystemNotifications?: (predicate: (kind: SystemNotificationKind) => boolean) => void; /** * Whether this tool config is for a subagent (not the top-level agent). * When true, background task mode and multi-turn registry paths are disabled * to prevent notifications from leaking to the parent session. */ isSubagent?: boolean; /** * Content exclusion service for filtering files based on organization policies. * May be undefined when the service is not yet initialized (e.g., before auth). */ contentExclusionService?: ContentExclusionService; /** * Live accessor for the content exclusion service. Prefer this over * {@link contentExclusionService} in tool contexts that outlive a single turn (e.g. the * persistent shell tool context): the session disposes and lazily recreates the service on * auth/token refresh, so a value snapshot can become a disposed instance that fails closed and * blocks every command. When wired, the accessor returns the session's current service (or * undefined when none is active); the {@link contentExclusionService} snapshot is only used as a * fallback when no accessor is provided (e.g. direct constructions or tests). */ getContentExclusionService?: () => ContentExclusionService | undefined; /** * Tools-based rewind capture sink. When present, editing tools (and the shell * tool, best-effort) are wrapped so the file-snapshot store records the * pre/post state of every file they mutate, enabling precise file restore on * `/rewind`. Set by the CLI and resolved per session id, so sub-agents — which * reuse their parent's session id — capture into the parent's store and have * their edits reverted by rewinding the parent turn. Undefined disables * capture (e.g. REWIND_V2 off, or no sink registered for the session). */ fileSnapshotCapture?: FileSnapshotCapture; /** * Unified registry for tracking all background tasks (agents and shells). */ taskRegistry?: TaskRegistry; /** Agent task ID in the TaskRegistry for the current multi-turn agent. */ taskRegistryAgentId?: string; /** * Session-owned inbox for asynchronous context from sidekick agents. */ inbox?: Inbox; /** * Returns whether any sidekick agents are registered. * Awaits initialization so the answer is final before tools are built. */ hasSidekickAgents?: () => Promise; /** * Callback for publishing inbox entries from sidekick agents. * When set, the `send_inbox` tool is created in the tool pipeline. * The callback encapsulates per-launch state: send count, freshness checks, inbox write. */ sendInboxPublisher?: SendInboxPublisher; /** * Per-session dynamic-context-board state. When present, the `context_board` * tool is created in the tool pipeline. Inherited by subagents through the * task tool's effective config so subagents that allowlist `context_board` * can read/write the shared board. */ dynamicContext?: { store: SessionStore; repository: string; branch: string; }; /** * Shell tool context for this session, created lazily by getShellTools. */ shellContextHolder?: ShellContextHolder; /** Generation of the sandbox-bound shell context captured by this tool config. */ shellContextGeneration?: number; /** * Shared mutable cache for Memory API results, passed from the * session into every ToolConfig. */ memoryApiCache?: MemoryApiCache; /** * Client name to report in LSP sessions. */ lspClientName?: string; /** * Directory path for logging raw shell output data. * When set, each shell session writes a log file to this directory. */ shellLogsPath?: string; /** * Optional emitter for telemetry events from tools that operate outside the * normal tool result lifecycle (e.g., memory retrieval during prompt construction, * or aggregate metrics at shutdown). Wired to session.sendTelemetry() in CLI. * * When both callback (CCA) and telemetryEmitter (CLI) are available on a tool, * callback.progress() takes precedence. */ telemetryEmitter?: (event: TelemetryEvent_2) => void; /** * Whether LLM completions should use streaming. * Propagated from the parent session so sub-agents respect the session's streaming config. * Defaults to true when not set. */ enableStreaming?: boolean; /** * Runtime context for filtering builtin agents (e.g., "cli", "cca", "sdk"). * When set, only agents whose `contexts` include this value are available. */ agentContext?: AgentContext; /** Current sub-agent nesting depth (0 = top-level session). */ subAgentDepth?: number; /** * Agent executors for running subagents. Set during tool initialization * and used by `Session.startSubagent()` to delegate agent execution * without duplicating the routing logic in the task tool. */ agentExecutors?: AgentExecutors; /** * Returns the parent session's current subagent settings. Tools read through * this provider so live `/subagents` picker changes can take effect without * rebuilding the tool list. Callers with only a snapshot should adapt it as * `() => snapshot` at the boundary instead of adding a parallel settings field. */ getSubagentSettings?: () => UserSettings["subagents"]; /** Returns the parent session's current model for `subagents.*.model: "inherit"`. */ getParentModel?: () => string | undefined; /** Returns the parent session's current reasoning effort for `subagents.*.effortLevel: "inherit"`. */ getParentReasoningEffort?: () => string | undefined; /** Returns the parent session's current context tier for `subagents.*.contextTier: "inherit"`. */ getParentContextTier?: () => ContextTier_3 | undefined; /** * Factory to create an ephemeral LocalSession configured as a subagent. * Set by the parent session in buildSettingsAndTools(). Used by SessionAgentExecutor * to create child sessions that inherit auth, working dir, depth, interaction type, etc. */ createSubagentSession?: (agentId: string, options?: SubagentSessionOptions) => LocalSession; /** * Schedule management API. When present, the `manage_schedule` * tool is created in the CLI toolset so the model can create/list/stop * recurring prompts. */ scheduleApi?: ScheduleApi; /** * CAPI model list from the parent session, used for model metadata lookups * (e.g., model family, vendor, CAPI-reported reasoning efforts). * Populated from `Session.getModelListCache()` when building tools. */ models?: readonly Model[]; }; /** * Result for when a tool call is denied due to content exclusion policy. */ declare function toolDeniedByContentExclusionResult(filePath: string, message: string): Readonly; declare function toolDeniedByRulesResult(rules: ReadonlyArray, customMessage?: string): Readonly; declare const toolDeniedWithoutUserRequest: Readonly; declare interface ToolDescriptor { name: string; title?: string; description?: string; inputSchema?: unknown; outputSchema?: unknown; annotations?: Record; execution?: Record; _meta?: Record; [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. */ 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; /** 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 */ 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; /** 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; /** 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 { /** Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. */ ui?: ToolExecutionCompleteToolDescriptionMetaUI; } /** Schema for the `ToolExecutionCompleteToolDescriptionMetaUI` type. */ 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 { /** Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. */ ui?: ToolExecutionCompleteUIResourceMetaUI; } /** Schema for the `ToolExecutionCompleteUIResourceMetaUI` type. */ declare interface ToolExecutionCompleteUIResourceMetaUI { /** Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. */ csp?: ToolExecutionCompleteUIResourceMetaUICsp; domain?: string; /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. */ permissions?: ToolExecutionCompleteUIResourceMetaUIPermissions; prefersBorder?: boolean; } /** Schema for the `ToolExecutionCompleteUIResourceMetaUICsp` type. */ declare interface ToolExecutionCompleteUIResourceMetaUICsp { baseUriDomains?: string[]; connectDomains?: string[]; frameDomains?: string[]; resourceDomains?: string[]; } /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissions` type. */ declare interface ToolExecutionCompleteUIResourceMetaUIPermissions { /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. */ camera?: ToolExecutionCompleteUIResourceMetaUIPermissionsCamera; /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. */ clipboardWrite?: ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite; /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. */ geolocation?: ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation; /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. */ microphone?: ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone; } /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsCamera` type. */ declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsCamera { [key: string]: unknown; } /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite` type. */ declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite { [key: string]: unknown; } /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation` type. */ declare interface ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation { [key: string]: unknown; } /** Schema for the `ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone` type. */ 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 */ 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 { /** Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. */ ui?: ToolExecutionStartToolDescriptionMetaUI; } /** Schema for the `ToolExecutionStartToolDescriptionMetaUI` type. */ 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"; /** * JSON Schema object for tool input parameters. * * Tool input schemas are always objects (type: "object") since function calling * requires named parameters. This type is compatible with: * - OpenAI's `FunctionParameters` (`{ [key: string]: unknown }`) * - Anthropic's `Tool.InputSchema` (`{ type: 'object'; [k: string]: unknown }`) * * When accessing specific schema properties (e.g., `properties`, `required`), * explicit type narrowing or assertions are required. */ 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_3[]; } /** * 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; }; /** * Lightweight tool metadata used for system message building, token counting, and display. * Contains only the declarative properties of a tool, without execution callbacks. * * This is the base type that Tool extends. Functions that only need tool metadata * (like cliSystemMessage) should accept ToolMetadata[] to allow passing either * ToolMetadata[] or Tool[] without conversion. */ declare type ToolMetadata = { /** * Name used to identify the tool in prompts and tool calls. */ name: string; /** * Optional namespaced name for the tool used for declarative filtering of tools. * e.g.: "playwright/navigate" */ namespacedName?: string; /** * Optional MCP metadata. * These are only set for MCP-backed tools and are used for telemetry/logging. * * Note: `mcpServerName` is a display/original name and may contain "/". */ mcpServerName?: string; mcpToolName?: string; /** * Where this tool came from. Always set — required so the compiler enforces that * every tool registration site declares its source. */ source: ToolSource; /** Intended for UI and end-user contexts — optimized to be human-readable * and easily understood, even by those unfamiliar with domain-specific terminology. * * If not provided, the name should be used for display (except for Tool, where * annotations.title should be given precedence over using name, if present). */ title?: string; /** * Description of what the tool does. */ description: string; /** * JSON Schema for the tool's input. * Required for function tools, optional for custom tools. */ input_schema?: ToolInputSchema; /** * Optional instructions for how to use this tool effectively. * These instructions will be included in the system prompt's section. */ instructions?: string; /** * When true, marks this tool as deferred for tool search. * Deferred tools are sent to the model with `copilot_defer_loading: true` * and are not loaded into the model's context until discovered via a tool search tool. * See: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool */ deferLoading?: 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"; /** * The type of the tool. Defaults to "function" if not specified. * - "function": Standard function tool with JSON Schema input * - "custom": Custom tool with grammar-based input format */ type?: "function" | "custom"; /** * The input format for custom tools. Only used when type is "custom". */ format?: CustomToolInputFormat_2; /** * Whether calling this tool should terminate the agent loop. * When true, the model will not be called again after this tool executes. */ isTerminal?: boolean; /** * When true, the tool's output should always be displayed expanded (verbatim) * in the CLI timeline, similar to how local shell tool output is shown. * Set from the MCP tool annotation `displayVerbatim`. */ displayVerbatim?: boolean; /** * Indicates whether the tool is read-only. * Set from MCP tool annotations (`readOnlyHint`) when available. */ readOnly?: boolean; /** * Whether or not information about this tool is safe to send to telemetry without obfuscation. * - If `true`/`false`, then it will be assumed that all such information is safe/unsafe. * - If an object, then safety is determined per property. */ safeForTelemetry?: { name: boolean; inputsNames: boolean; } | true; /** * MCP Apps (SEP-1865) tool metadata. Carries `_meta.ui` (resourceUri, * visibility) for tools backed by MCP servers that opt into the UI extension. * Only set when MCP Apps is enabled for the session. */ _meta?: { ui?: McpUiToolMeta; }; }; declare type ToolPartialOutputCallback = (callId: string, output: string) => void; declare type ToolProgressCallback = (callId: string, progressMessage: string) => void; /** * Result for when the user explicitly rejects a permission request, optionally with feedback * on what they'd like the tool to do differently. */ declare function toolRejectedByUserResult(feedback?: string): Readonly; declare type ToolResult = string | ToolResultExpanded; declare interface ToolResultContent { type: "tool_result"; toolUseId: string; content?: CallToolResultContent[]; structuredContent?: unknown; isError?: boolean; _meta?: Record; } declare type ToolResultExpanded = { /** * The result to be given back to the LLM. * * If @see sessionLog is omitted, then this will be used as the session log. */ textResultForLlm: string; /** * Base64-encoded image or resource content returned to the LLM. */ binaryResultsForLlm?: BinaryResult[]; /** * The execution outcome of the tool call. * - `success`: The tool executed successfully and produced a valid result. * - `failure`: The tool encountered an error or did not produce a valid result. * - `timeout`: The tool was aborted because it exceeded its time budget. * - `rejected`: The tool call was rejected either because the user didn't want this call, or a previous dependent one. * - `denied`: The tool call was denied because the permissions service said no. */ resultType: "success" | "failure" | "timeout" | "rejected" | "denied"; /** * If there was any sort of error that caused the tool to fail, then a string representation of the error. Typically * only set if {@link resultType} is `'failure'`. */ error?: string; /** * Specific telemetry for the tool. Will be sent back to the server by the agent. */ toolTelemetry?: { properties?: TelemetryT["properties"]; restrictedProperties?: TelemetryT["restrictedProperties"]; metrics?: TelemetryT["metrics"]; }; /** * Well-formatted (typically Markdown) string that can be used to display the input/output of the tool invoked. * * (Optional) If omitted, the text result for the LLM will be used as the session log. */ sessionLog?: string; /** * When true, skips the large output processing that would normally write * large results to a temp file. Used when the caller explicitly requested * the full output (e.g., forceReadLargeFiles=true on the view tool). */ skipLargeOutputProcessing?: boolean; /** * User messages to inject into the conversation history after this tool result. * These messages are added to the conversation and sent to the model, but can be * filtered from the timeline display based on their source. * * Use case: Skills inject their full content as user messages so the model * treats them as instructions to follow, while keeping the timeline clean. */ newMessages?: InjectedUserMessage[]; /** * Structured content blocks from tool execution. * Contains rich content like text, images, audio, and resources in their native format. * Can be populated by any tool (MCP tools, bash, etc.) that returns structured content. */ contents?: ContentBlock[]; /** * Tool references returned by a tool search tool. * When set, the tool result message content will be an array of * `{ type: "tool_reference", tool_name: "..." }` objects instead of plain text. * This tells the model which deferred tools are now available for use. */ toolReferences?: string[]; /** * Provider-neutral sources this tool makes available to the model as citable content * (e.g. web-search results). When set, the Anthropic request builder materializes these into * `search_result` content blocks so the model can return native citations; the data is also * persisted on the `tool.execution_complete` event so it survives session resume. */ citableSources?: CitableSource[]; /** * Information about a skill invocation. Set by the skill tool when a skill is * successfully loaded. The session uses this to emit a skill.invoked event * for tracking skills across compaction. * @internal */ skillInvocation?: SkillInvocation; /** * MCP Apps (SEP-1865) UI resource fetched alongside the tool result. * Populated by the MCP transport when the invoked tool has * `_meta.ui.resourceUri` and the auto-fetch succeeded. Hosts render this * inside a sandboxed iframe. */ uiResource?: McpUiResource; /** MCP `CallToolResult._meta`, forwarded verbatim. Populated for MCP tools when `FIDES_IFC` is on. */ mcpMeta?: Record; /** * MCP `CallToolResult.structuredContent`, forwarded verbatim. * * Preserved as a standalone object (separate from {@link textResultForLlm}) * so SDK / MCP App consumers can use the structured payload directly rather * than parsing it back out of the flattened text. Populated for MCP tools * whose result carries `structuredContent`. */ structuredContent?: unknown; }; declare namespace tools { export { isToolResultExpanded, buildToolCallbackOptions, getGrepToolNameFromTools, getToolSource, getMcpInfo, liveSandboxFromConfig, getRemovedToolsByName, getAddedToolsByName, getToolNamesFromHistory, summarizeToolCall, AvailableModelInfo, FileEditedMetrics, FileEditedRestrictedProperties, InjectedUserMessage, ToolResultExpanded, SkillInvocationTrigger, SkillInvocation, RejectedToolResult, DeniedToolResult, ToolResult, BinaryResult, ToolCallbackOptions, ToolCallback, ToolShutdown, ToolPartialOutputCallback, ToolProgressCallback, ToolInputSchema, CustomToolInputFormat_2 as CustomToolInputFormat, ToolSource, ToolMetadata, Tool_2 as Tool, CUSTOM_TOOL_NAMES, MemoryApiCache, ShellContextHolder, ToolConfig, SubAgentToolConfigOverrides, stubAssessScriptSafety, PossiblePath, PossibleUrl, AssessedCommand, SafetyAssessment, ShellInitProfile, ShellConfig, ShellType, createToolSet, localShellToolName, createAskUserTool, AskUserToolName, AUTOPILOT_ASK_USER_RESPONSE, AskUserRequest, AskUserResponse, RequestUserInputFn, createCanvasTools, isCcaUseTsAutofindEnabled, CODE_REVIEW_TOOL_NAME, CODE_REVIEW_FF_NAME, CODE_REVIEW_DISABLE_FF_NAME, CCA_USE_TS_AUTOFIND_FF_NAME, isCodeReviewFeatureEnabled, CREATE_PULL_REQUEST_TOOL_NAME, createPullRequestInputSchema, CreatePullRequestInput, createPullRequestToolDescription, createPullRequestToolInstructions, createPullRequestTool, FETCH_DOCUMENTATION_TOOL_NAME, fetch_copilot_cli_documentation, isLargeOutputEnabled, shouldWriteToFile, formatBytes, generateLargeOutputMessage, writeResultToFile, processLargeOutput, buildLargeOutputOptions, registerTempFile, cleanupTempFiles, getCreatedTempFiles, 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, createLSPTool, createLSPRefactorTools, toolDeniedByRulesResult, getToolDeniedWithoutUserRequest, toolRejectedByUserResult, toolDeniedByContentExclusionResult, handlePermissionResult, alwaysApproveRequestPermissionFn, llmToolRejectionMessage, toolDeniedWithoutUserRequest, PermissionResultMessages, HandlePermissionResultOptions, REPLY_TO_COMMENT_TOOL_NAME, replyToCommentInputSchema, ReplyToCommentInput, reply_to_comment, handleProgressReport, REPORT_PROGRESS_TOOL_NAME, REPORT_PROGRESS_ONLY_PUSH_FEATURE_FLAG, reportProgressInputSchema, ReportProgressInput, reportProgressPushOnlyToolDescription, reportProgressLegacyToolDescription, report_progress, createSqlTool, SqlToolName, SqlInput, createCloudSessionStoreSqlTool, SessionStoreSqlToolName, CloudSessionStoreSqlInput, splitSqlStatements, isWriteToFileStrReplaceEditorCommand, doesStrReplaceEditorArgsWriteContentInclude, isStrReplaceEditorCall, getStrReplaceEditorArgsOrNull, readDirectoryListing, handleViewCommand, VIEW_TOOL_NAME, INSTRUCTION_DISCOVERY_MESSAGE_SOURCE, StrReplaceEditorOptions, StrReplaceEditorTelemetry, StrReplaceEditorResult, ViewInput, CreateInput, EditInput, InsertInput, ViewArgs, CreateArgs, StrReplaceArgs, InsertArgs, StrReplaceEditorArgs, StrReplaceEditorShutdownTelemetry, editingTools, str_replace_editor, DirectoryListingResult, isAutopilotContinuationMessage, createTaskCompleteTool, TaskCompleteToolName, AUTOPILOT_CONTINUATION_MESSAGE, LARK_AUTOPILOT_CONTINUATION_MESSAGE, claudeModelSupportsToolSearch, gptModelSupportsToolSearch, searchToolNamesByPattern, createToolSearchTool, prepareClientToolSearchInput, resolveIsToolSearchEnabled, resolveIsBuiltinToolSearchEnabled, resolveIsClientToolSearchEnabled, markToolsAsDeferred, clearAllDeferral, clearDeferralForAgentTools, ToolSearchToolName, GITHUB_MCP_SERVER_NAME, BLUEBIRD_MCP_SERVER_NAME, ToolSearchInput, ToolSearchToolOptions, DEFERRED_TOOLS_THRESHOLD, parseTodoCounts, parseTodoEntries, UpdateTodoToolName, TodoEntryStatus, TodoEntry, updateTodo } } declare interface ToolSearchInput { pattern: string; limit?: number; } declare const ToolSearchToolName = "tool_search_tool_regex"; /** * Options for creating the tool search tool. */ declare interface ToolSearchToolOptions { /** * Function that returns the current list of all tools (including deferred ones). * Called each time the model invokes tool_search so the results reflect the latest tool set. */ getAllTools: () => ReadonlyArray; } /** 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; } /** * A callback to be called when the tool is shutting down. Gives the tool * a chance to clean things up, and return a telemetry event (if desired) which * will be emitted by the agent. */ declare type ToolShutdown = () => Promise; /** 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; } /** * Classifies a tool by where it was registered: * - `builtin`: shipped by the runtime * - `mcp`: provided by an MCP server * - `external`: registered by an SDK client via `externalToolDefinitions` * (exposed in the tool-filter wire syntax as `custom:`) */ declare type ToolSource = "builtin" | "mcp" | "external"; /** Schema for the `ToolsUpdatedData` type. */ declare interface ToolsUpdatedData { /** Identifier of the model the resolved tools apply to. */ model: string; } /** Session event "session.tools_updated". */ declare interface ToolsUpdatedEvent { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `ToolsUpdatedData` type. */ 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 interface ToolUseContent { type: "tool_use"; name: string; id: string; input: Record; _meta?: Record; } /** 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"; } /** * 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_2[]): ToolMetadata[]; /** * Resolves OTel trace context for an in-flight MCP tool call. * Returns W3C `traceparent`/`tracestate` headers. * * - **In-process** (`InProcMCPTransport`): injected directly into `callTool` `params._meta`. * - **Out-of-process** (`OutOfProcMCPTransport`): forwarded as `traceContext` in the HTTP * request body to `MCPServer`, which then injects it into `params._meta`. */ 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; send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; close(): Promise; onclose?: () => void; onerror?: (error: Error) => void; onmessage?: (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[]; } /** Schema for the `UIElicitationArrayAnyOfFieldItemsAnyOf` type. */ 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"; } /** Schema for the `UIElicitationFieldValue` type. */ 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; /** 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; /** 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"; } /** Schema for the `UIElicitationStringOneOfFieldOneOf` type. */ 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"; /** Schema for the `UIExitPlanModeResponse` type. */ 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; /** Schema for the `UIExitPlanModeResponse` type. */ 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; /** Schema for the `UIUserInputResponse` type. */ 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; } /** Schema for the `UIUserInputResponse` type. */ 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; export declare interface UpdateOptionsBehavior { emitToolDefinitionsChanged?: boolean; emitSessionLimitsChanged?: 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_2 | 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; /** * 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; }; /** Durable session usage checkpoint for reconstructing aggregate accounting on resume */ declare interface UsageCheckpointData { /** 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"; } /** 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; /** ISO 8601 timestamp when the session started */ sessionStartTime: string; /** Session-wide per-token-type accumulated token counts */ tokenDetails?: Record; /** 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; totalApiDurationMs: number; sessionStartTime: number; codeChanges: CodeChangeMetrics; modelMetrics: Map; 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; } /** Schema for the `UsageMetricsModelMetric` type. */ declare interface UsageMetricsModelMetric { /** Request count and cost metrics for this model */ requests: UsageMetricsModelMetricRequests; /** Token count details per type */ tokenDetails?: Record; /** 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; } /** Schema for the `UsageMetricsModelMetricTokenDetail` 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; } /** Schema for the `UsageMetricsTokenDetail` 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; /** * 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; } /** Smaller inline threshold for user-initiated shell output injected into the next model turn. */ 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; }; /** Schema for the `UserAuthInfo` type. */ 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; readonly canOfferSessionApproval: boolean; readonly warning?: string; readonly requestSandboxBypass?: boolean; readonly requestSandboxBypassReason?: string; }; /** * 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; }; /** * 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; }; /** * 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[]; }; /** 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; }; 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"; /** Schema for the `UserMessageData` type. */ 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". */ declare interface UserMessageEvent_2 { /** Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; /** Schema for the `UserMessageData` type. */ 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; 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"; }; export declare type UserPromptSubmittedHook = Hook; /** * User prompt submitted hook types */ export declare interface UserPromptSubmittedHookInput extends BaseHookInput { prompt: string; } export declare interface UserPromptSubmittedHookOutput { modifiedPrompt?: string; additionalContext?: string; suppressOutput?: boolean; /** * If true, the hook has fully handled the request. The agentic loop will be * skipped and responseContent will be displayed as the assistant's response. */ handled?: boolean; /** * The response content to display when handled is true. Supports markdown. * Required when handled is true. */ responseContent?: string; /** * Optional identifier for the handler (e.g., "typeagent", "custom-router"). * Used for logging and attribution. */ handledBy?: string; /** * If "block", the user prompt is blocked. The prompt should never reach the * model, chat history, or transcript. */ decision?: HookBlockDecision; /** Human-readable explanation for why the prompt was blocked. */ reason?: string; } /** * 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; }; /** * 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; } /** 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; 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; 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; renderMarkdown?: 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; 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; feature_flags?: { enabled?: string[]; [key: string]: unknown; }; skillDirectories?: string[]; disabledSkills?: string[]; disabledMcpServers?: string[]; enabledMcpServers?: string[]; 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; [key: string]: unknown; }; extensions?: { disabledExtensions?: string[]; mode?: "disabled" | "load_only" | "load_and_augment"; [key: string]: unknown; }; enabledPlugins?: Record; extraKnownMarketplaces?: ExtraKnownMarketplaces; strictKnownMarketplaces?: StrictKnownMarketplaces; voice?: { enabled?: boolean; selectedModel?: string; [key: string]: unknown; }; permissions?: { disableBypassPermissionsMode?: string; [key: string]: unknown; }; /** Enterprise-mandated OpenTelemetry configuration (managed settings only). */ telemetry?: ManagedTelemetrySettings; copilotUrl?: string; showReasoning?: boolean; disableAllHooks?: boolean; hooks?: HooksObject; remoteSessions?: boolean; experimental?: boolean; logLevel?: "none" | "error" | "warning" | "info" | "debug" | "all" | "default"; } declare const UserSettings: { home: typeof userSettingsConfigHome; path: typeof settingsFilePath; directoryFiles: (settings?: RuntimeSettings) => Promise; directoryFilesWithMetadata: (settings?: RuntimeSettings) => Promise<{ file: string; mtime: Date; birthtime: Date; }[]>; clearCache: () => void; load: (settings: RuntimeSettings | undefined) => Promise; /** * 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: RuntimeSettings | undefined) => Promise; /** * 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: RuntimeSettings | undefined) => Promise; /** * 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: RuntimeSettings | 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: RuntimeSettings | undefined) => Promise; /** * 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, deleteKeys: readonly string[], settings: RuntimeSettings | undefined) => Promise<"ok" | "invalid">; write: (data: UserSettings, subDir?: string, settings?: RuntimeSettings) => Promise; writeKey: (key: keyof UserSettings, value: UserSettings[keyof UserSettings], subDir?: string, settings?: RuntimeSettings, options?: { refuseOnReadFailure?: boolean; }) => Promise; /** * 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: (key: K, partial: Partial>, subDir?: string, settings?: RuntimeSettings) => Promise; /** * 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: RuntimeSettings | undefined) => Promise; }; declare function userSettingsConfigHome(settings?: RuntimeSettings): 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; } /** 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 = { readonly kind: "approve-once"; } | { readonly kind: "approve-for-session"; readonly approval: SessionApprovalFor; } | { readonly kind: "approve-for-location"; readonly approval: SessionApprovalFor; 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; /** Schema for the `UserToolSessionApprovalCommands` type. */ declare interface UserToolSessionApprovalCommands { /** Command identifiers approved by the user */ commandIdentifiers: string[]; /** Command approval kind */ kind: "commands"; } /** Schema for the `UserToolSessionApprovalCommands` type. */ declare interface UserToolSessionApprovalCommands_2 { /** Command identifiers approved by the user */ commandIdentifiers: string[]; /** Command approval kind */ kind: "commands"; } /** Schema for the `UserToolSessionApprovalCustomTool` type. */ declare interface UserToolSessionApprovalCustomTool { /** Custom tool approval kind */ kind: "custom-tool"; /** Custom tool name */ toolName: string; } /** Schema for the `UserToolSessionApprovalCustomTool` type. */ declare interface UserToolSessionApprovalCustomTool_2 { /** Custom tool approval kind */ kind: "custom-tool"; /** Custom tool name */ toolName: string; } /** Schema for the `UserToolSessionApprovalExtensionManagement` type. */ declare interface UserToolSessionApprovalExtensionManagement { /** Extension management approval kind */ kind: "extension-management"; /** Optional operation identifier */ operation?: string; } /** Schema for the `UserToolSessionApprovalExtensionManagement` type. */ declare interface UserToolSessionApprovalExtensionManagement_2 { /** Extension management approval kind */ kind: "extension-management"; /** Optional operation identifier */ operation?: string; } /** Schema for the `UserToolSessionApprovalExtensionPermissionAccess` type. */ declare interface UserToolSessionApprovalExtensionPermissionAccess { /** Extension name */ extensionName: string; /** Extension permission access approval kind */ kind: "extension-permission-access"; } /** Schema for the `UserToolSessionApprovalExtensionPermissionAccess` type. */ declare interface UserToolSessionApprovalExtensionPermissionAccess_2 { /** Extension name */ extensionName: string; /** Extension permission access approval kind */ kind: "extension-permission-access"; } /** Schema for the `UserToolSessionApprovalMcp` type. */ 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; } /** Schema for the `UserToolSessionApprovalMcp` type. */ 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; } /** Schema for the `UserToolSessionApprovalMemory` type. */ declare interface UserToolSessionApprovalMemory { /** Memory approval kind */ kind: "memory"; } /** Schema for the `UserToolSessionApprovalMemory` type. */ declare interface UserToolSessionApprovalMemory_2 { /** Memory approval kind */ kind: "memory"; } /** Schema for the `UserToolSessionApprovalRead` type. */ declare interface UserToolSessionApprovalRead { /** Read approval kind */ kind: "read"; } /** Schema for the `UserToolSessionApprovalRead` type. */ declare interface UserToolSessionApprovalRead_2 { /** Read approval kind */ kind: "read"; } /** Schema for the `UserToolSessionApprovalWrite` type. */ declare interface UserToolSessionApprovalWrite { /** Write approval kind */ kind: "write"; } /** Schema for the `UserToolSessionApprovalWrite` type. */ 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; }; /** * 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"; }; declare const VIEW_TOOL_LARGE_OUTPUT_THRESHOLD: number; declare const VIEW_TOOL_NAME = "view"; /** Human-readable size hint for the view tool truncation threshold, for use in prompts. */ declare const VIEW_TOOL_SIZE_HINT: string; declare type ViewArgs = ViewInput & { command: typeof VIEW_TOOL_NAME; }; declare type ViewInput = { path: string; view_range?: number[]; forceReadLargeFiles?: boolean; }; /** Current sharing status and shareable GitHub URL for a session. */ declare interface VisibilityGetResult { /** Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. */ shareUrl?: string; /** Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). */ status?: SessionVisibilityStatus; /** Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. */ synced: boolean; } /** Desired sharing status for the session. */ declare interface VisibilitySetRequest { /** Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. */ status: SessionVisibilityStatus; } /** Effective sharing status and shareable GitHub URL after updating session visibility. */ declare interface VisibilitySetResult { /** Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. */ shareUrl?: string; /** Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). */ status?: SessionVisibilityStatus; /** Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. */ synced: boolean; } /** Warning message for timeline display with categorization */ 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; /** 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, AssistantStreamingDeltaEvent_2 as AssistantStreamingDeltaEvent, AssistantTurnEndEvent_2 as AssistantTurnEndEvent, AssistantTurnStartEvent_2 as AssistantTurnStartEvent, AssistantUsageEvent_2 as AssistantUsageEvent, Attachment_2 as Attachment, ToolExecutionCompleteContentAudio as AudioContent, 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, McpAppToolCallCompleteEvent_2 as McpAppToolCallCompleteEvent, McpHeadersRefreshCompletedEvent_2 as McpHeadersRefreshCompletedEvent, McpHeadersRefreshRequiredEvent_2 as McpHeadersRefreshRequiredEvent, McpOauthCompletedEvent as McpOAuthCompletedEvent, McpOauthRequiredEvent as McpOAuthRequestedEvent, 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, 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, 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"; declare type Workspace = z_2.infer; /** * Log message prefix emitted when a session workspace is initialized. * This marker is used by `findSessionLogFiles` to identify which process log * files belong to a given session, so changes here must stay in sync. */ 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; /** * Load workspace metadata from storage. Returns null if the workspace * doesn't exist. */ loadWorkspace(): Promise; /** * Save workspace metadata to storage. Creates parent directories if they * don't exist. */ saveWorkspace(workspace: Workspace): Promise; /** * 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; /** * 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; /** * 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; /** * 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; /** Rename the session (set custom name). */ renameSession(name: string): Promise; /** * Update arbitrary fields on this session's workspace. * Creates the workspace if it doesn't exist yet. */ updateWorkspaceFields(fields: Partial): Promise; /** Delete the workspace and its directory. */ deleteWorkspace(): Promise; /** * 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; /** Load the checkpoint index entries from the index.md file. */ listCheckpoints(): Promise; /** Read a specific checkpoint by number. */ readCheckpoint(checkpointNumber: number): Promise; /** Read the plan content for this workspace. */ readPlan(): Promise; /** Write plan content for this workspace. */ writePlan(content: string): Promise; /** Delete the plan file for this workspace. */ deletePlan(): Promise; /** Check if a plan exists for this workspace. */ planExists(): Promise; /** Read the machine-managed autopilot objective state for this workspace. */ readAutopilotObjective(): Promise; /** 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; /** Check if an autopilot objective state file exists for this workspace. */ autopilotObjectiveExists(): Promise; /** List files in the workspace's files directory. */ listFiles(): Promise; /** * Read a file from the workspace files directory. * @param filePath - Relative path within the files directory */ readWorkspaceFile(filePath: string): Promise; /** * 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; }>; } /** Schema for the `WorkspacesCheckpoints` type. */ 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; } declare const WorkspaceSchema: z_2.ZodEffects; git_root: z_2.ZodOptional; repository: z_2.ZodOptional; host_type: z_2.ZodOptional>; branch: z_2.ZodOptional; name: z_2.ZodOptional; client_name: z_2.ZodOptional; user_named: z_2.ZodOptional; summary_count: z_2.ZodDefault; created_at: z_2.ZodOptional; updated_at: z_2.ZodOptional; remote_steerable: z_2.ZodOptional; mc_task_id: z_2.ZodOptional; mc_session_id: z_2.ZodOptional; mc_last_event_id: z_2.ZodOptional; chronicle_sync_dismissed: z_2.ZodOptional; }, "strip", z_2.ZodTypeAny, { id: string; summary_count: number; cwd?: string | undefined; name?: string | undefined; repository?: string | undefined; branch?: string | undefined; client_name?: string | undefined; host_type?: "github" | "ado" | undefined; created_at?: string | undefined; updated_at?: string | undefined; user_named?: boolean | undefined; git_root?: string | undefined; remote_steerable?: boolean | undefined; mc_task_id?: string | undefined; mc_session_id?: string | undefined; mc_last_event_id?: string | undefined; chronicle_sync_dismissed?: boolean | undefined; }, { id: string; cwd?: string | undefined; name?: string | undefined; repository?: string | undefined; branch?: string | undefined; client_name?: string | undefined; host_type?: "github" | "ado" | undefined; created_at?: string | undefined; updated_at?: string | undefined; user_named?: boolean | undefined; git_root?: string | undefined; summary_count?: number | undefined; remote_steerable?: boolean | undefined; mc_task_id?: string | undefined; mc_session_id?: string | undefined; mc_last_event_id?: string | undefined; chronicle_sync_dismissed?: boolean | undefined; }>, { id: string; summary_count: number; cwd?: string | undefined; name?: string | undefined; repository?: string | undefined; branch?: string | undefined; client_name?: string | undefined; host_type?: "github" | "ado" | undefined; created_at?: string | undefined; updated_at?: string | undefined; user_named?: boolean | undefined; git_root?: string | undefined; remote_steerable?: boolean | undefined; mc_task_id?: string | undefined; mc_session_id?: string | undefined; mc_last_event_id?: string | undefined; chronicle_sync_dismissed?: boolean | undefined; }, unknown>; /** 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; }; /** * Writes a large tool result to a temp file and returns a modified * result with instructions for the LLM. * * The file is written to the configured `options.outputDir` when set, * otherwise to `sessionFs.tmpdir`. When no sessionFs is provided, a local * temp-file fallback is used. */ declare function writeResultToFile(result: ToolResultExpanded, options: LargeOutputOptions): Promise; export { }