import { CancellationToken } from "../../../base/common/cancellation.js"; import { Event } from "../../../base/common/event.js"; import { Disposable, IReference, IDisposable } from "../../../base/common/lifecycle.js"; import { ArtifactIntegrationRequest, ArtifactIntegrationResponse, ArtifactIntegrationUpdate, IArtifactIntegrationTransport } from "../../artifactIntegrations/common/artifactIntegrationProtocol.js"; import { type ArtifactIntegrationDescriptor } from "../../artifactIntegrations/common/artifactIntegration.js"; import { ArtifactChatAction } from "../common/artifactIntegrationChat.js"; import { URI } from "../../../base/common/uri.js"; import { type IAgentHostManagedWorktree, type IAgentHostWorktreeCleanupStatus } from "../common/agentHostWorktreeCleanup.js"; import { type IAgentHostTcpConnection } from "../common/agentHostTcpConnection.js"; import { type IAgentHostClientCertificatesProvider } from "../common/clientCertificatesProtocol.js"; import { type IAgentHostClientProxyProvider } from "../common/clientProxyProtocol.js"; import { ILogService } from "../../log/common/log.service.js"; import { IConfigurationService } from "../../configuration/common/configuration.service.js"; import { IAgentCreateChatRequestOptions, IAgentCreateChatWorkspace, IAgentCreateSessionConfig, type IAgentExtensionInventory, IAgentResolveSessionConfigParams, IAgentSessionConfigCompletionsParams, IAgentSessionMetadata, AuthenticateParams, AuthenticateResult, IMcpNotification } from "../common/agent.js"; import { IAgentConnection, IAgentHostManagedSettingsDiagnostics, IAgentHostNetworkDiagnosticsInfo, IAgentHostNetworkFetchResult, type AgentHostDebugLogsArtifactKind, type IAgentHostDebugLogsArtifact, type IAgentHostDebugLogsChunk, type IMissionControlCredentialSealingRequest } from "../common/agentService.js"; import { type IAgentHostMcpAuthenticationRequest } from "../common/agentHostExtensionProtocol.js"; import { type IAgentHostSavedChat, type IAgentHostSavedChatContinuation, type IAgentHostSavedChatContinuationResult } from "../common/agentHostSavedChat.js"; import type { IAgentHostFirstResponseDiagnostic } from "../common/otel/agentHostTiming.js"; import type { IChatUserInteractionTiming } from "@codingame/monaco-vscode-chat-service-override/vscode/vs/platform/otel/common/chatUserInteraction"; import { type IRemoteWatchHandle } from "../common/agentHostFileSystemProvider.js"; import { type IActiveSubscriptionInfo, type IAgentSubscription } from "../common/state/agentSubscription.js"; import { type IAgentHostResourceUriMapper } from "../common/agentHostUri.js"; import { AgentHostResourceIdentity } from "../common/agentHostResourceService.js"; import { IAgentHostResourceService } from "../common/agentHostResourceService.service.js"; import type { CommandMap } from "../common/state/protocol/messages.js"; import { type ActionEnvelope, type ChatAction, type ClientAnnotationsAction, type ClientAutomationAction, type ClientAutomationRunAction, type ClientChangesetAction, type IRootConfigChangedAction, type SessionAction, type TerminalAction } from "../common/state/sessionActions.js"; import { StateComponents, type AgentInfo, type RootState } from "../common/state/sessionState.js"; import type { AgentChatMoveDestination } from "../common/agentHostChatMove.js"; import { ProtocolError, type IStateSnapshot } from "../common/state/sessionProtocol.js"; import { type IVscodeUpgradeResult } from "../common/state/protocolUpgrade.js"; import { type AgentHostTransportFailureReason, type IProtocolTransport } from "../common/state/sessionTransport.js"; import { ContentEncoding, type CompletionsParams, type CompletionsResult, type CreateTerminalParams, type ResolveSessionConfigResult, type SessionConfigCompletionsResult } from "../common/state/protocol/commands.js"; import type { InvokeChangesetOperationParams, InvokeChangesetOperationResult } from "../common/state/protocol/channels-changeset/commands.js"; import type { FetchAutomationRunsParams, FetchAutomationRunsResult, ListAutomationTriggerDefinitionsParams, ListAutomationTriggerDefinitionsResult, RunAutomationParams, RunAutomationResult } from "../common/state/protocol/channels-automation/commands.js"; import { ILoadEstimator } from "../../../base/parts/ipc/common/ipc.net.js"; import { ITelemetryService } from "../../telemetry/common/telemetry.service.js"; import { AgentHostClientConnectionKind } from "../common/agentHostTelemetry.js"; import type { OtlpExportLogsParams } from "../common/state/protocol/channels-otlp/notifications.js"; import type { Implementation, InitializeResult } from "../common/state/protocol/common/commands.js"; import { type IObservable } from "../../../base/common/observable.js"; import { type IRemoteAgentHostReconnectPolicy } from "../common/reconnectPolicy.js"; import type { IRemoteAgentHostProtocolClient } from "../common/remoteAgentHostService.js"; import { IWorkspaceTrustRequestService } from "../../workspace/common/workspaceTrust.service.js"; import { IWorkspaceTrustManagementService } from "../../workspace/common/workspaceTrust.service.js"; import { IWorkspaceTrustEnablementService } from "../../workspace/common/workspaceTrust.service.js"; import { type IConnectionDiagnosticEvent, type IConnectionDiagnosticState } from "../common/connectionDiagnostics.js"; import { IDevContainerAgentHostMainService } from "../common/devContainerAgentHost.service.js"; /** * High-level connection state of an {@link AgentHostProtocolClient}. * Exposed via {@link AgentHostProtocolClient.onDidChangeConnectionState} * so consumers can surface transient reconnect activity in the UI. */ export declare enum AgentHostClientState { /** Initial handshake in progress. */ Connecting = "connecting", /** The host rejected the initial protocol version; upgrade remains available. */ Incompatible = "incompatible", /** Transport is open and handshake/reconnect has completed. */ Connected = "connected", /** Transport closed unexpectedly; an automatic reconnect is in flight or scheduled. */ Reconnecting = "reconnecting", /** Client has been disposed or has given up reconnecting. Terminal state. */ Closed = "closed" } /** Optional configuration for an {@link AgentHostProtocolClient}. */ export interface IAgentHostProtocolClientOptions { /** Maps client and host resource identities for non-local connections. */ readonly resourceUris?: IAgentHostResourceUriMapper; /** Seals relay credentials only after independently authenticating the requested recipient key. */ readonly sealAuthenticationToken?: (request: IMissionControlCredentialSealingRequest) => Promise; /** Estimator used to suppress watchdog closes while the local event loop is saturated. Defaults to the shared instance. */ readonly loadEstimator?: ILoadEstimator; /** Stable client identity. Generated when omitted. */ readonly clientId?: string; /** Client implementation metadata advertised during the handshake. */ readonly clientInfo?: Implementation; /** How a dropped transport is restored. Defaults to {@link DEFAULT_RECONNECT_POLICY}. */ readonly reconnectPolicy?: IRemoteAgentHostReconnectPolicy; /** Paired OS power events exclude sleep from the recovery budget. */ readonly onDidSuspend?: Event; readonly onDidResume?: Event; /** Refresh connection prerequisites before constructing a replacement transport. */ readonly prepareReconnect?: () => Promise; /** Prepare credentials before initial authentication or restoration; transient failures remain reconnectable. */ readonly prepareAuthentication?: () => Promise; /** Resolves required authentication before initialization or transport recovery becomes ready. */ readonly resolveInitialAuthentication?: () => Promise; /** Resolves existing credentials for advertised resources before protected requests are released. */ readonly resolveAdvertisedAuthentication?: (agents: readonly AgentInfo[]) => Promise; /** Serves client trust roots on demand only for remotes sharing the client's network. */ readonly clientCertificates?: IAgentHostClientCertificatesProvider; /** Serves proxy resolution and proxy Kerberos tickets only for remotes sharing the client's network. */ readonly clientProxy?: IAgentHostClientProxyProvider; /** Releases resources owned by the logical protocol client after its final disposal. */ readonly onDispose?: () => void; } /** An initial authentication resolver failed after a successful initialize. */ export declare class InitialAuthenticationError extends Error { constructor(error: unknown); } /** * A protocol-level client for a single agent host connection. * Manages the transport, handshake, subscriptions, action dispatch, * and command/response correlation. * * Implements {@link IAgentConnection} so consumers can program against * a single interface regardless of whether the agent host is local or remote. */ export declare class AgentHostProtocolClient extends Disposable implements IAgentConnection, IRemoteAgentHostProtocolClient { private readonly _logService; private readonly _resourceService; private readonly _configurationService; private readonly _telemetryService; private readonly _workspaceTrustEnablementService; private readonly _workspaceTrustManagementService; private readonly _workspaceTrustRequestService; private readonly _tcpConnections; private readonly _tcpBudget; private readonly _channelScheduler; private _mcpAuthenticationHandler; private _authenticationTokenSealer; private readonly _trustedAuthenticationTokenSealer; readonly _serviceBrand: undefined; private readonly _clientId; private readonly _address; private readonly _resourceIdentity; private readonly _transportFactory; private _transport; get clientConnectionKind(): AgentHostClientConnectionKind | undefined; private _relayRootRefresh; private _initialAuthenticationResource; private _expiredRelayAuthentication; /** Disposable holding the listeners attached to the current transport. */ private readonly _transportListeners; /** The next reconnect sends `initialize` instead of `reconnect`, so the host decides its capabilities again. */ private _freshInitializeRequested; /** Whether to name the chat subscriptions held once the re-initialize for chats with their own agents connects. */ private _describeChatSubscriptionsOnReconnect; /** Whether this connection already re-initialized for `multipleChatProviders` since the host's gate last turned on. */ private _reinitializedForChatProviders; private readonly _connectionAuthority; readonly resourceUris: IAgentHostResourceUriMapper; private _serverSeq; private _nextClientSeq; private _defaultDirectory; /** * Latest `initialize` response from the host. Captured at the end of * {@link connect} and re-captured after a soft-reconnect that pulled * a fresh snapshot. `undefined` before the handshake completes. */ private readonly _initializeResult; private _authenticationHandshake; readonly sandboxCertificateInstallationSupported: import("../../../base/common/observable.js").IObservableWithChange; readonly sandboxCertificateRotationSupported: import("../../../base/common/observable.js").IObservableWithChange; readonly sandboxCertificateRemovalSupported: import("../../../base/common/observable.js").IObservableWithChange; get supportsConversationImport(): boolean; private readonly _devContainerService; get devContainerService(): IDevContainerAgentHostMainService | undefined; private readonly _subscriptionManager; private readonly _onDidAction; readonly onDidAction: Event; private readonly _artifactIntegrationUpdates; private readonly _artifactIntegrationReset; /** The most recent {@link serveArtifactIntegrations} registration; earlier registrations stay inert. */ private readonly _artifactIntegrationRegistration; /** Answers the host's requests for the integrations this client serves on the current connection. */ private _servedArtifactIntegrations; private readonly _onDidNotification; readonly onDidNotification: Event; private readonly _onMcpNotification; readonly onMcpNotification: Event; /** * Fires for every `otlp/exportLogs` notification the host sends on a * channel this client has subscribed to. Each payload is an * OTLP/JSON `ExportLogsServiceRequest` value verbatim; consumers * decode it (see `iterateOtlpLogRecords`) and route the records to a * registered logger or sink. * * Channel URIs are kept opaque on the wire so the same event covers * every {@link TelemetryCapabilities.logs} URI the host advertises — * subscribers should filter by `channel` if they care. */ private readonly _onDidReceiveOtlpLogs; readonly onDidReceiveOtlpLogs: Event; private readonly _onDidClose; readonly onDidClose: Event; private readonly _onDidInvalidateTransport; private readonly _onDidFatalClose; readonly onDidFatalClose: Event; private readonly _onDidChangeConnectionState; readonly onDidChangeConnectionState: Event; readonly connectionAvailable: IObservable; readonly artifactIntegrationTransport: { onDidUpdate: Event; onDidReset: Event; available: IObservable; request: (request: ArtifactIntegrationRequest) => Promise; }; private readonly _onDidReconnect; readonly onDidReconnect: Event; private readonly _onDidScheduleReconnect; readonly onDidScheduleReconnect: Event; private readonly _onDidConnectionDiagnostic; readonly onDidConnectionDiagnostic: Event; private _diagnosticAttemptId; private _lastSuccessfulResponseAt; getConnectionDiagnosticState(): IConnectionDiagnosticState; private _diagnostic; private _traceConnection; /** Adds content-free diagnostics for client-side repository preparation on this connection. */ traceRepositoryPreparation(phase: "repository.prepare" | "repository.clone", operation: () => Promise): Promise; /** * Discriminated state union. Read via narrowing (`_state.kind === ...`); * reconnect-only fields like the gate/outbox/attempt counter are only * accessible while {@link _state.kind} is {@link AgentHostClientState.Reconnecting}, * and protocol errors are only accessible while the state is * {@link AgentHostClientState.Incompatible} or {@link AgentHostClientState.Closed}. */ private _state; /** Pending JSON-RPC requests keyed by request id. */ private readonly _pendingRequests; private readonly _authentication; private readonly _authenticationOperations; private _nextRequestId; /** /** * Reverse requests awaiting a response, scoped to their incoming transport. * An active count proves the host is waiting for client work rather than * being silently dead. */ private readonly _pendingReverseRequests; /** * Whether a liveness close has been deferred while the client was unable to * receive traffic from the host. */ private _livenessDeferred; private _livenessDeferredSince; /** Channels awaiting a post-authentication snapshot. Entries survive interrupted recovery attempts. */ private readonly _subscriptionsAwaitingRestore; /** Keeps an interrupted authentication pass pending until a replacement connection finishes it. */ private _authenticationRestorePending; /** * Timestamp of the most recent data of any kind received from the * server. Used only for diagnostic logging when the close timer fires. */ private _lastReadTime; /** * Liveness watchdog — see {@link _resetLivenessTimers}. * * {@link _pingTimer} fires after {@link PING_INTERVAL_MS} of inbound * silence and sends an application-level `ping` so we have something * to time out on. {@link _closeTimer} fires after another * {@link LIVENESS_TIMEOUT_MS} of continued silence and force-closes * the transport so the renderer's reconnect logic kicks in. If the host * has an unanswered reverse request or the local event loop has high load, * both timers re-arm instead. Once the deferral clears, it grants a full * liveness window before closing. * Both are reset on any inbound data, so busy connections generate * no ping traffic at all. * * Detects silently-dead transports (e.g. SSH/tunnel after laptop * sleep + network change) that don't produce a socket close event of * their own. */ private readonly _pingTimer; private readonly _relayKeepAliveTimer; private _relayKeepAlivePending; private readonly _closeTimer; /** * Used to suppress watchdog-triggered closes when our own JS event loop * has been pegged — in that case the silence is on our side, not the * remote's, and tearing down the transport would just generate a useless * reconnect cycle that aborts in-flight requests. */ private readonly _loadEstimator; private readonly _clientInfo; private readonly _reconnectPolicy; private readonly _prepareReconnect; private readonly _prepareAuthentication; private readonly _reconnectDeadlineTimer; private _isSuspended; private _firstSessionRequestPending; private _firstSessionOpenPending; private _connectionOperation; private readonly _resolveInitialAuthentication; private readonly _resolveAdvertisedAuthentication; private readonly _clientCertificates; private readonly _clientProxy; private readonly _onDispose; private _didDispose; /** * URIs we have already granted implicit read access for on this connection. * Uses URI-aware comparison to dedupe repeat sends and is cleared with the connection. */ private readonly _grantedImplicitReadUris; private readonly _implicitReadGrants; get clientId(): string; get address(): string; get defaultDirectory(): string | undefined; get connectionState(): AgentHostClientState; /** Deadline for the next scheduled reconnect attempt, if one is pending. */ get nextReconnectAt(): number | undefined; /** The versions offered in `initialize`; read on every connection, so the setting applies from the next one. */ private _offeredProtocolVersions; /** * The latest `initialize` response from the host, or `undefined` if * the handshake has not completed yet. Exposed observably so callers can * react as advertised capabilities (telemetry, `completionTriggerCharacters`, * `terminalCommandPrefix`, ...) arrive. */ get initializeResult(): IObservable; constructor(identity: AgentHostResourceIdentity, transportOrFactory: IProtocolTransport | (() => IProtocolTransport), options: IAgentHostProtocolClientOptions | undefined, _logService: ILogService, _resourceService: IAgentHostResourceService, _configurationService: IConfigurationService, _telemetryService: ITelemetryService, _workspaceTrustEnablementService: IWorkspaceTrustEnablementService, _workspaceTrustManagementService: IWorkspaceTrustManagementService, _workspaceTrustRequestService: IWorkspaceTrustRequestService); /** * Install a transport and wire listeners. Used both for the initial * transport and for replacements created by the factory during a * transport-level reconnect. */ private _installTransport; /** * Transition to a new {@link ClientState}. Fires {@link onDidChangeConnectionState} * only when the variant kind actually changes; in-place mutation of * reconnect-state fields (e.g. swapping the gate on a failed retry) does * NOT count as a transition and produces no event. */ private _transitionTo; private _newReconnectGate; private _newReconnectState; private _armReconnectDeadline; private _suspendReconnectDeadline; private _resumeReconnectDeadline; private _handleReconnectTimeout; private _checkReconnectState; dispose(): void; /** * Connect to the remote agent host and perform the protocol handshake. */ connect(): Promise; /** * Externally signal that the transport has closed. Used by services * managing a passive transport (SSH / dev-tunnels) when they observe * a connection-loss IPC event independent of the transport's own * onClose — without this, a single dropped IPC delivery on the * transport's close channel leaves the client stranded in * `Connected` until its watchdog fires (which can take hours when * the renderer is backgrounded and `setTimeout` is throttled). * * Idempotent — no-op if already closed or mid-reconnect. */ notifyTransportClosed(): void; /** * Called from the transport's `onClose` event. When a {@link _transportFactory} * is configured we attempt to soft-reconnect rather than fire `onDidClose` — * the protocol-level `reconnect` request lets the server replay missed * actions and preserves the `clientId` so pending tool calls etc. are not * cancelled by the host-side disconnect timeout. Without a factory * (passive-transport SSH/relay path) we fall back to "close means closed" * and let the service decide whether to spin up a fresh client. */ private _handleTransportClose; private _beginReconnectFromConnecting; /** * Reopens a terminal connection after its host has been explicitly restarted. */ reconnectFromClosed(): boolean; /** * Skips the remaining backoff and retries immediately. Returns `false` when * there is no pending retry to accelerate. */ reconnectNow(): boolean; private _scheduleReconnect; private _attemptReconnect; private _reconnectOrInitialize; /** Restore subscriptions omitted from a handshake snapshot after authentication is re-established. */ private _markSubscriptionsAwaitingRestore; /** * Re-subscribe every channel recorded by * {@link _markSubscriptionsAwaitingRestore} so it is reseated with state * from the current host process. * * A channel leaves the set once it has a fresh snapshot, the server * reported it missing, or it is no longer subscribed. A dropped transport * deliberately leaves the remaining entries in place so the next reconnect * finishes the job — that reconnect may well be answered with a `replay`, * which would otherwise never deliver the snapshot these channels need. */ private _restoreSubscriptionsAwaitingRestore; private _restoreAuthentication; private _clientMeta; private _applyInitializeResult; private _hydrateInitializedRootState; /** * Push the renderer-owned config values the host mirrors (telemetry level, * proxy discovery, migrate flag, …) as `RootConfigChanged` actions. Called on * initial connect AND on reconnect: a reconnected host may be a freshly * restarted process (or one that lost these values), and re-pushing is a cheap * no-op when nothing changed. Without this, a value read early — like the * migrate flag in `listSessions` — can be missing after a window reload. * * Most settings arrive here declaratively, via `agentHost` on their * configuration schema. The explicit calls below cover the cases a single * key-plus-transform can't express: values derived from several settings, and * settings contributed by an extension rather than by core. */ private _forwardClientConfig; /** * The host decides `multipleChatProviders` from its root config at the * handshake, but this client mirrors `multipleChatProviders.enabled` only * after it, and offers the protocol version that may advertise it only * while the setting is on. When the setting is on, the host's gate is on * (as confirmed by the host's root state), and the handshake didn't * advertise the capability, re-initialize once so the host decides again, * including when the handshake negotiated an older version because the * setting was off then. At most once until the host's gate or the setting * turns off again, so it never loops; nothing happens with the setting off. */ /** * The chat subscriptions this client holds, by holder: every one is restored after a re-initialize, so this * names the components that make a re-initialize restore many chats. */ private _describeChatSubscriptions; private _maybeReinitializeForChatProviders; private _updateDynamicAutoTiers; private _updateAutoApprovePolicyRestriction; private _updateWorkspaceTrust; /** * Apply a `reconnect` RPC result to the subscription manager. On `replay` * we feed each missed envelope through the normal action path; on * `snapshot` we reseat each named subscription with the fresh state and * advance the server seq cursor accordingly. */ private _applyReconnectResult; /** * Drain queued outgoing wire traffic after a successful soft reconnect: * * 1. Resend pending optimistic session actions that the server did NOT * echo back in the replay buffer (i.e. anything still on * {@link AgentSubscriptionManager.getPendingActions}). * 2. Flush every message that {@link _sendNotification} queued onto the * outbox while the gate was engaged. * * Replays are deduped against the outbox by `clientSeq` so a session * action that was both optimistic-tracked AND queued during the * reconnect window only goes out once. */ private _drainAfterReconnect; get rootState(): IAgentSubscription; getSubscription(kind: StateComponents, resource: URI, owner: string): IReference>; getSubscriptionUnmanaged(_kind: StateComponents, resource: URI): IAgentSubscription | undefined; getInflightSessionCreate(resource: URI): Promise | undefined; trackSessionCreate(resource: URI, promise: Promise): void; getActiveSubscriptions(): readonly IActiveSubscriptionInfo[]; dispatch(channel: string, action: SessionAction | ChatAction | TerminalAction | ClientChangesetAction | ClientAnnotationsAction | ClientAutomationAction | ClientAutomationRunAction | IRootConfigChangedAction): void; dispatchBackgroundChatAction(chat: string, action: ArtifactChatAction): Promise; dispatchConfirmed(channel: string, subscription: IAgentSubscription, action: SessionAction | ChatAction | TerminalAction | ClientChangesetAction | ClientAnnotationsAction | ClientAutomationAction | ClientAutomationRunAction | IRootConfigChangedAction, token: CancellationToken): Promise; private artifactIntegrationRequest; serveArtifactIntegrations(createServer: () => IArtifactIntegrationTransport & IDisposable, integrations: IObservable): IDisposable; /** * Subscribe to state at a URI. Returns the current state snapshot. * * For stateless channels (e.g. `ahp-otlp:` telemetry channels) use * {@link subscribeStateless} — calling this method on a stateless * channel rejects because the server omits `snapshot` on the * response. */ subscribe(resource: URI): Promise; private _subscribe; /** * Subscribe to a stateless channel — one for which the server does * not maintain replayable state and therefore omits `snapshot` from * the `subscribe` response. Used today for the host's OTLP telemetry * channels (`ahp-otlp:`). * * Returns once the subscription is confirmed by the server. * Subsequent notifications on the channel arrive via the relevant * dispatch event (e.g. {@link onDidReceiveOtlpLogs} for log records). */ subscribeStateless(resource: URI): Promise; /** * Unsubscribe from state at a URI. */ unsubscribe(resource: URI): void; /** * Dispatch a client action to the server. Returns the clientSeq used. */ private dispatchAction; /** * Create a new session on the remote agent host. */ createSession(config?: IAgentCreateSessionConfig): Promise; reportFirstResponse(diagnostic: IAgentHostFirstResponseDiagnostic): Promise; reportUserInteraction(timing: IChatUserInteractionTiming): Promise; /** Lets a host serving this client's proxy support refresh the proxy it applies after this client's settings change. */ private _notifyClientProxyChanged; removeSessionArtifact(session: URI, artifactId: string): Promise; stopBackgroundWork(chat: URI, id: string): Promise; measureWorktreeDiskUsage(root: URI, token: CancellationToken, session?: URI): Promise; sessionWorktreeCleanup(session: URI, retry: boolean, force?: boolean): Promise; listManagedWorktrees(repositories: readonly URI[]): Promise; cleanupManagedWorktree(repository: URI, worktree: URI, branch: string, force?: boolean): Promise; installSandboxCertificate(chat: string, scopeId: string): Promise; rotateSandboxCertificate(chat: string, scopeId: string): Promise; removeSandboxCertificate(chat: string, scopeId: string): Promise; refreshSubscription(resource: URI): Promise; readSavedChat(session: URI, chat?: URI): Promise; completeSavedChatContinuation(request: IAgentHostSavedChatContinuation): Promise; importSession(session: URI): Promise; moveSession(session: URI, destination: URI, after: URI | undefined): Promise; moveChat(chat: URI, destination: AgentChatMoveDestination): Promise; listAgentExtensions(session?: URI, chat?: URI): Promise; setAgentExtensionEnabled(extensionId: string, enabled: boolean, session?: URI, chat?: URI): Promise; createDetachedWorktree(session: URI, prompt: string): Promise<{ handle: string; worktree: URI; }>; setDetachedWorktreeArchived(handle: string, archived: boolean): Promise; claimDetachedWorktree(handle: string): Promise; deleteDetachedWorktree(handle: string): Promise; reconcileDetachedWorktrees(scope: string, activeHandles: readonly string[]): Promise; resolveSessionConfig(params: IAgentResolveSessionConfigParams): Promise; sessionConfigCompletions(params: IAgentSessionConfigCompletionsParams): Promise; completions(params: CompletionsParams): Promise; listAutomationTriggerDefinitions(params: ListAutomationTriggerDefinitionsParams): Promise; runAutomation(params: RunAutomationParams): Promise; deleteAutomation(resource: string, deleteHistory: boolean, legacySessions?: readonly URI[], requestId?: string): Promise; acknowledgeAutomationDeletion(requestId: string): Promise; fetchAutomationRuns(params: FetchAutomationRunsParams): Promise; /** * Send an application-level ping and wait for the server's response. * Used by {@link _watchdogTick} to keep idle connections under * watchdog supervision; safe to call from external code as well. * * The returned promise rejects with a {@link ProtocolError} if the * connection closes before a response arrives. */ ping(): Promise; /** * Returns the trigger characters captured from the `initialize` handshake. * Empty when the remote host did not announce any. */ getCompletionTriggerCharacters(): Promise; /** * Authenticate with the remote agent host using a specific scheme. */ /** Registers the handler for silent host-initiated MCP authentication requests. */ registerMcpAuthenticationHandler(handler: (request: IAgentHostMcpAuthenticationRequest) => Promise): IDisposable; registerAuthenticationTokenSealer(seal: (request: IMissionControlCredentialSealingRequest) => Promise): IDisposable; private _encryptAuthentication; private _sealAuthentication; authenticate(params: AuthenticateParams): Promise; private _getAuthenticationOperation; private _refreshRelayRootSnapshot; private _readRelayRootSnapshot; private _normalizeAuthenticationParams; private _authenticationKey; /** * Gracefully shut down all sessions on the remote host. */ shutdown(): Promise; /** * List the endpoints the remote agent host suggests probing for connectivity. */ getNetworkDiagnosticsInfo(): Promise; getManagedSettingsDiagnostics(): Promise; getSessionStateFile(session: URI, chat?: URI): Promise; collectDebugLogs(session: URI | undefined, kind: AgentHostDebugLogsArtifactKind, chat?: URI, progressToken?: string): Promise; cancelDebugLogs(progressToken: string): Promise; /** * Read one bounded slice of a debug-log artifact previously returned by * {@link collectDebugLogs}. `resource` is the agent-host URI handed out by * that call; it is unwrapped back to the host-local path here. */ readDebugLogsChunk(resource: URI, position: number): Promise; /** * Probe connectivity from the remote agent host to a single `url`. */ diagnosticsFetch(url: string): Promise; /** * Dispose a session on the remote agent host. */ disposeSession(session: URI): Promise; createChat(session: URI, chat: URI, options?: IAgentCreateChatRequestOptions): Promise; setChatWorkspace(chat: URI, workspace: IAgentCreateChatWorkspace): Promise; disposeChat(chat: URI): Promise; /** * Create a new terminal on the remote agent host. */ createTerminal(params: CreateTerminalParams): Promise; /** * Dispose a terminal on the remote agent host. */ disposeTerminal(terminal: URI): Promise; invokeChangesetOperation(params: InvokeChangesetOperationParams): Promise; /** * Send a request on an `mcp://` AHP side channel. The agent-host * routes by `params.channel` so we inject it automatically. */ handleMcpRequest(channel: string, method: string, params: Record | undefined): Promise; /** * List all sessions from the remote agent host. */ listSessions(): Promise<(IAgentSessionMetadata & { readonly workingDirectory?: URI; })[]>; /** * `value` with the default chat an older VS Code host did not advertise * ({@link getOlderHostDefaultChat}). Every full session state and summary * the host sends passes through here (subscribe, reconnect and restore * snapshots, listings, `root/sessionAdded`), so the rest of the client * reads `defaultChat` directly. A partial `root/sessionSummaryChanged` * delta is not filled: an absent field there means unchanged. Returns a * new object and never replaces an advertised value. */ private _withOlderHostDefaultChat; /** {@link _withOlderHostDefaultChat} for the session state of a snapshot; other snapshots pass through. */ private _withOlderHostSnapshot; private _toHostUri; private _toClientUri; /** * Inspect an outgoing client-dispatched action and grant implicit reads for * resources that the host will need to read after receiving the action. */ private _grantImplicitReadsForOutgoingAction; private _grantImplicitReadsForMessage; /** * Register implicit read grants for each customization URI that we are * about to send to the host. The host needs to read these to materialize * the customization, but should not need to write them. Grants are * deduped per connection and revoked when the connection closes. */ private _grantImplicitReadsForCustomizations; private _grantImplicitRead; /** * List the contents of a directory on the remote host's filesystem. */ resourceList(uri: URI): Promise; /** * Read the content of a resource on the remote host. */ resourceRead(uri: URI, encoding?: ContentEncoding): Promise; resourceWrite(params: CommandMap["resourceWrite"]["params"]): Promise; resourceCopy(params: CommandMap["resourceCopy"]["params"]): Promise; resourceDelete(params: CommandMap["resourceDelete"]["params"]): Promise; resourceMove(params: CommandMap["resourceMove"]["params"]): Promise; resourceResolve(params: CommandMap["resourceResolve"]["params"]): Promise; resourceMkdir(params: CommandMap["resourceMkdir"]["params"]): Promise; createResourceWatch(params: CommandMap["createResourceWatch"]["params"]): Promise; /** * Convenience wrapper used by {@link AHPFileSystemProvider.watch}: * runs `createResourceWatch` + `subscribe` and returns a handle that * surfaces `resourceWatch/changed` envelopes as * {@link IFileChange}[] events. Disposing the handle unsubscribes * the watch channel. */ watchResource(params: CommandMap["createResourceWatch"]["params"]): Promise; /** * Trigger the CLI-managed upgrade flow for this agent host using the * method name advertised by the server (typically * {@link VSCODE_UPGRADE_METHOD}). Callable before {@link connect} has * completed — typically used when the host has just rejected our * `initialize` with an `UnsupportedProtocolVersion` error. The * transport stays open after the rejection, so the extension request * rides over it without a special out-of-band path. * * The result mirrors the CLI's HTTP response: ok flag, whether the * upgrade is needed / started, running/latest commits. */ triggerVscodeUpgrade(method: string): Promise; private _handleMessage; private _handleFatalClose; private _handleClose; private _raceClose; /** * Handles reverse RPC requests from the server (e.g. resourceList, * resourceRead). Thin wire adapter — dispatches each frame to * {@link IAgentHostResourceService} (which owns gating, virtual reads, * and the user-prompt flow) and translates results / errors back into * JSON-RPC frames. */ private _handleReverseRequest; /** Send a typed JSON-RPC notification for a protocol-defined method. */ private _sendNotification; private _sendExtensionNotification; private _sendNotificationMessage; openTcpConnection(target: { host: string; port: number; }): Promise; private _closeTcpConnections; /** Send a typed JSON-RPC request for a protocol-defined method. */ private _sendRequest; /** Send a JSON-RPC request for a VS Code extension method (not in the protocol spec). */ private _sendExtensionRequest; /** Sends a host-specific extension request; its consumer must validate the response. */ sendHostExtensionRequest(method: `extensions/${string}` | `x-${string}`, params: unknown): Promise; private _updateTelemetryLevel; private _effectiveTelemetryLevel; /** Merge a patch into the agent host's root configuration. */ private _dispatchRootConfig; private _updateDisableRepoInfoTelemetry; private _updateTerminalAutoApproveEnabled; private _updateManagedSettingsPermissions; /** * Common path for outgoing JSON-RPC requests: queue pre-initialize traffic, * gate on any in-flight reconnect (unless explicitly bypassed for the * `reconnect` RPC itself), assign an id, register the pending deferred, and * write to the wire. * * The reconnect-gate bypass exists because the `reconnect` request is sent * from inside `_attemptReconnect` while the gate is engaged, so it can't * wait on its own resolution. */ private _dispatchRequest; private _createRequest; private _shouldLogFailedRequest; private _toError; private _rejectPendingRequests; private _recordInboundTraffic; /** * Reset the liveness timers. Called at construction for an already-open * passive transport, after a successful client-transport initialization, * once on any inbound data (which is itself proof the remote is * alive), and once after a successful soft reconnect. * * Two timers cooperate: * * 1. {@link _pingTimer} fires after {@link PING_INTERVAL_MS} of silence * and sends an application-level `ping` so the close timer has * something to time out on. Tolerates servers that don't implement * `ping` — the error response still resets both timers. * * 2. {@link _closeTimer} fires after {@link PING_INTERVAL_MS}+ * {@link LIVENESS_TIMEOUT_MS} of continued silence and force-closes * the transport so the renderer's reconnect logic kicks in. Catches * silently-dead transports (e.g. SSH/tunnel after laptop sleep + * network change) that don't emit a socket close event of their own. * It defers while the host awaits a reverse-request response or the * local event loop has high load. Once either deferral clears, it grants * a fresh full liveness window. * * After laptop sleep + wake the JS event loop is paused, so a timer * armed before sleep fires immediately after wake. That's fine — * any inbound message processed during the wake catch-up resets it * before the close handler runs. * * Reconnect recovery is supervised once its transport is established, so a * silent handshake cannot leave subscription requests gated indefinitely. * An inbound message also clears any deferred liveness state. */ private _startRelayKeepAlive; private _resetLivenessTimers; private _isWebPubSubRelay; private _cancelLivenessTimers; private _canCheckLiveness; private _onPingTimer; /** Rechecks deferrals promptly, then force-closes only after a fresh liveness window expires. */ private _onCloseTimer; private _deferLivenessCheck; /** * Get the next client sequence number for optimistic dispatch. */ nextClientSeq(): number; }