import { Event } from "../../../base/common/event.js"; import { CancellationToken } from "../../../base/common/cancellation.js"; import { DisposableStore, IDisposable } from "../../../base/common/lifecycle.js"; import { IChannelClient } from "../../../base/parts/ipc/common/ipc.js"; import type { IObservable, IReader } from "../../../base/common/observable.js"; import { URI } from "../../../base/common/uri.js"; import type { IAgentServerToolHost } from "./agentServerTools.js"; import type { AgentHostClientType } from "./agentHostClientInfo.js"; import type { IAgentHostCredentialSource } from "./agentHostCredentials.js"; import type { IAgentHostProcessExitEvent } from "./agentHostProcessExit.js"; import type { CodexModelProvider, IAgentTurnTelemetryCorrelation, IAgentHostClientTelemetryContext, IAgentProviderSendStageRecorder, IAgentProviderTurnTelemetryContext } from "./agentHostTelemetry.js"; import type { AgentPermissionDecisionSource } from "./meta/agentPermissionResponseMeta.js"; import type { IChatSurfaceMeta } from "./meta/agentChatSurfaceMeta.js"; import type { IAgentChatUsage } from "./meta/agentUsageMeta.js"; import type { IMcpServerConfiguration } from "../../mcp/common/mcpPlatformTypes.js"; import type { AuthenticateTarget, ResolveSessionConfigResult, SessionConfigCompletionsResult } from "./state/protocol/commands.js"; import type { CanvasState } from "./state/protocol/channels-canvas/state.js"; import { type ChatUriFormat } from "./agentHostChatMinting.js"; import { ProtectedResourceMetadata, type BackgroundWork, type Changeset, type ChatInteractivity, type ChatOrigin, type ConfigSchema, type MessageAttachment, type ModelSelection, type AgentSelection, type SessionActiveClient, type SessionOrigin, type ToolCallPendingConfirmationState, type ToolDefinition, ChangesSummary } from "./state/protocol/state.js"; import type { ActionOrigin, AuthRequiredParams, SessionAction, ChatAction, ProgressParams } from "./state/sessionActions.js"; import { ChatInputResponseKind, SessionStatus, type AgentCapabilities, type ClientPluginCustomization, type Customization, type ErrorInfo, type ISessionFolderPickerDecision, type Message, type PendingMessage, type ChatInputAnswer, type SessionMeta, type ToolCallResult, type Turn, type PolicyState } from "./state/sessionState.js"; /** Permission response provenance and its originating client. */ export interface IAgentPermissionResponseContext { readonly selectedOptionId?: string; readonly origin?: ActionOrigin; readonly decisionSource?: AgentPermissionDecisionSource; readonly sandboxPathGrantSaved?: true; } /** Error returned when the Agent Host process cannot be started. */ export declare class AgentHostStartError extends Error { readonly fatal: boolean; constructor(message: string, fatal?: boolean); } /** Reports a provider CWD error after the new directory became irreversible and authoritative. */ export declare class AgentWorkingDirectoryChangedError extends Error { readonly workingDirectory: URI; constructor(workingDirectory: URI, message: string); } export declare function isInvalidUtilityProcessConfigurationMessage(message: string): boolean; export declare function isFatalAgentHostStartError(error: unknown): error is TypeError; export declare function toFatalAgentHostStartError(error: Error): AgentHostStartError; export interface IAgentHostConnection { readonly client: IChannelClient; readonly store: DisposableStore; readonly onDidProcessExit: Event; /** Gracefully shuts down Agent Host providers before the process is disposed. */ shutdown(): Promise; } /** Allows a connection request to join the shared process startup. */ export interface IAgentHostStartRequest { waitUntil(promise: Promise): void; } /** Allows the Agent Host process to join application shutdown. */ export interface IAgentHostShutdownRequest { join(promise: Promise): void; } export interface IAgentHostStarter extends IDisposable { readonly onRequestConnection?: Event; readonly onRequestRestart?: Event; readonly onWillShutdown?: Event; start(): Promise; } /** A network endpoint the agent host suggests probing, listed on {@link IAgentHostNetworkDiagnosticsInfo.endpoints}. */ export interface IAgentHostNetworkEndpoint { readonly name: string; readonly url: string; /** Substring the response body is expected to contain; when set, the probe reads the body and fails the check if it is absent. */ readonly expectedContent?: string; /** HTTP status code the probe treats as success. Defaults to `200` when omitted. */ readonly expectedStatus?: number; } export interface IAgentHostManagedSettingsSnapshot { readonly account?: string; readonly source: "server" | "device" | "client" | "policyHelper" | "mixed" | "none"; readonly serverManaged: boolean; readonly deviceManaged: boolean; readonly clientManaged?: boolean; readonly policyHelperManaged?: boolean; readonly failClosed: boolean; readonly bypassPermissionsDisabled: boolean; readonly permissionsAllowIntersected?: boolean; readonly sandboxEnabledByUndeterminedPolicy?: boolean; readonly managedKeys: readonly string[]; readonly settings?: unknown; /** Sessionless resolution layers; session client contributions and policy-helper execution are not included. */ readonly layers?: readonly { readonly source: string; readonly settings?: unknown; }[]; /** Includes source failures and cache-fallback warnings, independently of failClosed. */ readonly diagnostics?: readonly { readonly path: string; readonly severity: "error" | "warning"; readonly message: string; }[]; } export interface IAgentChatMetadata { readonly chat: URI; readonly startTime: number; readonly modifiedTime: number; readonly project?: IAgentSessionProjectInfo; readonly summary?: string; /** Provider model that should be selected when this chat is restored. */ readonly model?: ModelSelection; /** Activity bits plus the session-scoped {@link SessionStatus.IsRead} / {@link SessionStatus.IsArchived} flags. */ readonly status?: SessionStatus; /** Human-readable description of what the session is currently doing. */ readonly activity?: string; /** All working directories available to the session (index 0 = primary). */ readonly workingDirectories?: readonly URI[]; /** * Aggregate counts (additions / deletions / files) for this session's * changes. Single-folder sessions derive this from the branch changeset; * multi-folder sessions aggregate it across all folders. Mirrors * `SessionSummary.changes`. */ readonly changes?: ChangesSummary; /** * Catalogue of changesets the agent can produce for this chat or session. These are * lightweight summary entries without per-file detail; clients subscribe * to a specific expanded changeset URI for the full file list. Chat metadata * carries chat-owned entries while session metadata carries session-wide entries. */ readonly changesets?: readonly Changeset[]; /** * Side-channel metadata mirroring {@link SessionState._meta}, propagated * to clients via per-session state subscriptions and the root-channel * session summary (the host treats the session-state and session-summary * `_meta` as the same bag). Producers SHOULD use namespaced keys; consumers * MUST ignore unknown keys. Use the typed accessors in `sessionState.ts` * (e.g. `readSessionGitState`, `readSessionGitHubState`) for well-known * slots. */ readonly _meta?: SessionMeta; } /** Identifies metadata reads that may initialize an otherwise lazy provider. */ export interface IAgentChatMetadataOptions { /** A session restore needs authoritative provider data and may start its runtime. */ readonly activation?: "restore"; /** Stable host-owned timestamps a lazy provider may use for passive catalogue metadata. */ readonly registryFallback?: Pick; } /** Provider chat metadata listed together with the session it was listed for. */ export interface IAgentListedChat extends IAgentChatMetadata { readonly session: URI; } /** A provider chat ready to be registered as an Agent Host session. */ export interface IAgentDiscoveredChat extends IAgentListedChat { readonly external: boolean; } /** A fresh provider transcript for a chat being observed without running a host turn. */ export interface IAgentChatHistoryChange { readonly chat: URI; readonly turns: readonly Turn[]; } /** Returns the candidate session URI keys already present in the host registry. */ export type IAgentKnownSessionsFilter = (sessions: readonly URI[]) => Promise>; /** Options for {@link IAgent.startChatDiscovery}. */ export interface IAgentChatDiscoveryOptions { /** The host's startup-frozen gate for publishing adoptable legacy chats. */ readonly migrateLegacyChats: boolean; } /** Lightweight ordered chat metadata for session-list presentation. */ export interface IAgentSessionChatMetadata { readonly chat: URI; readonly summary?: string; readonly kind: "default" | "peer"; readonly origin?: ChatOrigin; readonly interactivity?: ChatInteractivity; /** The chat's own agent when it differs from its session's; absence means the session's agent. */ readonly provider?: string; readonly archived?: boolean; /** Exact chat read state when known; absence means the provider did not supply it. */ readonly isRead?: boolean; readonly changes?: ChangesSummary; /** * The chat's live status from the session catalog, including activity bits. * Absence means the host did not supply it. Clients must not persist the * activity bits, which are only valid while connected. */ readonly status?: SessionStatus; /** Last known modification time of the chat (ms since epoch); client-cache only. */ readonly modifiedTime?: number; /** Last known host-side working directories of the chat (protocol URI strings); client-cache only. */ readonly workingDirectories?: readonly string[]; } export interface IAgentSessionMetadata extends Omit { readonly session: URI; /** Host-advertised agent identity; older cached metadata may omit it. */ readonly provider?: string; readonly origin?: SessionOrigin; readonly chats?: readonly IAgentSessionChatMetadata[]; } export interface IAgentSessionProjectInfo { readonly uri: URI; readonly displayName: string; } export interface IAgentCreateSessionResult extends IAgentCreateChatResult { readonly session: URI; readonly project?: IAgentSessionProjectInfo; /** Opaque provider backing for the session's initial chat, when it has one. */ readonly chat?: IAgentCreateChatResult; /** * The single working directory the provider resolved for this session — its * process root. This may differ from the requested primary (e.g. a * workspace-less session runs in a provider-assigned scratch dir). It is NOT * the full multi-root set: a provider only resolves the one directory its * subprocess launches in. The host assembles the session's set by replacing * the requested primary (index 0) with this value while keeping the requested * tail. Worktree remaps and the fully-resolved set land later, on the first * send, via {@link IAgentMaterializeSessionEvent.workingDirectories}. * `undefined` means the provider did not resolve a directory (the host keeps * the requested set as-is). */ readonly resolvedWorkingDirectory?: URI; /** * `true` when the agent only allocated an in-memory placeholder for this * session (no SDK session, no worktree, no on-disk state). Materialization * happens lazily on the first {@link IAgentChats.sendMessage}, at which point * the agent fires {@link IAgent.onDidMaterializeChat}. The * {@link IAgentService} uses this flag to defer the `sessionAdded` protocol * notification so observers don't see the session in their list until it * has been persisted. */ readonly provisional?: boolean; } /** * Payload of {@link IAgent.onDidMaterializeChat}. Fired when a previously * {@link IAgentCreateSessionResult.provisional} chat has its SDK session, * worktree (if any), and on-disk metadata in place. A provider may fire the * event again when it replaces or rematerializes an already-backed chat; * consumers must treat each event as the chat's latest materialization receipt. */ export interface IAgentMaterializeChatEvent { readonly chat: URI; /** Updated opaque backing for the session chat, when materialization minted it. */ readonly result?: IAgentCreateChatResult; /** * The complete resolved working-directory set (index 0 = the resolved process * root, e.g. a worktree). The host replaces index 0 of the current session set * with this set's index 0 while preserving the rest of the current set — the * resume path can only report the single process cwd, so its tail is owned * by the restored session state. */ readonly workingDirectories: readonly URI[] | undefined; readonly project: IAgentSessionProjectInfo | undefined; } export type AgentProvider = string; export interface IAgentPluginUninstallRequest { readonly name: string; readonly marketplace: string; readonly directSourceId?: string; } /** Provider-owned persisted installation, not a session-effective or client-provided plugin. */ export interface IAgentPluginInstallation extends IAgentPluginUninstallRequest { readonly version?: string; readonly description?: string; readonly verifiedSource?: { readonly repository: string; readonly revision: string; }; readonly iconUrl?: string; } export type AgentExtensionMode = "disabled" | "load_only" | "load_and_augment" | "unknown"; export type AgentExtensionSource = "user" | "project" | "plugin"; export type AgentExtensionStatus = "running" | "disabled" | "failed" | "starting" | "unknown"; /** One executable extension discovered from the provider's persisted or session-effective inventory. */ export interface IAgentExtensionInfo { readonly id: string; readonly name: string; readonly resource?: URI; readonly source: AgentExtensionSource; /** Persisted enabled entries use `unknown`; only a live session can report `running`, `failed`, or `starting`. */ readonly status: AgentExtensionStatus; readonly pluginName?: string; } /** Host-scoped extension inventory and the provider's effective loading mode. */ export interface IAgentExtensionInventory { readonly mode: AgentExtensionMode; readonly extensions: readonly IAgentExtensionInfo[]; } export type AgentCanvasExtensionSource = "user" | "project" | "session" | "plugin" | "unknown"; /** One canvas declaration available to an initialized provider chat. */ export interface IAgentCanvasInfo { readonly canvasId: string; readonly extensionId: string; readonly extensionSource: AgentCanvasExtensionSource; readonly extensionName?: string; readonly displayName: string; readonly description: string; readonly requiresInput: boolean; readonly actionCount: number; } /** `undefined` is unsettled; an array, including an empty one, is authoritative. */ export type AgentCanvasDefinitionSnapshot = readonly IAgentCanvasInfo[] | undefined; /** Opens or focuses one stable canvas instance in an initialized provider chat. */ export interface IAgentCanvasOpenRequest { readonly canvasId: string; readonly extensionId?: string; readonly instanceId: string; } /** Closes one canvas that a live provider chat presents, notifying its canvas provider. */ export interface IAgentCanvasCloseRequest { /** The canvas channel the chat advertised. It identifies one canvas lifetime: reopening a canvas advertises a new channel. */ readonly resource: URI; } export interface IAgentCustomizationInstallationCatalogue { readonly resourceId?: string; readonly itemUrl?: string; readonly displayName: string; readonly description?: string; readonly publisher?: string; readonly version?: string; readonly source: string; } export type IAgentCustomizationInstallation = { readonly installationId: string; readonly mediaType: string; readonly catalogue?: IAgentCustomizationInstallationCatalogue; readonly state: "installed" | "missing" | "error"; readonly errorMessage?: string; } & ({ readonly kind: "skill"; readonly name: string; readonly targetUri?: URI; } | { readonly kind: "mcp"; readonly serverName: string; }); export interface IAgentCustomizationInstallationRequest { readonly mediaType: string; readonly identifier: string; readonly displayName: string; readonly description: string; readonly version?: string; readonly itemUrl?: string; readonly selectionId?: string; readonly catalogIdentity?: string; readonly installation: { readonly kind: "skill"; } | { readonly kind: "mcp"; readonly source?: { readonly kind: "url"; readonly mediaType: "application/mcp-server+json"; readonly url: string; }; } | { readonly kind: "plugin"; } | { readonly kind: "configuredPlugin"; readonly name: string; readonly marketplace: string; }; } export interface IAgentCustomizationMarketplaceSearchRequest { readonly query: string; /** Retrieves an ordered saved feed instead of searching. */ readonly feedId?: string; readonly mediaType?: string; readonly limit: number; readonly cursor?: string; } export interface IAgentCustomizationMarketplaceSearchItem { readonly selectionId: string; readonly identifier?: string; readonly catalogIdentity?: string; readonly iconUrl?: string; readonly categories?: readonly string[]; readonly compatibilityTags?: readonly string[]; readonly kind: "skill" | "mcp" | "plugin"; readonly displayName: string; readonly description?: string; readonly publisher?: string; readonly pluginName?: string; readonly marketplace?: string; readonly marketplaceSource?: string; readonly itemUrl?: string; readonly version?: string; readonly repository?: string; readonly path?: string; readonly connectorIds?: readonly string[]; readonly installCount?: number; readonly installable: boolean; readonly unavailableMessage?: string; } export type IAgentCustomizationMarketplaceSearchResult = { readonly kind: "page"; readonly items: readonly IAgentCustomizationMarketplaceSearchItem[]; readonly nextCursor?: string; } | { readonly kind: "unavailable"; readonly reason: "session" | "unsupported" | "authentication"; }; export type IAgentCustomizationInstallationReview = { readonly operationId: string; readonly action: "install" | "uninstall"; readonly kind: "skill"; readonly displayName: string; readonly description?: string; readonly source: string; readonly target: string; readonly fileCount: number; readonly totalBytes: number; readonly filesModified?: boolean; } | { readonly operationId: string; readonly action: "install" | "uninstall"; readonly kind: "mcp"; readonly displayName: string; readonly serverName: string; readonly target: string; readonly endpoint?: string; readonly command?: string; readonly args?: readonly string[]; readonly env?: Readonly>; readonly configurationFields: readonly string[]; readonly restoresPreviousConfiguration?: boolean; readonly preservesSharedAuthentication?: boolean; } | { readonly operationId: string; readonly action: "install"; readonly kind: "plugin"; readonly displayName: string; readonly description?: string; readonly version?: string; readonly source: string; readonly target: string; readonly fileCount: number; readonly totalBytes: number; readonly installsDisabled: boolean; readonly mcpServerCount: number; }; export type IAgentCustomizationInstallationApplyResult = { readonly kind: "receipt"; readonly installationId: string; } | { readonly kind: "plugin"; readonly name: string; readonly repository: string; readonly ref: string; readonly path: string; }; export interface IAgentPluginInstallRequest { readonly source: string; } /** What retrying did for one plugin that the organization's managed settings require. */ export interface IAgentManagedPluginRetryEntry { /** Plugin spec in `plugin@marketplace` form. */ readonly spec: string; readonly status: "installed" | "updated" | "already_present" | "failed" | "deferred" | "not_required"; /** Why the plugin was not prepared; present for `failed` and `deferred`. */ readonly error?: string; } export interface IAgentPluginMarketplace { readonly name: string; readonly source: string; readonly isDefault: boolean; readonly managed: boolean; readonly available: boolean; } export interface IAgentPluginMarketplaceItem { readonly name: string; readonly description?: string; } export interface IAgentPluginMarketplaceRemoveResult { readonly removed: boolean; readonly dependentPlugins?: readonly string[]; } export interface IAgentPluginMarketplaceRefreshResult { readonly name: string; readonly success: boolean; readonly error?: string; } export type AgentTurnProviderCallState = "notStarted" | "pending" | "resolved" | "rejected"; export type AgentTurnProviderSessionState = "active" | "disconnecting" | "disconnected" | "shutdown"; /** Provider-observed records, not an assertion that every network call reported usage. */ export interface IAgentTokenUsageSummary { readonly model?: string; readonly reasoningEffort?: string; readonly usageScope: "direct-model" | "compaction"; readonly usageStatus: "known" | "partial" | "notReported"; readonly usageRecordCount: number; readonly inputKnownRecordCount: number; readonly outputKnownRecordCount: number; readonly cacheKnownRecordCount: number; readonly knownInputTokens?: number; readonly knownOutputTokens?: number; readonly knownCacheReadTokens?: number; } /** A point-in-time snapshot; missing counters and missing snapshots remain unknown. */ export interface IAgentTurnTokenUsage { readonly summaries: readonly IAgentTokenUsageSummary[]; } export type IAgentTurnDiagnosticSnapshot = { readonly state: "available"; readonly providerCallState: AgentTurnProviderCallState; readonly providerTurnStarted: boolean; readonly providerSessionState: AgentTurnProviderSessionState; } | { readonly state: "missingChat" | "missingTurn"; }; /** Well-known agent provider id for the Claude agent-host backend. */ export declare const CLAUDE_AGENT_PROVIDER_ID: "claude"; /** Well-known agent provider id for the Codex agent-host backend. */ export declare const CODEX_AGENT_PROVIDER_ID: "codex"; /** Well-known agent provider id for the Copilot CLI agent-host backend. */ export declare const COPILOT_CLI_AGENT_PROVIDER_ID: "copilotcli"; /** * Static capability facts an agent backend advertises about itself. Each flag * is opt-in (absent means unsupported) so single-chat agents (e.g. Codex) can omit * the bag entirely. Discovered over IPC alongside the rest of * {@link IAgentDescriptor} and surfaced to the sessions UI so features are * capability-gated instead of switched on the provider id. * * This is the IPC contract alias of the protocol-visible {@link AgentCapabilities} * type (defined in the root-state protocol); both share a single canonical shape * so a new flag added in one place is automatically reflected in the other. */ export type IAgentCapabilities = AgentCapabilities; /** Agent Host-only capabilities that are not serialized to protocol clients. */ export interface IAgentHostCapabilities { readonly workspaceConversion: boolean; } /** Metadata describing an agent backend, discovered over IPC. */ export interface IAgentDescriptor { readonly provider: AgentProvider; readonly displayName: string; readonly description: string; /** Static capability flags the agent advertises (see {@link IAgentCapabilities}). */ readonly capabilities?: IAgentCapabilities; } /** * Parameters for the `authenticate` command. * Analogous to sending `Authorization: Bearer ` (RFC 6750 section 2.1). */ export interface AuthenticateParams { /** * The `resource` identifier from the server's * {@link IAuthorizationProtectedResourceMetadata} that this token targets. */ readonly resource: string; /** * Scopes that were used to acquire the token. Omitted for legacy clients * that can only identify tokens by protected resource. */ readonly scopes?: readonly string[]; /** The bearer token value (RFC 6750). */ readonly token: string; /** The access token's remaining lifetime in seconds, when known. */ readonly expiresIn?: number; /** The single consumer this token is for; when absent, tokens match by resource and scopes. */ readonly target?: AuthenticateTarget; /** Optional client metadata. Hosts must remain usable when it is absent. */ readonly _meta?: Record; } /** Request for a previously accepted bearer token. */ export interface IAgentHostAuthTokenRequest { readonly session?: string; /** Protected resource identifier from {@link ProtectedResourceMetadata.resource}. */ readonly resource: string; /** Required token scopes, when the caller needs a scope-specific token. */ readonly scopes?: readonly string[]; } /** * Result of the `authenticate` command. */ export interface AuthenticateResult { /** Whether the token was accepted. */ readonly authenticated: boolean; } /** * Canonical {@link ProtectedResourceMetadata} for the GitHub Copilot * resource. Shared between every agent provider that consumes a GitHub * Copilot bearer token (e.g. Copilot CLI, Claude) so they advertise an * identical resource identifier to the auth flow — clients dispatch by * `resource`, and divergent metadata would silently route the same * token down separate code paths. */ export declare const GITHUB_COPILOT_PROTECTED_RESOURCE: ProtectedResourceMetadata; /** * Canonical {@link ProtectedResourceMetadata} for GitHub repository write * operations (e.g. creating a pull request). Distinct from * {@link GITHUB_COPILOT_PROTECTED_RESOURCE} so that the broader `repo` * scope is only requested when a session actually needs it (e.g. when a * changeset operation handler throws `AHP_AUTH_REQUIRED` with this * resource), rather than at session create for every agent. * * `required: false` reflects that the resource is only needed on demand — * agents do not have to advertise it eagerly. The workbench-side auth * contributor resolves it lazily in response to operation invocations. */ export declare const GITHUB_REPO_PROTECTED_RESOURCE: ProtectedResourceMetadata; /** * Pure decision: does this set of advertised protected resources require the * user to be signed in to GitHub Copilot right now? * * Returns `true` iff the agent advertises the canonical GitHub Copilot * protected resource ({@link GITHUB_COPILOT_PROTECTED_RESOURCE}) with * `required !== false`. Provider-agnostic by design: an agent that drops the * resource entirely (e.g. Claude in native mode) or advertises it with * `required: false` (e.g. Codex on OpenAI) does not require a GitHub sign-in. * * An absent `required` field is treated the same as `true` (see * {@link ProtectedResourceMetadata.required}). */ export declare function protectedResourcesRequireGitHubCopilotSignIn(resources: readonly ProtectedResourceMetadata[]): boolean; export interface IAgentCreateSessionConfig { readonly credentials?: IAgentHostCredentialSource; readonly provider?: AgentProvider; readonly model?: ModelSelection; readonly _meta?: Record; /** * Initial custom agent selection for the new session. Omit to start with * no custom agent selected (provider default behavior). */ readonly agent?: AgentSelection; readonly session?: URI; /** * The working directories the session's agent is granted tool access to, * ordered so that index 0 is the intended process root (the "primary"). * * Distinct values: * - `undefined` — no directories requested (workspace-less inference applies); * - `[]` — explicitly no directories; * - `[dir, …]` — the ordered set (index 0 = primary/process root). * * A client MUST NOT supply more than one entry unless the agent advertises * the `multipleWorkingDirectories` capability (not advertised yet). During * the compatibility phase callers supply exactly one directory (`[dir]`). */ readonly workingDirectories?: readonly URI[]; readonly config?: Record; /** * Eagerly claim the active client role for the new session. When provided, * the server initializes the session with this client as the active * client, equivalent to dispatching a `session/activeClientSet` * action immediately after creation. The `clientId` MUST match the * connection's own `clientId`. */ readonly activeClient?: SessionActiveClient; /** * Import an existing (e.g. local) conversation into a brand-new session as * real, editable turns. The provider translates {@link turns} into a * Copilot event log seeded on disk and resumes the session so the turns are * reconstituted as genuine backend events (editable / forkable / truncatable). * * The service layer assigns fresh UUID turn ids before handing the turns to * the provider so the seeded event ids and the seeded protocol turns stay * aligned. Mutually exclusive with {@link fork}. */ readonly importConversation?: { readonly turns: readonly Turn[]; readonly model?: ModelSelection; readonly title?: string; }; /** * MCP-style opt-in progress token from the client's `createSession`. When * set, the service reports any long-running session bring-up work — chiefly * the lazy first-use SDK download — as `progress` notifications carrying * this token, so the client can correlate them to this call. */ readonly progressToken?: string; } /** A repository worktree a multi-folder session owns besides its main working directory. */ export interface IAgentChatAdditionalWorktree { readonly handle: string; readonly workingDirectory: string; readonly repositoryRoot: string; readonly chat?: string; } export interface IAgentChatSessionSettings { /** Where the session's customizations are anchored; `undefined` when it has none. */ readonly customizationDirectory: URI | undefined; /** Further directories whose customizations apply to the session. */ readonly additionalCustomizationDirectories: readonly URI[]; /** The project the session was resolved to, if any. */ readonly project: IAgentSessionProjectInfo | undefined; /** Whether the session has no workspace. */ readonly workspaceless: boolean; /** The first working directory of the session's default chat, if known. */ readonly defaultChatWorkingDirectory: URI | undefined; /** The additional repository worktrees the session owns. */ readonly additionalWorktrees: readonly IAgentChatAdditionalWorktree[]; } /** A change of the session that owns a chat. */ export interface IAgentChatOwnerChange { readonly previous: URI; readonly current: URI; } /** * The session that owns one chat, resolved by Agent Host whenever it is read. * * A chat's owner can change while the chat runs, so providers read * {@link get} at the moment they use the owner (publishing session-level * actions, server tools, terminal and subagent URIs, enablement, telemetry) * and never store the value it returns. */ export interface IAgentChatOwnerRef { /** The session that owns the chat now. */ get(): URI; /** The current owner's subagent chat format, read at use because this reference can predate default-chat registration. */ getSubagentChatUriFormat(): ChatUriFormat; /** Fires after the chat's owner changed. */ readonly onDidChange: Event; } /** An owner reference that always answers `owner`, for chats Agent Host never reassigns. */ export declare function fixedChatOwnerRef(owner: URI, subagentChatUriFormat?: ChatUriFormat): IAgentChatOwnerRef; /** * Host-owned transient context for an addressed chat operation. * * `resource` is the provider-owned persistence scope for this exact chat: its * recorded storage, which stays the same when the chat changes owner. `owner` * is the session that owns the chat now, resolved late (see * {@link IAgentChatOwnerRef}): identity, session actions and session-level * resources. Configuration is per chat (3b). Providers must not derive any of * them from `chat` themselves. * * Agent Host populates {@link origin} and {@link customizations} on every * context it hands to a provider (create, materialize, send, and every other * addressed chat operation). */ export interface IAgentChatContext { readonly credentials?: IAgentHostCredentialSource; readonly resource: URI; /** The session that owns the chat, read at each use and never stored. */ readonly owner: IAgentChatOwnerRef; /** * The session-wide settings the host owns, so providers never read them back * out of the session's configuration storage. `undefined` only when the host * has no state for the session yet (creation, before the first import). */ readonly sessionSettings: IAgentChatSessionSettings | undefined; /** * The directories the host launches this chat in when the provider's own * storage of the chat records none. `undefined` for tool chats, workspaceless * sessions and chats with no recorded launch directory. */ readonly launchWorkingDirectories: readonly URI[] | undefined; /** * Whether this chat has no workspace of its own: it runs in a host-allocated * scratch folder. Decided per chat by the host from its recorded folders, * never from its owner's identity. */ readonly workspaceless: boolean; readonly clientTelemetryContext?: IAgentHostClientTelemetryContext; /** The owning turn's immutable admission snapshot, supplied only for its send. */ readonly turnTelemetryContext?: IAgentProviderTurnTelemetryContext; readonly turnTelemetryCorrelation?: IAgentTurnTelemetryCorrelation; /** Records provider-owned dispatch facts on the addressed turn, before progress can complete it. */ readonly reportCodexModelProvider?: (provider: CodexModelProvider) => void; /** * Records, before progress can complete the addressed turn, that its send * found a provider session started before the first message: without a * reason when the send used it, or with the bounded reason it was discarded * and the send launched one instead. */ readonly reportPrewarmedSession?: (discardReason?: string) => void; /** * The addressed chat's origin, taken verbatim from the host-owned chat * catalog, and exhaustive across every way a chat comes into existence: * a plainly user-created peer chat and the session-backed default chat * carry {@link ChatOriginKind.User}; a fork carries * {@link ChatOriginKind.Fork} with the exact source chat and turn; a side * chat carries {@link ChatOriginKind.SideChat}; and a subagent chat always * carries its {@link ChatOriginKind.Tool} spawn edge, so providers never * have to recover it from state or URI shape. Absent only when the host has * no catalog entry for the chat yet — the narrow window during restore * before the chat is registered, where the caller supplies the origin it is * restoring with. */ readonly origin?: ChatOrigin; /** * The owning session's last host-published customization snapshot — the * same list clients observe on `SessionState.customizations`, including * user enablement toggles. Supplied at the create, materialize, send, and * update boundaries so providers never read them back out of shared host * state, and reconciled against the provider's own view rather than * replacing it. Absent when the host has not published a snapshot for the * session yet, which is deliberately distinct from an empty list. */ readonly customizations?: readonly Customization[]; /** Per-operation host instructions that providers add to model context without persisting as user content. */ readonly hostInstructions?: readonly string[]; /** Records provider timing for the current send or resumed execution. */ readonly sendStageRecorder?: IAgentProviderSendStageRecorder; /** Whether the current turn is an automated Agent Merge repair turn. */ readonly agentMergeTurn?: boolean; /** * The VS Code chat surface the owning session was created for, from its surface * metadata. Supplied at each operation, so a runtime that replaces the chat's * keeps the surface's behavior. Absent for sessions no such surface created. */ readonly chatSurface?: IChatSurfaceMeta["surface"]; } export type AgentChatOperationContext = URI | IAgentChatContext; /** * Normalize a legacy session-only chat context into the explicit * {@link IAgentChatContext} shape by attaching the host-supplied `resource`. */ export declare function resolveAgentChatContext(sessionOrContext: AgentChatOperationContext, resource: URI): IAgentChatContext; /** * The session database a chat stores in when it is the chat its session was * created with: its storage is that session, not its own resource. Older * chats of that kind have no recorded provider backing, and their provider * identity is that session's id. `undefined` for a chat that stores under its * own resource. A storage fact read from the recorded storage, never a role * derived from the chat URI. */ export declare function resolveSessionBackedStorage(context: IAgentChatContext, chat: URI): URI | undefined; /** * Reads the host-supplied {@link IAgentChatContext.origin} for an addressed * chat operation. See {@link IAgentChatContext.origin} for absence semantics. */ export declare function resolveAgentChatOrigin(context?: URI | IAgentChatContext): ChatOrigin | undefined; /** * Reads the tool-call spawn edge of a subagent chat from its host-supplied * origin. Returns `undefined` when the chat was not spawned by a tool call. * Providers use this to route inner tool completions and transcript filtering * to the spawning chat without consulting shared host state. */ export declare function resolveSubagentChatParent(context?: URI | IAgentChatContext): IAgentSpawnedChatParent | undefined; /** * Reads the last host-published customization snapshot carried by an * addressed chat operation's context. See {@link IAgentChatContext.customizations} * for absence semantics. */ export declare function resolveAgentHostCustomizations(context?: URI | IAgentChatContext): readonly Customization[] | undefined; export declare function resolveAgentHostInstructions(context?: URI | IAgentChatContext): readonly string[] | undefined; /** Fully resolved options for creating one chat. */ export interface IAgentCreateChatOptions { /** Whether the owning session is transient and should skip durable-only provider work. */ readonly isEphemeral?: boolean; /** * Whether the owning chat surface is scoped to editing a single file (editor * inline chat). Blanket shell auto-approvals must not apply to such a * session, because a shell command can write anywhere the sandbox allows and * carries no destination the permission layer can check against the scope. */ readonly hasScopedEditSurface?: boolean; /** * Whether the owning chat surface is an inline chat (editor or terminal), where * latency matters more than routing depth, so Copilot Fusion runs at its fast tier. */ readonly isInlineChatSurface?: boolean; /** * Authoritative initial title supplied to host creation. When present, it * takes precedence over a generated fork placeholder; explicit provenance * determines whether automatic title replacement is allowed. */ readonly title?: string; /** Optional model override; defaults to the session's model. */ readonly model?: ModelSelection; /** Optional custom agent selection. */ readonly agent?: AgentSelection; /** Complete ordered working-directory set resolved by Agent Host. */ readonly workingDirectories?: readonly URI[]; /** Project metadata resolved by Agent Host. */ readonly project?: IAgentSessionProjectInfo; /** Provider-specific configuration resolved by Agent Host. */ readonly config?: Record; /** Active client to seed before the first turn. */ readonly activeClient?: SessionActiveClient; /** Defer creating the provider SDK backing until the chat's first send. */ readonly deferBacking?: boolean; /** Existing conversation turns to import into this chat. */ readonly importConversation?: IAgentCreateSessionConfig["importConversation"]; /** * Fork an existing chat into this new chat. The new chat starts * pre-populated with the source chat's turns up to and including * {@link IAgentCreateChatForkSource.turnId}, and its backing chat * is forked from the source so it can continue independently. */ readonly fork?: IAgentCreateChatForkSource; } /** The surface-scoped {@link IAgentCreateChatOptions} for a chat whose owning session `surface` created. */ export declare function getChatSurfaceOptions(surface: IChatSurfaceMeta["surface"] | undefined): Pick; /** * Host-facing chat creation options. Providers receive the resolved * {@link IAgentCreateChatOptions} and never receive side-chat provenance. */ export interface IAgentCreateChatRequestOptions extends IAgentCreateChatOptions { /** * Host-owned first user message submitted after creating the chat. This is * intentionally excluded from {@link IAgentCreateChatOptions}: providers * create the chat before the host processes this message through the normal * client-aware send path. */ readonly initialMessage?: Message; /** * Create this new chat as a side chat branching from a turn in an existing * chat (via `/btw`). The host resolves this into {@link fork} before calling * the provider, while retaining the side-chat provenance itself. */ readonly sideChat?: IAgentCreateChatSideChatSource; /** * The agent requested for the new chat (`CreateChatParams.provider`). The * host resolves and validates it and creates the chat in that agent; * absent means the source chat's agent for a fork or side chat, else the * session's. Never passed to providers. */ readonly provider?: AgentProvider; /** * Host-owned workspace requested for a new peer chat. The host prepares it * (adding the folder to the session, creating a worktree or a scratch * folder) and resolves it into {@link workingDirectories}; providers never * receive it. Exclusive with {@link workingDirectories}, {@link fork} and * {@link sideChat}. */ readonly workspace?: IAgentCreateChatWorkspace; } /** The workspace a client asks for when it creates a peer chat (VS Code `_meta`, validated). */ export type IAgentCreateChatWorkspace = { readonly kind: "folder"; readonly folder: URI; readonly isolation: "folder"; } | { readonly kind: "folder"; readonly folder: URI; readonly isolation: "worktree"; readonly baseBranch: string | undefined; readonly prompt: string; } | { readonly kind: "scratch"; }; /** Identifies the exact source chat and turn to fork from. */ export interface IAgentCreateChatForkSource { readonly source: URI; /** Turn ID in the source chat; content up to and including this turn is copied. */ readonly turnId: string; /** * Allows a fork to start without waiting for the source chat's queue. * Side chats branch from potentially active source turns and use this to * avoid blocking their own creation behind that turn. */ readonly independentQueue?: boolean; /** Zero-based source turn index, when the provider needs it for import/fork mapping. */ readonly turnIndex?: number; /** * Maps old source turn IDs to fresh turn IDs for the forked chat. Populated * by the agent service so the agent can remap per-turn data (e.g. SDK event * ID mappings) in the forked chat's database. */ readonly turnIdMapping?: ReadonlyMap; } /** Immutable selected-text snapshot captured when a side chat is created. */ export interface IAgentCreateChatSideChatSelection { readonly text: string; /** Optional provenance for the response part that contained {@link text}. */ readonly responsePartId?: string; } /** Identifies a source chat and turn a side chat (`/btw`) branches from. */ export interface IAgentCreateChatSideChatSource { readonly source: URI; /** Turn ID in the source chat the side chat records as its provenance. */ readonly turnId: string; /** Optional selected-text snapshot captured from the source chat transcript. */ readonly selection?: IAgentCreateChatSideChatSelection; } /** Result of {@link IAgentChats.createChat}: the opaque blob to persist for restore. */ export interface IAgentCreateChatResult { readonly project?: IAgentSessionProjectInfo; readonly resolvedWorkingDirectory?: URI; readonly provisional?: boolean; /** Id of the last provider turn copied into a newly created fork, when known. */ readonly inheritedTurnId?: string; /** * Opaque, agent-owned token the orchestrator persists verbatim in the chat * catalog and hands back to {@link IAgent.materializeChat} on * restore. The orchestrator never parses it. `undefined` means nothing to * persist (e.g. the agent keeps no resumable backing). */ readonly providerData?: string; /** * The SDK-level session URI that backs this chat, when the agent mints one in * the same session store its own {@link IAgent.listSessions} enumerates * (e.g. Claude). First-class and non-opaque — unlike {@link providerData} the * orchestrator reads it to correlate and suppress the backing session so it * never surfaces as a top-level session. `undefined` when the agent keeps no * separately-enumerable backing session. */ readonly backingSession?: URI; } /** Payload of {@link IAgent.onDidChangeChatData}. */ export interface IAgentChatDataChange { readonly chat: URI; /** The new opaque blob to persist (replaces any previously stored value). */ readonly providerData: string; } /** A legacy concrete chat backing enumerated by {@link IAgent.listLegacyChatBackings} for migration. */ export interface IAgentLegacyChat { /** The concrete chat's channel URI (see {@link buildChatUri}). */ readonly uri: URI; /** The opaque, agent-owned backing blob, encoded as {@link materializeChat} expects. */ readonly providerData?: string; } /** The native chat catalog requires an external readiness action before it can be enumerated. */ export declare const AgentChatMigrationDeferred: unique symbol; /** Provider-native chat catalog result used by registry migration. */ export type AgentChatMigrationResult = readonly IAgentListedChat[] | undefined | typeof AgentChatMigrationDeferred; /** * Identifies the parent that spawned a chat. The orchestrator records * it as the spawned chat's {@link ChatOriginKind.Tool} origin so clients can * render the parent/child relationship (e.g. a sub-agent "team" member spawned * by a tool call in the parent chat). */ export interface IAgentSpawnedChatParent { /** The parent chat URI whose tool call performed the spawn. */ readonly chat: URI; /** The id of the tool call in the parent that spawned this chat. */ readonly toolCallId: string; } /** * Payload of {@link IAgent.onDidSpawnChat}: a new chat the * agent spawned itself (e.g. a sub-agent delegated by a tool call), as opposed * to a user-driven chat created via * {@link IAgentChats.createChat}. */ export interface IAgentSpawnChatEvent { /** The session URI the spawned chat belongs to. */ readonly session: URI; readonly chat: URI; /** * The parent that spawned it, when the spawn was delegated by a tool call. * Recorded as the chat's tool origin in the catalog. Absent for a * top-level, agent-initiated chat with no spawning tool call. */ readonly parent?: IAgentSpawnedChatParent; readonly title?: string; } /** Builds the shared title for subagent chats and activity messages, preferring a concise task description over the agent type's name. */ export declare function subagentChatTitle(taskDescription: string | undefined, agentDisplayName: string | undefined): string; /** * Maps agent `subagent_started` signals to the unified chat catalog's spawn * events. Shared by the agents' spawn bridges and the orchestrator so subagent * membership has one derivation. */ export declare namespace SubagentChatSignal { /** * Derives the {@link IAgentSpawnChatEvent} for a `subagent_started` signal, * addressing the subagent by the stable {@link subagentChatUri} of the * conversation chat that issued the tool call and recording the spawning * tool call as its parent edge. The subagent belongs to the spawning chat's * recorded owner. Returns `undefined` for any other signal, or when the * spawning chat's owner is unknown. */ function toSpawnEvent(signal: AgentSignal, lookupChat: (chat: string) => { readonly owner: string; readonly format: ChatUriFormat; } | undefined): IAgentSpawnChatEvent | undefined; } /** A provider's preparation can block input without adding a conversation turn. */ export interface IAgentPrepareChatResult { readonly error?: ErrorInfo; } /** * The chat-addressed operation surface an agent exposes for the chats * within a session. * * Every operation method addresses a chat by a concrete chat channel URI; the * orchestrator ({@link IAgentService}) owns the `(session, chat)` mapping and * calls these operations with a concrete chat URI plus transient context when * the provider needs the owning session or storage scope. */ export interface IAgentChats { /** * Optional pre-send preparation, such as materializing a deferred provider * session, after the turn's model/agent selection and working directories * are resolved. The host may run it concurrently with the turn-start * checkpoint capture and awaits both before {@link sendMessage} for the same * `turnId`, so implementations must not send a prompt or modify the working * tree. Preparation that is not needed must resolve without doing work. */ prepareTurn?(chat: URI, turnId: string, workingDirectories: readonly URI[] | undefined, context: AgentChatOperationContext): Promise; /** Prepare an existing chat for input without sending a turn. May acquire its native writer lock. */ prepareChat?(chat: URI, context: AgentChatOperationContext): Promise; /** * Optionally starts the runtime of a chat that was created with a deferred * backing ({@link IAgentCreateChatResult.provisional}) before its first send, * so its MCP servers and plugins load while the user composes. The warm * runtime must not persist, list or announce the chat: the first send * claims it (or replaces it when its launch configuration went stale), and * disposing the chat discards it. Resolves `true` when a warm runtime is * live afterwards; a chat that cannot be warmed resolves `false` without * doing work. */ warmChat?(chat: URI, context: IAgentChatContext): Promise; /** * Create a fresh additional chat within an already-provisioned `session`, * using the complete working directory and config supplied in * {@link IAgentCreateChatOptions}. `chat` is the client-chosen channel URI. * The orchestrator supplies provider-owned persistence and configuration * scopes via `context`, so the agent never has to recover either by parsing * `chat`. */ createChat(chat: URI, context: AgentChatOperationContext, options?: IAgentCreateChatOptions): Promise; /** Dispose the addressed chat and free its backing. */ disposeChat(chat: URI, context: AgentChatOperationContext): Promise; /** Return whether the addressed chat can currently release its in-memory backing. */ canReleaseChat?(chat: URI, context: AgentChatOperationContext): Promise; /** Release the addressed chat's in-memory backing without deleting durable data. */ releaseChat(chat: URI, context: AgentChatOperationContext): Promise; /** * Send a user message into `chat`. On every send, the host passes the complete * resolved, ordered working-directory snapshot (index 0 = the process root / * resolved worktree, followed by any additional roots), or `undefined` for * workspace-less sessions. Providers must make that snapshot effective before * the prompt enters their runtime. `context` is transient operation context; * providers must not retain it as chat membership state. */ sendMessage(chat: URI, prompt: string, workingDirectoriesOrDirectory: readonly URI[] | URI | undefined, attachments?: readonly MessageAttachment[], turnId?: string, senderClientId?: string, clientTypeOrContext?: AgentHostClientType | URI | IAgentChatContext, context?: URI | IAgentChatContext): Promise; /** Resume a failed turn without adding another user message. */ resumeTurn?(chat: URI, turnId: string, context: AgentChatOperationContext, senderClientId?: string, clientType?: AgentHostClientType): Promise; /** Abort the in-flight turn for `chat`. */ abort(chat: URI, context: AgentChatOperationContext): Promise; /** Return the model currently bound to `chat`, when the provider knows it. */ getModel?(chat: URI, context: AgentChatOperationContext): ModelSelection | undefined; changeModel(chat: URI, model: ModelSelection, context: AgentChatOperationContext): Promise; /** * Change (or clear) the selected custom agent for `chat`. Passing * `undefined` clears the selection (provider default behavior). */ changeAgent(chat: URI, agent: AgentSelection | undefined, context: AgentChatOperationContext): Promise; /** Reconstruct the turns for `chat` (used on restore). */ getMessages(chat: URI, context: AgentChatOperationContext): Promise; } /** Provider-native metadata events, before protocol translation. */ export interface IAgentChatSessionEvent { readonly chat: URI; readonly id: string; readonly timestamp: string; readonly persisted: boolean; readonly type: string; readonly data: unknown; } export interface IAgentResolveChatConfigParams { readonly provider?: AgentProvider; readonly workingDirectory?: URI; readonly config?: Record; } /** A policy query failed before the provider could apply a selection or send a prompt. */ export declare class AgentPolicyError extends Error { readonly code = "policyResolutionFailed"; } export interface IAgentChatConfigCompletionsParams extends IAgentResolveChatConfigParams { readonly property: string; readonly query?: string; } export type IAgentResolveSessionConfigParams = IAgentResolveChatConfigParams; export type IAgentSessionConfigCompletionsParams = IAgentChatConfigCompletionsParams; /** Serializable model information from the agent host. */ export interface IAgentModelInfo { readonly provider: AgentProvider; readonly id: string; readonly name: string; readonly maxContextWindow?: number; readonly maxOutputTokens?: number; readonly maxPromptTokens?: number; readonly supportsVision: boolean; readonly configSchema?: ConfigSchema; readonly policyState?: PolicyState; readonly _meta?: Record; } /** * A signal emitted by an agent during session execution. * * Most signals carry a protocol {@link SessionAction} directly via the * `kind: 'action'` shape, eliminating a parallel event ontology. A small * number of cases that have no clean protocol action (permission * auto-approval, subagent session creation, steering acknowledgment, and * host-owned model-call telemetry and chat billing) remain as discriminated non-action signals. */ export type AgentSignal = IAgentActionSignal | IAgentCanvasSignal | IAgentChatUsageSignal | IAgentModelCallCompletedSignal | IAgentModelCallFinishedSignal | IAgentToolPendingConfirmationSignal | IAgentSubagentStartedSignal | IAgentSubagentResumedSignal | IAgentSubagentCompletedSignal | IAgentSteeringConsumedSignal; /** * Carries a protocol {@link SessionAction} produced by an agent. The host * dispatches the action through the state manager after routing via * {@link IAgentActionSignal.parentToolCallId} (if set). * * Agents are responsible for populating the target channel and any `turnId` / * `partId` fields on the action. */ export interface IAgentActionSignal { readonly kind: "action"; /** Target session or chat channel URI. For inner subagent events this is the parent session — see {@link parentToolCallId}. */ readonly resource: URI; /** Protocol action to dispatch. */ readonly action: SessionAction | ChatAction; /** If set, route the action to the subagent session belonging to this tool call. */ readonly parentToolCallId?: string; } /** Materializes or updates a chat-owned live canvas channel. */ export interface IAgentCanvasSignal { readonly kind: "canvas"; readonly chat: URI; readonly resource: URI; readonly state: CanvasState; } /** Publishes a chat's aggregate billing without changing any turn's usage or content. */ export interface IAgentChatUsageSignal { readonly kind: "chat_usage"; readonly chat: URI; readonly usage: IAgentChatUsage; } /** Reports one completed upstream model response for host-owned turn telemetry. */ export interface IAgentModelCallCompletedSignal { readonly kind: "model_call_completed"; /** Target chat channel URI. For inner subagent calls this is the parent chat channel. */ readonly resource: URI; /** Provider-reported turn identifier. The host remaps it when routing to a subagent chat. */ readonly turnId: string; /** Stable provider message or response identifier used to suppress duplicate notifications. */ readonly modelCallId: string; /** If set, route the model call to the subagent session belonging to this tool call. */ readonly parentToolCallId?: string; } export type AgentModelCallFinishedOutcome = "success" | "error" | "cancelled" | "rejected"; /** Reports the final lifecycle outcome of one dispatched model-call attempt. */ export interface IAgentModelCallFinishedSignal { readonly kind: "model_call_finished"; /** Target chat channel URI. For inner subagent calls this is the parent chat channel. */ readonly resource: URI; /** Host turn identifier owning this model-call attempt. */ readonly turnId: string; /** Stable SDK event identifier used to suppress duplicate notifications. */ readonly modelCallId: string; /** Monotonic provider-dispatch duration in milliseconds. */ readonly dispatchDurationMs: number; readonly outcome: AgentModelCallFinishedOutcome; /** Present only for accepted successful responses. */ readonly containsBuiltInFileEditRequest?: boolean; readonly editClassifierVersion: number; /** If set, route the model call to the subagent session belonging to this tool call. */ readonly parentToolCallId?: string; } /** Host-owned permission categories used for tool confirmation and auto-approval. */ export declare enum AgentPermissionKind { Shell = "shell", Write = "write", Mcp = "mcp", Read = "read", Url = "url", Skill = "skill", CustomTool = "custom-tool", Hook = "hook", Memory = "memory", Workflow = "workflow", ExtensionManagement = "extension-management", ExtensionPermissionAccess = "extension-permission-access", ExtensionEnvAccess = "extension-env-access" } /** * A tool has finished collecting parameters and needs the host to decide * whether it should run (or, mid-execution, re-confirm). The host applies * auto-approval logic over {@link permissionKind} / {@link permissionPath} * (see `SessionPermissionManager.getAutoApproval`) and then dispatches the * appropriate `ChatToolCallReady` action — with confirmation options * baked in when the user must approve, or with `confirmed: NotNeeded` when * the host auto-approved. * * Kept as a non-action signal because the host owns this approval policy; * the agent only describes the tool call and the kind of permission being * requested. The {@link state} field carries the protocol-shaped tool-call * state and is dispatched verbatim into the action. */ export interface IAgentToolPendingConfirmationSignal { readonly kind: "pending_confirmation"; /** Target chat channel URI containing the tool call. */ readonly chat: URI; /** Protocol-shaped pending-confirmation state, dispatched verbatim into `ChatToolCallReady`. */ readonly state: ToolCallPendingConfirmationState; /** Host-only auto-approval kind (not part of the dispatched action). */ readonly permissionKind?: AgentPermissionKind; /** Host-only auto-approval path target (not part of the dispatched action). */ readonly permissionPath?: string; /** Host-only URL target for request approval (not part of the dispatched action). */ readonly permissionUrl?: string; /** Host-only command for shell approval when the displayed tool input contains structured arguments. */ readonly shellCommand?: string; /** * Host-only flag requiring the client to show a confirmation instead of applying host auto-approval. * The runtime currently sets it for managed Shell, Read, Edit, and Domain selector asks. */ readonly managedApprovalRequired?: boolean; /** * Host-only flag indicating that the runtime requested sandbox escalation. */ readonly requestSandboxBypass?: boolean; /** * Host-only flag indicating that the sandbox escalation keeps the sandbox attached * while file and process restrictions record instead of block. */ readonly requestSandboxPermissive?: boolean; /** * Host-only shell language for terminal auto-approval. * Only `bash` and `powershell` are eligible for terminal-rule analysis; * missing requires explicit confirmation. */ readonly shellLanguage?: "bash" | "powershell"; /** * If set, the tool call belongs to the subagent rooted at this * parent tool call. Used by the host to route the resulting * `ChatToolCallReady` to the subagent session — otherwise the * action would land on the parent session, where there is no * matching `ChatToolCallStart`. */ readonly parentToolCallId?: string; } export type AgentSubagentTaskModelSource = "task_argument" | "subagent_configuration" | "custom_agent_definition" | "unset"; /** `task` is a delegated subagent; `fusionPhase` is a presentation-only chat for one HydraFusion phase of the parent turn. */ export type AgentSubagentKind = "task" | "fusionPhase"; /** * A subagent was spawned by a tool call. The host creates a child session * silently and routes subsequent inner-tool events to it. * * Kept as a non-action signal because subagent session creation has no * protocol action — it's a host-side composition primitive. */ export interface IAgentSubagentStartedSignal { readonly kind: "subagent_started"; readonly chat: URI; readonly toolCallId: string; readonly agentName: string; readonly agentDisplayName: string; readonly agentDescription?: string; readonly taskModelSource?: AgentSubagentTaskModelSource; /** Absent means `task`. */ readonly subagentKind?: AgentSubagentKind; /** For telemetry, when the chat reports no usage of its own. */ readonly model?: string; /** * The spawning Task tool's short (typically 3-5 word) `description` * input, e.g. "Review package.json structure". Distinct from * {@link agentDescription} (the agent *type*'s long role blurb) and * {@link agentDisplayName} (the agent type's name). Preferred as the * peer chat's tab title because it is concise and per-task, so two * subagents of the same type still get distinct, meaningful names. * Absent when the harness does not surface a task description. */ readonly taskDescription?: string; /** * The full delegated instruction the parent handed the subagent (the * spawning tool's `prompt` input). Populated by each provider at emit * time from its own native source, so the shared orchestrator never * parses a provider-specific tool-input shape. Seeds the subagent peer * chat's opening request. Distinct from {@link taskDescription} (a short * tab-title label). Absent when the harness does not surface a prompt. */ readonly taskPrompt?: string; /** * If set, the spawning tool call ({@link toolCallId}) itself lives * inside another subagent's chat — this is the tool call **one level up** * from the spawning tool (its parent), i.e. the tool that spawned the * immediate parent chat. The host uses it to route the * subagent-discovery side effect (the `ChatToolCallContentChanged` * block that lets clients find the child chat) to that immediate parent * chat rather than the top-level {@link chat}. Because subagent chats * are flat (all keyed off the root session + the spawning tool id), * this single one-hop reference resolves the correct parent chat at * ANY nesting depth — no per-level chain is needed. Absent for a * top-level subagent, whose spawning tool call lives directly in * {@link chat}. */ readonly parentToolCallId?: string; } /** * A previously completed subagent started another turn after being steered. */ export interface IAgentSubagentResumedSignal { readonly kind: "subagent_resumed"; readonly chat: URI; readonly toolCallId: string; readonly message?: Message; } /** * A subagent turn has finished — either successfully or with an error. The * child chat and its routing remain live because the same subagent can be * steered into another turn. */ export interface IAgentSubagentCompletedSignal { readonly kind: "subagent_completed"; readonly chat: URI; readonly toolCallId: string; } /** A steering message was consumed (sent to the model). */ export interface IAgentSteeringConsumedSignal { readonly kind: "steering_consumed"; readonly chat: URI; readonly id: string; } export declare namespace AgentSession { /** * Creates a session URI from a provider name and raw session ID. * The URI scheme is the provider name (e.g., `copilot:/`). */ function uri(provider: AgentProvider, rawSessionId: string): URI; /** * Extracts the raw session ID from a session URI (the path without leading slash). * Accepts both a URI object and a URI string. */ function id(session: URI | string): string; /** * Legacy provider-scheme fallback; standard sessions require explicit provider metadata. */ function provider(session: URI | string): AgentProvider | undefined; /** * Whether a session URI has the shape {@link uri} mints: no authority, query or fragment. * Session storage is keyed by {@link id} alone, so any other shape must not be resolved to it. */ function isCanonical(session: URI): boolean; } /** * A notification originating from an MCP server, routed back to the AHP * client through the `mcp://` side channel. `channel` is the channel * URI advertised on the owning * {@link McpServerCustomization.channel | McpServerCustomization}; the * client uses it to fan the notification out to the appropriate App. * `method` and `params` follow the underlying MCP notification spec * (e.g. `notifications/tools/list_changed`). */ export interface IMcpNotification { readonly channel: string; readonly method: string; readonly params?: Record; } /** * A per-chat handle for one active client's contributions (tools and * plugin customizations), obtained via * {@link IAgent.getOrCreateActiveClient}. * * `tools` and `customizations` are mutable accessor properties: assigning a * new array replaces this client's contribution wholesale and triggers the * agent's internal reaction (refreshing the merged tool set exposed to the * model, or kicking off an asynchronous customization sync). The arrays are * `readonly` so callers cannot mutate them in place and silently bypass the * setter. The agent merges the contributions of all active clients on a * exact chat, deduplicating as needed. */ export interface IActiveClient { /** Client identifier (matches `clientId` from `initialize`). */ readonly clientId: string; /** Human-readable client name (e.g. `"VS Code"`), if provided. */ readonly displayName: string | undefined; /** This client's tools. Assigning replaces the set (full replacement). */ tools: readonly ToolDefinition[]; /** This client's plugin customizations. Assigning replaces the set and starts an internal sync. */ customizations: readonly ClientPluginCustomization[]; } /** Worktree identity a predecessor recorded for a chat, so a missing checkout can be recreated on resume. */ export interface IAgentAdoptedWorktree { readonly branchName: string; readonly baseBranch: string | undefined; readonly worktreePath: URI; readonly repositoryRoot: URI; } /** * Why an adoption attempt ended the way it did. Reported in logs and telemetry so * a session that did not migrate can be diagnosed without reproducing it. */ export type AgentChatAdoptionReason = /** Already has Agent Host metadata — native or previously adopted. */ "alreadyNative" /** Not a legacy extension-host Copilot CLI chat (e.g. standalone CLI, Local agent). */ | "notLegacyChat" /** A legacy chat whose recorded working directory no longer exists and could not be resolved. */ | "workingDirectoryMissing" /** A legacy chat whose extension-host marker could not be re-read, leaving its archived state unknown. */ | "markerUnavailable" /** Newly adopted. */ | "adopted"; /** Outcome of attempting to adopt a legacy provider-native chat. */ export interface IAgentChatAdoptionResult { /** Whether this call newly seeded Agent Host metadata. */ readonly adopted: boolean; /** Whether the chat was a genuine legacy adoption candidate. */ readonly eligible: boolean; /** Whether the chat already has Agent Host metadata, i.e. it is ours regardless of adoption. */ readonly native?: boolean; /** Host-owned list-visible values recovered from the predecessor format. */ readonly listVisible?: ({ readonly title: string; readonly titleSource: "user" | "agent" | "auto"; } | { readonly title?: undefined; readonly titleSource?: undefined; }) & { readonly isRead?: boolean; }; /** Set when the adopted chat ran in a worktree that no longer exists and can be recreated. */ readonly worktree?: IAgentAdoptedWorktree; /** Diagnostic reason behind {@link adopted}. */ readonly reason?: AgentChatAdoptionReason; /** Bounded provenance evidence; a missing marker alone does not prove an external session. */ readonly diagnostics?: { readonly markerStatus: "valid" | "missing" | "invalid" | "readError"; readonly provenance: "legacy" | "external" | "unknown"; readonly markerFromCache: boolean; readonly markerOrigin?: "vscode" | "other" | "missing" | "unrecognized" | "invalidType" | "unavailable"; readonly sessionIdStatus?: "opaque" | "empty" | "controlCharacters" | "pathSeparators" | "dotSegment"; readonly copilotHomeSource?: "environment" | "userHome"; readonly sessionStateRootStatus?: "directory" | "file" | "other" | "missing" | "readError" | "notChecked"; readonly sessionDirectoryStatus?: "directory" | "file" | "other" | "missing" | "readError" | "notChecked"; readonly eventsFileStatus?: "directory" | "file" | "other" | "missing" | "readError" | "notChecked"; readonly workspaceMetadataStatus?: "valid" | "missing" | "invalid" | "readError" | "tooLarge" | "notFile" | "notChecked"; /** Persisted runtime client, which can change on resume; not immutable creator provenance. */ readonly lastKnownClient?: "vscode" | "vscode-agent-host" | "github-cli" | "github-autopilot" | "missing" | "unrecognized" | "invalidType" | "unavailable"; readonly errorCode?: string; readonly errorMessage?: string; }; } /** Identifies the client that submitted a pending message. */ export interface IAgentPendingMessageSender { readonly credentials?: IAgentHostCredentialSource; readonly clientId: string | undefined; readonly clientContext: IAgentHostClientTelemetryContext; } /** Account-scoped telemetry metadata; captured contexts become empty when their credentials are superseded. */ export interface IAgentTelemetryContext { readonly copilotSku: string | undefined; /** Analytics ID from the same account discovery as the SKU, without an additional hash. */ readonly copilotTrackingId?: string; } export interface IAgentSessionPlan { readonly plan: { readonly exists: boolean; readonly content: string | null; readonly path: string | null; }; readonly todos: readonly { readonly id: string | null; readonly title: string | null; readonly status: string | null; readonly description: string | null; }[]; readonly dependencies: readonly { readonly todoId: string; readonly dependsOn: string; }[]; } /** * Implemented by each agent backend (e.g. Copilot SDK). * The {@link IAgentService} dispatches to the appropriate agent based on * the agent id. */ export interface IAgent { readonly supportsScopedCredentials?: boolean; /** Unique provider identifier. */ readonly id: AgentProvider; /** Capabilities consumed only inside the Agent Host process. */ readonly agentHostCapabilities: IAgentHostCapabilities; /** Provider descriptor and capabilities. */ getDescriptor(): IAgentDescriptor; /** Available provider models. */ readonly models: IObservable; /** Optional refresh for providers whose model catalog can change at runtime. */ refreshModels?(): Promise; /** Discovers models using only the requesting connection's credentials, without changing the shared catalog. */ getModelsForCredentials?(credentials: IAgentHostCredentialSource, token?: CancellationToken): Promise; /** Refresh live Connector state, optionally reinitializing only the named Connector. */ refreshConnectorSessions?(forceConnectorName?: string): Promise; /** List SDK-owned installations, excluding runtime-only and client-provided plugins. */ listPluginInstallations?(session?: URI, chat?: URI): Promise; /** Uninstall a plugin through the provider that owns its installation state. */ uninstallPlugin?(request: IAgentPluginUninstallRequest, session?: URI, chat?: URI): Promise; /** Persists enablement for an installed plugin identified by its marketplace spec or direct source ID. */ setPluginEnabled?(plugin: string, enabled: boolean): Promise; /** List canvas declarations available to one initialized provider chat. After returning `undefined`, publish {@link ActionType.ChatCanvasesChanged} when an authoritative snapshot is available. */ listSessionCanvases?(session: URI, chat: URI, context: AgentChatOperationContext): Promise; /** Open or focus one canvas instance in an initialized provider chat. */ openSessionCanvas?(session: URI, request: IAgentCanvasOpenRequest, chat: URI, context: AgentChatOperationContext): Promise; /** Close one canvas that a live provider chat presents, notifying its canvas provider. Never resumes a cold chat. */ closeSessionCanvas?(session: URI, request: IAgentCanvasCloseRequest, chat: URI, context: AgentChatOperationContext): Promise; /** Install a plugin through the provider that owns its installation state. */ installPlugin?(request: IAgentPluginInstallRequest, session?: URI, chat?: URI): Promise; /** * Retry preparing the plugins required by managed settings in a live chat * now, even while automatic retries are paused after a failure. */ retryManagedPlugins?(session: URI, chat?: URI): Promise; /** List plugin marketplaces through the provider that owns marketplace state. */ listPluginMarketplaces?(session: URI, chat?: URI): Promise; /** Add a plugin marketplace through the provider that owns marketplace state. */ addPluginMarketplace?(session: URI, source: string, chat?: URI): Promise; /** Browse one plugin marketplace through the provider that owns marketplace state. */ browsePluginMarketplace?(session: URI, name: string, chat?: URI): Promise; /** Remove a plugin marketplace through the provider that owns marketplace state. */ removePluginMarketplace?(session: URI, name: string, force?: boolean, chat?: URI): Promise; /** Refresh one or all plugin marketplaces through the provider that owns marketplace state. */ refreshPluginMarketplaces?(session: URI, name?: string, chat?: URI): Promise; /** Search the provider-native customization catalog for an exact session. */ searchCustomizationMarketplace?(session: URI, request: IAgentCustomizationMarketplaceSearchRequest): Promise; /** List receipt-owned Skill and MCP installations through the provider SDK. */ listCustomizationInstallations?(session: URI): Promise; /** Prepare an exact receipt-owned install or uninstall for explicit review. */ prepareCustomizationInstallation?(session: URI, request: IAgentCustomizationInstallationRequest | { readonly installationId: string; }): Promise; /** Apply an exact operation previously returned for explicit review. */ applyCustomizationInstallation?(operationId: string): Promise; /** Reconcile receipt-owned installations and return the refreshed inventory. */ recoverCustomizationInstallations?(session: URI): Promise; /** * Provisional bridge for provider-global raw MCP configuration. * @see https://github.com/github/copilot-agent-runtime/issues/26495 */ addMcpServerConfiguration?(name: string, config: IMcpServerConfiguration): Promise; /** Discover executable extensions from the provider's persisted inventory. */ listAgentExtensions?(session?: URI, chat?: URI): Promise; /** * Persist User/Plugin enablement and reconcile one exact live chat when supplied. * Project entries are inventory-only; Project and Session mutation are unsupported. */ setAgentExtensionEnabled?(extensionId: string, enabled: boolean, session?: URI, chat?: URI): Promise; /** Capture the current account without allowing a later account to relabel an in-flight turn. */ getTelemetryContext?(): IAgentTelemetryContext; /** Reads the owning session's provider-native plan and structured todos. */ getSessionPlan?(session: URI): Promise; /** Applies a legacy boolean approval selection through the provider's runtime permission policy. */ setSessionApproveAll?(session: URI, enabled: boolean): Promise; /** Streamed progress for an exact chat. */ readonly onDidChatProgress: Event; /** Native snapshots can arrive after host cancellation or steering has already ended a turn. */ readonly onDidStoreTurnEdits?: Event<{ readonly chat: URI; readonly turnIds: readonly string[]; }>; /** Host-wide progress for provider setup, including work without a chat yet. */ readonly onDidReportProgress?: Event>; /** Optional admitted native metadata stream for environment-owned session mirroring. */ readonly onDidChatSessionEvent?: Event; /** Read genuine persisted metadata without creating or resuming a provider session. */ readChatSessionEvents?(chat: URI, context: IAgentChatContext, token: CancellationToken, afterEventId?: string, onDidReadEventId?: (id: string) => void): AsyncIterable; /** Synchronize a host-owned title into an already-live provider session. */ synchronizeChatSessionTitle?(chat: URI, title: string): Promise; /** Fires when a provisional chat acquires its SDK backing and durable metadata. */ readonly onDidMaterializeChat: Event; /** Fires when an opaque chat backing changes and must be persisted again. */ readonly onDidChangeChatData: Event; /** Fires when the provider creates a chat, such as a delegated subagent. */ readonly onDidSpawnChat: Event; /** Exact-chat operations: create, send, abort, mutate, restore history, release, and dispose. */ readonly chats: IAgentChats; /** Re-attach an exact chat from opaque provider data without inferring its role. */ materializeChat(chat: URI, context: URI | IAgentChatContext, providerData: string | undefined): Promise; /** Optional steering hook. Return false to defer handoff until the provider's turn is ready. */ setPendingMessages?(chat: URI, steeringMessage: PendingMessage | undefined, queuedMessages: readonly PendingMessage[], steeringSender?: IAgentPendingMessageSender): boolean | void; /** * Hands off one independent submission without replacing the legacy slot; false defers until ready. * A promise that resolves false hands the message back unsent, for example because the turn it was * meant to steer ended first. The host then keeps it pending and runs it as the next turn. */ sendSteeringMessage?(chat: URI, message: PendingMessage, sender?: IAgentPendingMessageSender): boolean | void | Promise; /** * Withdraws a steering message, previously handed off through {@link sendSteeringMessage}, that a * client removed before the model received it. A message the model already received stays in its * turn. Without this hook, the host rejects removing steering while a turn is active. */ withdrawSteeringMessage?(chat: URI, messageId: string): void; /** Optional history mutation for providers with a native truncation operation. */ truncateChat?(chat: URI, turnId: string | undefined, context?: URI | IAgentChatContext): Promise; /** Waits for native file snapshots to be persisted, including after a host turn is cancelled or steered. */ waitForTurnEdits?(chat: URI, turnId: string): Promise; /** * Stops an entry of the chat's background work that this provider marked * stoppable. Resolves false when the entry is unknown or had already finished. */ stopBackgroundWork?(chat: URI, id: string): Promise; /** Installs the live chat runtime's sandbox certificate after explicit client consent, preserving the advertised chat string. */ installSandboxCertificate?(chat: string, scopeId: string): Promise; /** Replaces the live runtime's sandbox CA after explicit client consent. */ rotateSandboxCertificate?(chat: string, scopeId: string): Promise; /** Removes OS trust for the live runtime's sandbox CA after explicit client consent, retaining the stored CA. */ removeSandboxCertificate?(chat: string, scopeId: string): Promise; /** * Changes the working directory of an exact chat's existing provider-native * backing. Callers MUST gate this operation on * {@link IAgentHostCapabilities.workspaceConversion}; implementations that do * not advertise the capability MUST reject the call. */ setWorkingDirectory(chat: URI, context: URI | IAgentChatContext, workingDirectory: URI): Promise; /** Changes the addressed chat's backing. Shared roots may change only under the host's single-chat catalog lock. */ setChatWorkingDirectory?(chat: URI, context: IAgentChatContext, workingDirectory: URI, options?: { readonly replaceSessionWorkspace: boolean; }): Promise; /** Return bounded diagnostics for an in-flight turn when supported. */ getTurnDiagnosticSnapshot?(chat: URI, turnId: string): IAgentTurnDiagnosticSnapshot | undefined; /** Capture bounded provider context from cached state without I/O. */ captureTurnTelemetryContext?(): IAgentProviderTurnTelemetryContext; /** Read observed usage at terminal dispatch for this exact owning turn, excluding descendants and later delivery. */ getTurnTokenUsage?(chat: URI, turnId: string, parentToolCallId?: string): IAgentTurnTokenUsage | undefined; /** Record the host-remapped turn for a completed provider model call. */ recordModelCallTurnCorrelation?(chat: URI, modelCallId: string, turnId: string): void; /** Get or create one client's contribution handle for an exact chat. */ getOrCreateActiveClient(chat: URI, context: URI | IAgentChatContext, client: { readonly clientId: string; readonly displayName?: string; }, hostCustomizations?: readonly Customization[]): IActiveClient; /** Remove one client's contributions from an exact chat. */ removeActiveClient(chat: URI, context: URI | IAgentChatContext, clientId: string): void; /** Complete a client tool call on its host-resolved provider chat. */ onClientToolCallComplete(chat: URI, toolCallId: string, result: ToolCallResult, context?: IAgentChatContext): void; /** Respond to a pending permission request from the SDK. */ respondToPermissionRequest(requestId: string, approved: boolean, context?: IAgentPermissionResponseContext): void; /** Respond to a pending user input request from the SDK's ask_user tool. */ respondToUserInputRequest(requestId: string, response: ChatInputResponseKind, answers?: Record): void; /** Resolve provider-owned chat configuration; host-owned worktree fields are omitted. */ resolveChatConfig(params: IAgentResolveChatConfigParams): Promise; /** Select provider-owned configuration inherited by a newly created chat. */ getInheritedChatConfig(config: Readonly>): Record | undefined; /** Select provider-owned configuration for an unattended autonomous turn. */ getAutonomousSessionConfig?(config: Readonly>): Record | undefined; /** Return dynamic completions for a provider-owned chat configuration property. */ chatConfigCompletions(params: IAgentChatConfigCompletionsParams): Promise; /** Optional push signal; providers with pull-only customization discovery omit it. */ readonly onDidCustomizationsChange?: Event; /** Optional provider-wide catalog; providers with only per-chat discovery omit it. */ getCustomizations?(): readonly Customization[]; /** Return the effective customization projection for an exact chat. */ getChatCustomizations(chat: URI, context: URI | IAgentChatContext, hostCustomizations?: readonly Customization[]): Promise; /** Returns host-internal plugin owners for MCP servers temporarily published top-level. */ getMcpServerOwners?(session: URI): ReadonlyMap | undefined; /** * Optional provider-owned decision about the multi-root new-session Folder * picker, computed from the ordered working-directory set (index 0 = the * current primary) and seeded into the session's `_meta` at creation for the * client. Returns `undefined` when the provider has no opinion: nothing is * seeded and the client keeps the picker hidden by default, so a provider * that wants it shown must say so with `{ hidden: false }`. The optional * {@link token} aborts the (possibly filesystem-bound) computation. */ computeFolderPickerDecision?(workingDirectories: readonly URI[], token?: CancellationToken): Promise; /** Provides chats that are ready to be registered as Agent Host sessions. */ readonly onDidDiscoverChats: Event; /** Passive transcript changes from another client; these must not start host-side turn execution. */ readonly onDidChangeChatHistory?: Event; /** Observe another client's persisted transcript while a host client subscribes to this chat. */ watchChatHistory?(chat: URI): IDisposable; /** * Refresh the chat's background work while a client observes an already-hydrated chat. * `published` reads the list the chat currently shows, so a session that replaced an * earlier one, for example after a client restart, can remove entries its runtime no * longer reports. */ watchChatBackgroundWork?(chat: URI, published: () => readonly BackgroundWork[]): IDisposable; /** * Starts provider-owned native chat discovery; repeated calls are idempotent. * The host passes its own startup-frozen legacy-migration gate so discovery * and listing always agree on whether legacy chats are adoptable. */ startChatDiscovery?(options?: IAgentChatDiscoveryOptions): Promise; /** Lets discovery drop registered candidates before per-session I/O. */ setKnownSessionsFilter?(filter: IAgentKnownSessionsFilter): void; /** Optional adoption hook for providers with a predecessor-owned on-disk format. */ ensureChatAdopted?(chat: URI, context: URI | IAgentChatContext): Promise; /** * The worktree a predecessor recorded for a session it still owns (one not * adopted yet), so deleting the session removes it as the predecessor's * delete did. `undefined` once the session has Agent Host metadata. */ readLegacyChatWorktree?(session: URI): Promise; /** Optional recovery hook for providers with historical backings but no persisted provider data. */ recoverLegacyChat?(chat: URI, context: URI | IAgentChatContext): Promise; /** Enumerate provider-native chats for registry migration. */ listChatsToMigrate(): Promise; /** Optional migration codec for providers that persisted peer backings before the host catalog. */ listLegacyChatBackings?(session: URI): Promise; /** * Optionally warms metadata for a burst of {@link getChatMetadata} calls; the expected count lets providers avoid bulk reads for small bursts. * Callers release the returned lease after the burst; providers may retain a bounded cache across bursts. */ prewarmSessionMetadata?(expectedSessionCount: number): Promise; /** Retrieve metadata for an exact registered chat. Ambient catalogue reads never set {@link IAgentChatMetadataOptions.activation}. */ getChatMetadata(chat: URI, context: URI | IAgentChatContext, providerData?: string, options?: IAgentChatMetadataOptions): Promise; getProtectedResources(): ProtectedResourceMetadata[]; /** An empty token revokes the credential previously forwarded for this resource. Optional metadata carries client hints, not authorization. */ authenticate(resource: string, token: string, expiresIn?: number, _meta?: Record): Promise; /** Optional token consumer for provider-owned resources such as MCP servers. */ handleAuthenticationToken?(params: AuthenticateParams): Promise; /** Optional current authentication requirement for providers that can require re-authentication after startup. */ readonly authenticationRequired?: IObservable | undefined>; /** Whether model-dependent prerequisites for unattended execution are ready; absent means no additional readiness gate. */ isReadyForAutomation?(model: ModelSelection | undefined, reader?: IReader): boolean; /** Optional endpoint list when the provider owns probeable network traffic. */ getNetworkDiagnosticsEndpoints?(): Promise; /** Optional account label when the provider can resolve one. */ getNetworkDiagnosticsAccount?(): Promise; /** Optional managed-settings snapshot for providers with an enterprise policy surface. */ getManagedSettingsDiagnostics?(): Promise; /** Canonical device remote-control policy; absence is distinct from a failed read. */ getRemoteControlManagedSettings?(): Promise | undefined>; /** Return the provider-owned state file for a session, when one exists. */ getSessionStateFile?(session: URI, chat?: URI): Promise; /** Return the exact provider-owned plan file, resolving the chat's native backing identity. */ getSessionPlanFile?(session: URI, chat: URI): URI | undefined; /** Add provider-owned diagnostics to an Agent Host debug-log staging directory. */ collectDebugLogs?(session: URI | undefined, outputDirectory: URI, chat?: URI): Promise; /** Optional host wiring for providers that advertise Agent Host server tools. */ setServerToolHost?(host: IAgentServerToolHost): void; /** Starts a controllable MCP server; providers may cooperatively honor cancellation, but in-flight SDK operations may not be cancellable. */ startMcpServer?(session: URI, id: string, token: CancellationToken): Promise; /** Optional lifecycle operation paired with {@link startMcpServer}. */ stopMcpServer?(session: URI, id: string): Promise; /** Releases turns waiting for MCP startup while the provider continues connecting servers. */ backgroundMcpServerStartup?(session: URI, id: string): Promise; /** Optional `mcp://` router for providers that advertise chat-scoped MCP side-channel resources. */ handleMcpRequest?(chat: URI, serverName: string, method: string, params: Record | undefined): Promise; /** Optional notification stream paired with {@link handleMcpRequest}. */ readonly onMcpNotification?: Event; /** Optional lifecycle hook for providers whose resources react to archived state. */ onArchivedChanged?(session: URI, isArchived: boolean): Promise; shutdown(): Promise; dispose(): void; }