import { CancellationToken } from "../../../../../base/common/cancellation.js"; import { Emitter, Event, PauseableEmitter } from "../../../../../base/common/event.js"; import { IMarkdownString } from "../../../../../base/common/htmlContent.js"; import { Disposable, DisposableMap, DisposableStore, IDisposable, IReference } from "../../../../../base/common/lifecycle.js"; import { IObservable, IReader, ISettableObservable, ITransaction } from "../../../../../base/common/observable.js"; import { ThemeIcon } from "../../../../../base/common/themables.js"; import { URI } from "../../../../../base/common/uri.js"; import { AuthenticateParams, AuthenticateResult, type IAgentSessionChatMetadata, IAgentSessionMetadata } from "../../../../../platform/agentHost/common/agent.js"; import { AgentMergeSessionOverrides, AgentMergeSessionState } from "../../../../../platform/agentHost/common/agentMerge.js"; import { IAgentConnection } from "../../../../../platform/agentHost/common/agentService.js"; import { type AgentHostUriMapper } from "../../../../../platform/agentHost/common/agentHostUri.js"; import type { IAgentHostManagedWorktree } from "../../../../../platform/agentHost/common/agentHostWorktreeCleanup.js"; import type { RemoteAgentHostConnectionStatus } from "../../../../../platform/agentHost/common/remoteAgentHostService.js"; import { ChangesetKind } from "../../../../../platform/agentHost/common/changesetUri.js"; import type { Implementation } from "../../../../../platform/agentHost/common/state/protocol/common/commands.js"; import { type ISessionSandboxPolicy } from "../../../../../platform/agentHost/common/meta/agentSandboxPolicyMeta.js"; import { ResolveSessionConfigResult, type SessionConfigPropertySchema, type SessionConfigValueItem } from "../../../../../platform/agentHost/common/state/protocol/commands.js"; import { AgentCustomization, ChangesSummary, Customization, type CustomizationEnablement, ModelSelection, RootConfigState, RootState, SessionState } from "../../../../../platform/agentHost/common/state/protocol/state.js"; import { type SessionOrigin } from "../../../../../platform/agentHost/common/state/protocol/channels-session/state.js"; import { AgentCapabilities, AgentInfo, SessionMeta, type ISessionGitState } from "../../../../../platform/agentHost/common/state/sessionState.js"; import { IConfigurationService } from "../../../../../platform/configuration/common/configuration.service.js"; import { IInstantiationService } from "../../../../../platform/instantiation/common/instantiation.js"; import { ILabelService } from "../../../../../platform/label/common/label.service.js"; import { ILogService } from "../../../../../platform/log/common/log.service.js"; import { IDialogService } from "../../../../../platform/dialogs/common/dialogs.service.js"; import { IStorageService } from "../../../../../platform/storage/common/storage.service.js"; import { IUriIdentityService } from "../../../../../platform/uriIdentity/common/uriIdentity.service.js"; import { IWorkspaceTrustManagementService } from "../../../../../platform/workspace/common/workspaceTrust.service.js"; import { IAgentCustomizationScope } from "../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostActiveClientService.js"; import { IAgentHostActiveClientService } from "../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostActiveClientService.service.js"; import { IAgentHostMcpAppToolsService } from "../../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostMcpAppToolsService.service.js"; import { IChatWidgetService } from "../../../../../workbench/contrib/chat/browser/chat.service.js"; import { IChatService } from "../../../../../workbench/contrib/chat/common/chatService/chatService.service.js"; import { IChatSessionsService } from "../../../../../workbench/contrib/chat/common/chatSessionsService.service.js"; import { IAutomationSessionTemplate } from "../../../../../workbench/contrib/chat/common/automations/automation.js"; import { AutomationModelConfiguration } from "../../../automations/browser/automationModelConfiguration.js"; import { ILanguageModelsService } from "../../../../../workbench/contrib/chat/common/languageModels.service.js"; import { IAgentHostMcpServer, IAgentHostSessionsProvider, IAgentMergeClientState } from "../../../../common/agentHostSessionsProvider.js"; import { ChatModelSource, ChatOriginKind, IChat, IGitHubInfo, ISession, ISessionAgentRef, ISessionApplication, ISessionEnvironment, ISessionArtifact, ISessionCanvas, ISessionCanvasDefinition, ISessionCapabilities, ISessionChangesSummary, ISessionCreationReference, ISessionPreparationProgress, ISessionType, ISessionWorkspace, ISessionWorkspaceBrowseAction, ISideChatSelection, SessionRemoteConnectionStatus, SessionStatus, SessionTypeAuthRequirement, type SessionCanvasDefinitionSnapshot } from "../../../../services/sessions/common/session.js"; import { IArtifactModel } from "../../../../../platform/artifactIntegrations/common/artifactIntegration.js"; import { ISessionsService } from "../../../../services/sessions/browser/sessionsService.service.js"; import { ISessionsRecentWorkspacesService } from "../../../../services/sessions/browser/sessionsRecentWorkspacesService.service.js"; import { IAutomationSessionConfiguration, IChatMovedEvent, ISessionChatMoveDestination, IDeleteChatOptions, type INestedChatFolderInfo, type INestedChatWorkspace, type INestedChatWorkspaceSupport, type IForkChatOptions, ISendRequestOptions, ISessionChangeEvent, ISessionChangesetOperationInvokedEvent, ISessionConfigurationSnapshot, ISessionModelPickerOptions, ISessionModelsSnapshot, ISessionPermissionOption, ISessionsProviderCreateSessionOptions, ISessionWorktreeConfiguration, ICreateNewChatOptions, IHarnessPresentation, type SessionResourceResolveReason } from "../../../../services/sessions/common/sessionsProvider.js"; import { ITelemetryService } from "../../../../../platform/telemetry/common/telemetry.service.js"; import { IGitHubService } from "../../../github/browser/githubService.service.js"; import { IPullRequestIconCache } from "../../../github/browser/pullRequestIconCache.service.js"; interface IAgentHostSessionDiscoveryMetadata { readonly summary?: string; readonly modifiedTime?: number; /** Repository-less discovery intent; an actual host project still takes precedence. */ readonly workspaceless?: boolean; /** `null` is a discovery-owned absent project; `undefined` leaves the project to the host. */ readonly project?: IAgentSessionMetadata["project"] | null; readonly initiator?: Implementation; } /** The folder a chat's Agent Merge settings belong to; see {@link AgentHostSessionAdapter.getAgentMergeFolder}. */ interface IAgentMergeFolder { /** Host-authored key of the folder. */ readonly folderKey: string | undefined; /** Key of the session folder, whose settings earlier versions stored in their own keys. */ readonly sessionFolderKey: string | undefined; /** Backend working directory of the folder, which the host keys its settings by. */ readonly workingDirectory: string | undefined; } /** Copilot CLI session type */ export declare const CopilotCLISessionType: ISessionType; /** * Resolve what an agent needs before it can serve a request, from what it * advertises — rather than from a static per-type flag, which cannot track * credentials that come and go. The advertised protected-resource set already * crosses the agent-host IPC boundary and already updates reactively, so it is * the signal rather than a parallel field providers would have to keep in sync. * * An agent that still requires the GitHub Copilot protected resource needs * sign-in; one that has dropped the requirement is running on its own * credentials. Note both Claude and Codex encode "not required" by *keeping* the * Copilot resource and marking it `required: false` rather than omitting it — * that lets the host silently forward a token to an already-signed-in user * without forcing sign-in on anyone else. This treats the two identically. * * The model count is the second, load-bearing half. `required: false` alone * would read as "usable without GitHub" even for an agent that cannot serve * anything, because an agent may advertise a *static* model catalog that answers * regardless of credentials (the Claude SDK's `supportedModels()` does exactly * this). Providers are therefore expected to publish an empty catalog when they * genuinely cannot run, and an empty catalog is what distinguishes * {@link SessionTypeAuthRequirement.Unusable} from * {@link SessionTypeAuthRequirement.None} here. * * Absent resources mean the host has not resolved the agent yet, so assume * GitHub until it does. */ export declare function resolveAgentAuthRequirement(agent: AgentInfo): SessionTypeAuthRequirement; /** * Variation points the host provider supplies when building an adapter. * Differences between local and remote sessions (icon, description text, * workspace builder, optional URI mapping) flow through this options bag so * the adapter itself stays a single concrete class. */ export interface IAgentHostAdapterOptions { readonly icon: ThemeIcon; readonly environment: string; /** Loading observable wired to the provider's authentication-pending state. */ readonly loading: IObservable; /** Builds the session workspace from session metadata; provider-specific (icon, providerLabel, requiresWorkspaceTrust). */ readonly buildWorkspace: (project: IAgentSessionMetadata["project"], workingDirectories: readonly URI[] | undefined, gitHubInfo: IObservable, gitState: ISessionGitState | undefined) => ISessionWorkspace | undefined; /** Optional URI mapping for host-side file resources (remote uses `toAgentHostUri`; local uses identity). */ readonly mapDiffUri?: AgentHostUriMapper; /** Optional URI mapping for host-side working directories. */ readonly mapWorkingDirectoryUri?: AgentHostUriMapper; /** * GitHub service used to resolve the pull request that targets the * session's branch and refresh its live state. Optional so tests / hosts * without a workbench GitHub service still construct adapters; PR * affordances simply stay dormant when absent. */ readonly gitHubService?: IGitHubService; /** * Instantiation service used to construct the session's changeset * resolvers. Shared with the Copilot chat sessions provider so all * agent-host sessions surface the same set of changesets. */ readonly instantiationService: IInstantiationService; /** * Forces every chat in the session to be read-only while `true`, regardless of what the host * reported. Set when the session's backing environment is unreachable and its conversation is * being served from persisted history: the transcript is real, but nothing can be sent to a * host that no longer exists. */ readonly readOnly?: IObservable; /** Keeps normally interactive chats draftable while their connection is unavailable. */ readonly allowOfflineDrafts?: IObservable; /** * Returns the agent connection for the session, tracking replacements when a reader is provided. */ readonly getConnection: (reader?: IReader) => IAgentConnection | undefined; /** * Maps a client chat resource of this provider to its backend chat channel URI, * for operations that name a chat to the host. */ readonly getBackendChatResource?: (chat: URI) => URI | undefined; /** Agent capability lookup shared by every adapter owned by this provider. */ readonly agentCapabilities: IObservable | undefined>; /** * Agent providers a new peer chat may use on this connection, or `undefined` when the * host does not advertise chats backed by different agents (or the feature is disabled). */ readonly chatProviders?: IObservable; /** The resource scheme an agent's sessions and models are registered under on this host. */ readonly resourceSchemeForAgent?: (agentProvider: string) => string; /** Whether this provider can present server-published canvas channels for the agent. */ readonly supportsCanvasPresentation?: (agentProvider: string, connection: IAgentConnection | undefined, reader: IReader) => boolean; /** * The scheme the host addresses this session under, when it differs from the agent provider * (cloud sandbox: provider `copilot`, sessions `ahp-session:/`). Defaults to the provider. */ readonly backendSessionScheme?: string; /** Maps a backend session URI to the client resource used by this host. */ readonly mapBackendSessionResource: (resource: URI) => URI; /** * The advertised default chat of a backend session of this host, from the * session state or listing this client holds; `undefined` when neither is known. */ readonly getBackendDefaultChat: (backendSession: URI, reader: IReader | undefined) => string | undefined; /** `Changeset.changeKind` the Changes view selects by default. Defaults to `branch`. */ readonly defaultChangesetKind?: ChangesetKind.Branch | ChangesetKind.Uncommitted | ChangesetKind.Session; /** Connection state from the backing remote provider, when there is one. */ readonly connectionStatus?: IObservable; /** Keeps reported activity separate from connection availability for remotely discoverable sessions. */ readonly preserveStatusWhenDisconnected?: boolean; /** Overrides the host's external-session classification. */ readonly externalSessionState?: (resource: URI, store: DisposableStore) => IObservable; /** Uses the session title for the main conversation instead of the host's default chat label. */ readonly useSessionTitleForDefaultChat?: boolean; /** Identifies provider placeholders that must not replace an existing display title. */ readonly isSessionTitlePlaceholder?: (title: string, session: URI) => boolean; /** * Reports that the user invoked a changeset operation of this adapter's * session, once any confirmation it requires was accepted and before it runs. */ readonly onDidInvokeChangesetOperation?: (operationId: string, metadata: Record | undefined) => void; } type AgentHostSessionStateMetadata = Pick; type AgentHostSessionSummaryWorkspaceMetadata = { project?: IAgentSessionMetadata["project"]; workingDirectories?: IAgentSessionMetadata["workingDirectories"]; }; /** * Adapts an {@link IAgentSessionMetadata} into an {@link ISession} for the * sessions UI. A single concrete class for both local and remote agent * hosts — variation flows through {@link IAgentHostAdapterOptions}. */ export declare function toSessionChatOriginKind(kind: string): ChatOriginKind; export declare class AgentHostSessionAdapter extends Disposable implements ISession { private readonly _options; private readonly _acquireChatDetails; private readonly _gitHubService; private readonly _sessionsService; private readonly _pullRequestIconCache; readonly sessionId: string; readonly resource: URI; readonly providerId: string; readonly sessionType: string; readonly harness: string; readonly environment: string; readonly application: IObservable; private readonly _legacyInitiator; readonly icon: ThemeIcon; readonly createdAt: Date; readonly workspace: ISettableObservable; readonly isQuickChat: IObservable; private readonly _origin; readonly isAutomation: import("../../../../../base/common/observable.js").IObservableWithChange; readonly isExternal: IObservable; readonly remoteConnectionStatus: IObservable | undefined; readonly createdBySession: IObservable; /** See {@link ISession.worktreePending}. */ readonly worktreePending: IObservable; readonly title: ISettableObservable; private _titleIsExplicit; readonly updatedAt: ISettableObservable; readonly status: ISettableObservable; readonly completedStateIcon: IObservable; readonly modelId: ISettableObservable; readonly modelSource: ISettableObservable; modelSelection: ModelSelection | undefined; readonly mode: ISettableObservable<{ readonly id: string; readonly kind: string; } | undefined>; readonly loading: IObservable; readonly isArchived: ISettableObservable; readonly isRead: ISettableObservable; readonly description: IObservable; readonly lastTurnEnd: ISettableObservable; readonly gitHubInfo: IObservable; readonly mainChat: IObservable; readonly chats: IObservable; /** * Capabilities combine provider-local policy with the connection's live root * state. Advertised agent capabilities re-emit after hydration; provider-local * capabilities remain available independently of root-state availability. * `supportsRename`/`supportsDelete` are always supported. */ readonly capabilities: IObservable; /** * The default chat (resource == this session's resource). Always present; * for single-chat sessions it is the only chat and `chats === [it]`. */ private readonly _defaultChat; /** * The session's live output observables (per-chat last-turn changes and * customizations), parsed from the active-session subscriptions and shared by * the default chat and every peer chat so each chat's status pills reflect * that chat's own last turn. */ private readonly _sessionOutput; /** * Independent title override for the default chat tab. `undefined` means the * default chat inherits the session title; a non-empty value means the user * (or host) renamed the default chat independently of the session. */ private readonly _defaultChatTitleOverride; /** * Independent status override for the default chat tab. `undefined` means the * default chat reflects the aggregated session status (the single-chat case, * where they are equivalent); a defined value means a multi-chat session, so * the default chat shows its own status rather than the session aggregate * (which may have been promoted by a running peer chat). */ private readonly _defaultChatStatusOverride; private readonly _defaultChatIsReadOverride; private readonly _defaultChatBackendUri; /** The backend URI of the session's default chat, once its catalog or listing names one. */ readonly defaultChatBackendUri: IObservable; private readonly _defaultChatUpdatedAt; private readonly _hasMultipleChats; private readonly _aggregateChatResources; private readonly _defaultChatWorkingDirectories; /** GitHub info per folder, keyed by working-directory key and created on demand. */ private readonly _folderGitHubInfos; /** * The chats that recorded each pull request, by link key. A tool chat is * not listed, so its pull requests belong to the chat that started it. An * owner that is not a listed chat is kept, so no listed chat claims its * pull request; a record without an owner belongs to the main chat. */ private readonly _pullRequestOwners; /** Whether this session was created with worktree isolation. */ private readonly _worktreeIsolation; /** Interactivity of the default chat. Driven from the default chat's protocol summary. */ private readonly _defaultChatInteractivity; private readonly _defaultChatChangesSummary; private readonly _mainChatObs; private readonly _chatsObs; /** Additional (non-default) peer chats keyed by chatId. */ private readonly _additionalChats; private readonly _sessionOutputCache; private _chatOutputResources; /** Chat ids that have not yet sent their first request (presented as `Untitled`). */ private readonly _newChatIds; /** * The model each peer chat was given, and where it came from, keyed by chat id. * * Held outside {@link _additionalChats} because that map is rebuilt from session state: a chat * created locally can have its model set before the state carrying it arrives, and the entry * that write would have landed on may not exist yet. Seeding from here at construction keeps * the selection — and the record of where it came from, which the model-picker's precedence * depends on — from being silently dropped. */ private readonly _chatModelSelections; /** * The last {@link SessionState} applied to the chat catalog, retained so the * catalog can be re-reconciled when {@link capabilities} change after the * fact. */ private _lastCatalogState; private readonly _chatCatalogCapabilitiesObserver; private readonly _supportsChatArchive; private readonly _supportsChatReadState; private readonly _rawId; private readonly _resourceScheme; readonly agentProvider: string; /** * This session's URI as the host's registry is keyed by it, which may use a different scheme * than {@link agentProvider} (cloud sandbox: provider `copilot`, backend `ahp-session:/`). * Every backend call must address the session by this URI. */ readonly backendUri: URI; private _project; /** Discovery-owned field baselines, persisted separately from authoritative host metadata. */ discoveryMetadata: IAgentHostSessionDiscoveryMetadata | undefined; private _workingDirectories; /** Working-directory set used to resolve session customizations. */ get workingDirectories(): readonly URI[]; private _agentBaseDir; private _meta; /** The latest session metadata used to build startup-cache presentation state. */ get sessionMeta(): SessionMeta; /** Settable so authoritative session metadata can change the session kind in place. */ private readonly _isQuickChat; /** Session-kind strategy (quick chat vs. workspace), derived from {@link _isQuickChat}. */ private get _kind(); /** * Observable mirror of {@link _meta}, kept in sync with every write to * `_meta` so reactive derivations (notably {@link gitHubInfo}) re-fire * when git / GitHub state arrives (or changes). The host treats the * session-state and session-summary `_meta` as the same bag, so both git * state and GitHub state live here. */ private readonly _metaObs; /** * The session's host scratch folders (`vscode.scratchFolders`), mapped like its working directories; `undefined` * when the host reports none. Read once per `_meta` change; scratch folders are never shown or used as roots. */ private readonly _scratchFolders; /** Artifacts recorded by the agent, derived from the session's `_meta` bag. */ readonly artifacts: IObservable; private _activity; private readonly _changesSummary; get changesSummary(): IObservable; /** * Sets the aggregate change chip. Callers inside a transaction MUST pass it * — a `set` without one builds and finishes its own transaction, notifying * observers before the enclosing update has applied its remaining fields. */ setChangesSummary(changes: ChangesSummary | undefined, tx?: ITransaction): boolean; readonly isActiveSessionObs: IObservable; constructor(metadata: IAgentSessionMetadata, providerId: string, resourceScheme: string, logicalSessionType: string, _options: IAgentHostAdapterOptions, chatCatalogLoading: IObservable, _acquireChatDetails: (sessionId: string) => IDisposable, _gitHubService: IGitHubService, _sessionsService: ISessionsService, _pullRequestIconCache: IPullRequestIconCache); private _withChatDetails; /** * Reconcile the per-chat catalog from an AHP {@link SessionState}. * * The default chat (resource == this session's resource) always maps to * {@link _defaultChat}. Additional peer chats become their own {@link IChat} * whose resource carries the chatId in the URI fragment so the chat view * opens a distinct widget that the session handler routes to the matching * chat channel. * * A non-default chat surfaces as a peer tab when the session supports * multiple chats (the `copilotcli` case) OR when it is a subagent * (tool-origin) chat. Subagent chats are always surfaced as read-only peers * — independent of multi-chat support — so the user can review a worker's * transcript (the agent-team pattern). Sessions with no surfaced peers * degrade to `[defaultChat]`. */ applyChatCatalog(state: SessionState): void; applyChatMetadata(chats: readonly IAgentSessionChatMetadata[] | undefined, tx?: ITransaction): boolean; supportsChatReadState(): boolean; hasUnreadChat(): boolean; getUnreadAggregateChats(): readonly IChat[]; private _markSessionUnreadForUnreadChat; getCurrentChatMetadata(chats: readonly IAgentSessionChatMetadata[] | undefined): readonly IAgentSessionChatMetadata[] | undefined; private _updateChatOutputResources; private _applyChatCatalog; setDefaultChatRead(isRead: boolean, tx?: ITransaction): boolean; private _createAdditionalChat; /** * Maps a protocol parent-chat URI (from a Tool/Fork {@link ChatSummary.origin}) * to this session's UI chat resource: the default chat maps to the session * resource; peer chats carry their chatId in the resource fragment. */ private _resolveParentChatResource; /** The agent provider backing a chat of this session: its own when the host reported one, else the session's. */ getChatAgentProvider(chatResource: URI): string; setChatRead(chatResource: URI, isRead: boolean, tx?: ITransaction): boolean; setLegacySessionReadState(isRead: boolean, tx?: ITransaction): boolean; /** The backend chats this session lists, each with its chat resource here; tracked by `reader`. */ readChatBackends(reader: IReader): ReadonlyMap; getBackendChatResource(chatResource: URI): URI | undefined; /** Whether the host advertises the chat as a move source; a session's default chat never is. */ isChatMovable(chatResource: URI): boolean; /** * Whether the chat works in a host scratch folder that another chat of this session (other than its subagent chats, * which move with it) also works in, so the host refuses to move it on its own. Forks of the chat share its folder * and stay. Read from summaries when explaining a refusal only. */ chatSharesScratchFolder(chatResource: URI): boolean; /** * The session folder a new nested chat works in by default: the default chat's first folder that is not a host * scratch folder; `undefined` in a workspace-less session. Reads cached summaries only, tracked by `reader`. */ getNestedChatSessionFolder(reader: IReader | undefined): URI | undefined; /** The branch and repository label when the session's own folder is a git worktree; `undefined` otherwise. */ getNestedChatSessionFolderWorktree(reader: IReader | undefined): { readonly branch: string | undefined; readonly repositoryLabel: string | undefined; } | undefined; /** Whether `chat` is one of the backend chats this session's catalog lists. */ ownsBackendChat(chat: string): boolean; /** Mark a peer chat new so it shows as `Untitled` until its first request. */ markChatAsNew(chatId: string): void; /** Clear the `new` flag after the chat's first request is sent. */ markChatAsSent(chatId: string): void; setChatModelId(chatResource: URI, modelId: string | undefined, source: ChatModelSource): void; setChatAgent(chatResource: URI, agent: ISessionAgentRef | undefined): void; /** * Reconcile the selected custom-agent URI against the host's current agent * list — e.g. the session graduated with an agent picked in the original repo * but now runs in an isolated worktree, where the host reports the same agent * file under the worktree path. * * The selection is rebased by matching the agent's repo-relative path against * the available agents (which already carry the worktree root) rather than the * session's reported working directory. The working directory is unreliable * here: the worktree-pathed customizations arrive well before either the * `SessionSummary` or `SessionState` working-directory flips to the worktree, * so a working-directory-keyed rebase would miss the window and let the picker * destructively reset the selection. Deriving the worktree root from the agent * list closes that race. * * Mirrors the agent-host backend's code to rebase by relative path. * The re-point is only applied to a URI that actually exists in * the supplied agent list, so it never runs ahead of the host reporting the * worktree agents (which would otherwise re-introduce the mismatch it fixes). */ reconcileSelectedAgent(agents: readonly AgentCustomization[]): void; /** * Finds an available agent that is the same repo-relative file as the current * selection but rooted under a different directory (its worktree twin). * * A candidate matches when its path ends with `/` on a path-segment * boundary and the implied root (the candidate path minus that suffix) differs * from `base`. The root is re-validated with `relativePath` so only a genuine * relocation of the same file is accepted. Returns the matched agent's URI and * its derived root, or `undefined` when there is no twin. */ private _findRelocatedAgent; /** * Seed the selected custom agent when a session is resumed (e.g. after a * window reload). A freshly loaded adapter starts with `mode === undefined`; * the host persists the selection on the default chat's `ChatState.draft.agent`, * which the provider reads and mirrors onto `session.mode` here. Guarded to * never override a live selection (a Part 1 graduation seed or a user pick), * keeping this a resume-only hydration. */ hydrateSelectedAgent(agentUri: string): void; /** * As {@link hydrateSelectedAgent}, for the model the session was last running on. * * {@link ChatModelSource.Chosen} because that is what it is: the session's own model, read back * from where the host persisted it. Without this a reopened session reports no model at all, * and model selection cannot tell it from one that has never had a model. */ hydrateSelectedModel(selection: ModelSelection): void; getChatModelId(chatResource: URI): string | undefined; getChatModelSelection(chatResource: URI): ModelSelection | undefined; getChatMode(chatResource: URI): { readonly id: string; readonly kind: string; } | undefined; /** Optimistically set the default chat tab title (independent of the session title). */ setDefaultChatTitle(title: string): void; /** Optimistically set an additional peer chat's title ahead of the host's `chatUpdated`. */ setAdditionalChatTitle(chatId: string, title: string): void; private _toModelSelection; /** The scheme the models of a chat's agent are registered under; the session's own for its agent. */ getChatModelScheme(chatResource: URI): string; private _getAdditionalChat; /** * Update fields from a refreshed metadata snapshot. Returns `true` iff * any user-visible field changed. */ update(metadata: IAgentSessionMetadata): boolean; setTitleFromHost(title: string, tx?: ITransaction): boolean; get titleIsExplicit(): boolean; setTitleFromUser(title: string): void; /** * Sets the activity text from a `SessionSummaryChanged` notification. * Returns `true` iff the activity observable changed. Callers inside a * transaction MUST pass it — see {@link setChangesSummary}. */ setActivity(activity: string | null | undefined, tx?: ITransaction): boolean; /** * Apply a `_meta` delta (the shared session-state / session-summary bag, * fed from `_applySessionMetadataFromState` or a `SessionSummaryChanged` * notification), synchronize the session kind, and rebuild the workspace. * Returns `true` iff anything observable changed, so the list regroups a * session whose kind changed even when its workspace did not. * * Callers that are already inside a transaction MUST pass it: a plain * `transaction()` here would finish (and therefore notify) mid-way through * the enclosing one, letting observers of `_meta` / `isQuickChat` / * `workspace` read a torn snapshot of the fields the caller has not applied * yet. */ setMeta(meta: SessionMeta | undefined, tx?: ITransaction): boolean; /** * Applies the workspace-bearing fields from authoritative session state in * one transaction so observers cannot see a converted session paired with * its previous working directory. On the first state snapshot, absent * optional fields retain catalogue metadata for compatibility; a later * present-to-absent transition clears them. */ applySessionStateMetadata(metadata: AgentHostSessionStateMetadata, previous: SessionState | undefined): boolean; /** * Applies project and working-directory fields from a session-summary delta. * Property presence distinguishes an omitted field from an explicit clear. */ applySessionSummaryWorkspaceMetadata(metadata: AgentHostSessionSummaryWorkspaceMetadata, tx: ITransaction): boolean; refreshWorkspace(): boolean; get origin(): SessionOrigin | undefined; setOrigin(origin: SessionOrigin | undefined, tx?: ITransaction): boolean; /** Records that this session runs with worktree isolation. See {@link worktreePending}. */ setWorktreeIsolation(isolated: boolean): void; private _syncQuickChatFromMeta; /** * The session's project. Read at persist time so a value assigned after the snapshot was taken * is not lost on the next save. */ get project(): IAgentSessionMetadata["project"]; /** Refresh discovery-owned fields without overwriting fields changed by the host. */ updateDiscoveryMetadata(metadata: Pick, workspaceless?: boolean): boolean; /** * Assign a project to a session that was materialized without one, recomputing the workspace. * Refuses when the session already has a project. * * Narrower than {@link update}, which also assigns `_workingDirectories` and would clear real * working directories, revert a renamed title, and roll back the modified time. */ backfillProject(project: IAgentSessionMetadata["project"]): boolean; private _setWorkspace; /** * Resolves the session workspace. Quick chats stay workspace-less * (`undefined`) regardless of any scratch working directory the host * assigned; workspace sessions build from project/git metadata. */ private _computeWorkspace; /** This session's working directories without its host scratch folders. */ get userWorkingDirectories(): readonly URI[]; /** The session's host scratch folders, mapped like its working directories; empty when the host reports none. */ get scratchFolders(): readonly URI[]; private _mapWorkingDirectory; /** A workspace of a chat's own folders, for a chat with folders of its own in a session without a workspace. */ private _buildOwnWorkspace; /** Adds live pull request presentation (icon, state, title) to GitHub info. */ private _presentGitHubInfo; /** * Icon of the pull requests attributed to `chat`, wherever in the session * they were found. A recorded pull request belongs to the chats that * recorded it. Otherwise, the session folder's belong to the main chat, * whose first folder the session folder is, and any other folder's belong * to the chats working in it. Prefers pull requests the session produced * over ones it only references or inherited from its checkout. */ private _getChatPullRequestIcon; /** Working-directory key of the session folder, the main chat's first folder. */ private _getSessionFolderKey; private _getSessionFolderWorkingDirectory; /** * The folder whose Agent Merge settings `chat` uses — its first folder, or * the session folder (the main chat's first folder) for the main chat or * when omitted. `undefined` while a peer chat's folders are still loading, * so its settings are never mistaken for the session folder's. */ getAgentMergeFolder(chat: URI | undefined, reader?: IReader): IAgentMergeFolder | undefined; /** Resolves the GitHub info each session folder reports from its own state. */ private _getFolderGitHubInfoResolver; private _getChatScopeGitState; private _createChatCurrentTurnChangesObservable; /** Background shells come from the chat channel, which is only subscribed while the session is active. */ private _createChatBackgroundShellsObservable; private _createChatCanvases; /** * Observes the canvases of one chat of this session without the active-session gate, so * a pinned canvas can find its live canvas again without showing its chat. The host counts * the chat subscription as a subscriber of this session, so holding the reference keeps it resident. */ observeChatCanvases(backendChat: URI): IReference>; /** * Observes one canvas of this session without the active-session gate. The host * counts the canvas subscription as a subscriber of its owning session, so holding * the reference keeps that session resident. */ observeCanvas(canvasResource: URI): IReference>; } /** * `kind` literal used on `ISession.mode` when the mode slot carries a * custom-agent selection. The `mode.id` is then the agent's URI. */ export declare const AGENT_MODE_KIND = "agent"; /** * Inputs needed to construct a {@link NewSession}. */ interface INewSessionConstructionContext { /** * Workspace the session is scoped to, or `undefined` for a **quick chat** * (a workspace-less session not bound to any folder). When `undefined`, * {@link quickChat} must be `true` and the backend session is created with * no `workingDirectory` (the host assigns a throwaway scratch cwd). */ readonly workspace: ISessionWorkspace | undefined; /** * `true` when this is a quick chat (see {@link workspace}). Forwarded to the * agent host on `createSession` so the session is tagged and routed as * workspace-less. */ readonly quickChat?: boolean; readonly sessionType: ISessionType; readonly providerId: string; readonly icon: ThemeIcon; readonly resourceScheme: string; /** * The URI scheme used to reconstruct this draft's backend (wire) session URI, * when it differs from the agent provider ({@link sessionType}.id). Defaults to * the agent provider. Cloud sandbox creates sessions under `ahp-session:/` * while the agent provider is `copilot`; the eager backend `createSession`/ * subscribe must use this scheme so it matches the handler's create path. */ readonly backendSessionScheme?: string; readonly authenticationPending: IObservable; readonly logService: ILogService; /** * Optional initial config values to seed into the new session before its * first {@link NewSession.resolveConfig} round-trip. Used to forward * `chat.permissions.default` into the agent host's `autoApprove` slot and * `git.branchPrefix` into the `worktreeBranchPrefix` slot so the values are * present from the very first `resolveConfig`/`createSession`. */ readonly initialConfigValues?: Record; readonly resolveInitialPermissionConfig?: (config: ResolveSessionConfigResult) => Record; readonly initialModeId?: string; /** Pull request the backend session is created from; requires a host that supports pull request sessions. */ readonly initialPullRequestUrl?: string; /** Provider-owned Automation values restored before the first configuration resolution. */ readonly initialSessionTemplate?: IAutomationSessionTemplate; /** Model selected specifically for this draft. */ readonly initialModelId?: string; /** Model-specific primitive values scoped specifically to this draft. */ readonly initialModelConfiguration?: Readonly>; /** * Optional property schemas to seed into the new session's config before its * first {@link NewSession.resolveConfig} round-trip. Carried over from the * provider's cache of well-known chips (isolation/branch) so those chips stay * visible (disabled) while the draft re-resolves, instead of blanking. */ readonly initialConfigSchema?: Record; readonly initialMetadata?: Record; /** * Instantiation service used to construct the session's changeset * resolvers, so the new-session skeleton surfaces the same changeset * list as the committed session that replaces it. */ readonly instantiationService: IInstantiationService; /** * Forwards `SessionState` snapshots from the eagerly-held wire * subscription back to the provider. `state === undefined` is a * cleanup sentinel emitted by {@link NewSession.dispose} on the * close-without-graduation path so the provider can drop any cached * entry it accumulated for this session. The graduation path skips * this sentinel because the running-session subscription pipeline * takes over ownership of the same `sessionId` key. */ readonly onSessionState?: (sessionId: string, state: SessionState | undefined) => void; readonly onSessionCreated: (backendSession: URI) => void; readonly onSessionUsed: (sessionId: string) => void; readonly activeClientScope: IAgentCustomizationScope; } /** * Bundles the at-most-one in-flight "new session" — the session being * composed in the new-chat view before the first message is sent. * * Encapsulates: * - the `ISession` skeleton + its observables (status, modelId, loading) * - the user's selected model (read by `sendRequest`) * - the resolved session config + a stale-request guard * - the eagerly created backend session (URI + subscription) that lets the * chat handler skip its legacy `createSession`-on-first-message round-trip * * Lifecycle: * - {@link eagerCreate} fires `connection.createSession` then opens a state * subscription. Wire ordering matters — see the comment in the body. * - {@link graduate} releases the subscription without firing * `disposeSession`; called when the session successfully transitions into * a real running session via `sendRequest`. * - {@link Disposable.dispose}/`dispose` releases the subscription **and** * fires `connection.disposeSession`; called when the user abandons the * new session (workspace switch, send failure, etc.). */ declare class NewSession extends Disposable { private readonly _options; private readonly _configurationService; readonly session: ISession; readonly sessionId: string; readonly agentProvider: string; /** This draft's URI as the host's registry is keyed by it. */ readonly backendUri: URI; readonly workspaceUri: URI | undefined; readonly requiresWorkspaceTrust: boolean; /** `true` when this is a workspace-less quick chat. */ readonly isQuickChat: boolean; /** Session-kind strategy chosen once at construction (quick chat vs. workspace). */ private readonly _kind; private readonly _status; private readonly _title; private readonly _modelId; private readonly _modelSource; private readonly _mode; private readonly _workspace; private readonly _changesets; private readonly _worktreePending; private readonly _description; private readonly _isNewSessionRequestInProgress; readonly preparationProgress: ISettableObservable; private readonly _newSessionRequestActivities; private _newSessionRequestId; private readonly _isActiveSessionObs; private readonly _loading; private readonly _mainChat; private _selectedModelId; private _selectedAgent; private _selectedAgentSource; observeClientCustomAgents(customAgents: IObservable, onDidChange: () => void): void; getClientCustomAgents(): readonly AgentCustomization[]; getClientAgentSourceUri(uri: URI): URI; /** * Latest resolved config. Replaces what used to live in `_newSessionConfigs`. * `undefined` indicates the most recent {@link resolveConfig} failed and no * cached values are usable. */ private _config; private _configResolution; private _configOperation; private _unresolvedConfigValues; private readonly _explicitlySetConfigProperties; private _branchLoad; /** * Monotonic counter for in-flight {@link resolveConfig} calls. Each call * increments the counter and only writes its result back if its sequence * is still the latest one. Bumped on dispose so any pending resolve * discards itself. */ private _configRequestSeq; private _hasResolvedConfig; private _initialConfigError; private _lastResolvedConfigSchema; /** * `true` while a `resolveConfig` round-trip is in flight. Distinct from * {@link ISession.loading} which also stays true when required config * values are missing — pickers gate on this so they stay interactive * in that state. Set sync in {@link beginResolveConfigSync} so the * optimistic `onDidChangeSessionConfig` pulse already exposes it. */ private readonly _isResolvingConfig; private readonly _lifetimeCts; private _eagerCreateTask; private _eagerCreateSuspended; /** Backend session URI, set immediately before the eager `createSession` call. */ private _backendUri; /** The created session's advertised default chat, once known. */ private _defaultChatUri; /** Connection used to create the backend session, captured for `disposeSession` on tear-down. */ private _connection; /** Held state subscription. Set after the wire `createSession` resolves. */ private _subscription; /** Held default-chat subscription used to publish the draft's changesets. */ private _chatSubscription; /** * `onDidChange` listener for {@link _subscription}. Forwards every * `SessionState` snapshot to the provider via {@link _onSessionState} * so the new session's customizations (and any other state) reach * `_lastSessionStates` while the session is still Untitled. Detached * in {@link graduate} (handoff) and {@link dispose} (close-without-send). */ private readonly _stateListener; private readonly _chatStateListener; /** Waits for the created session's state to advertise its default chat. */ private readonly _defaultChatWatch; /** * Autorun republishing active-client changes for this draft. Cleared in * {@link graduate} so the session handler's own reconciliation owns * republishing from then on, and the two never race. */ private readonly _activeClientPublisher; private readonly _onSessionState; private readonly _onSessionCreated; private readonly _onSessionUsed; private _hasBeenUsed; get hasBeenUsed(): boolean; private readonly _activeClientScope; private readonly _initialMetadata; private readonly _initialSessionTemplate; private readonly _resolveInitialPermissionConfig; private readonly _initialModeId; private readonly _initialPullRequestUrl; readonly modelConfiguration: AutomationModelConfiguration; get initialMetadata(): Record | undefined; private readonly _logService; private readonly _providerId; constructor(ctx: INewSessionConstructionContext, _options: IAgentHostAdapterOptions, sessionsService: ISessionsService, languageModelsService: ILanguageModelsService, _configurationService: IConfigurationService); /** Re-reads the isolation pick from the cached config into {@link _worktreePending}. */ private _syncWorktreePending; setSelectedModelId(modelId: string, source: ChatModelSource): void; getSelectedModelId(): string | undefined; clearSelectedModelId(): void; getSelectedModel(): ModelSelection | undefined; /** Untitled skeleton title used until the first request commits the session. */ get untitledTitle(): string; setSelectedAgent(agent: ISessionAgentRef | undefined, source?: ISessionAgentRef | undefined): void; getSelectedAgent(): ISessionAgentRef | undefined; getSelectedAgentSource(): ISessionAgentRef | undefined; getInitialSessionTemplate(): IAutomationSessionTemplate | undefined; clearSelectedAgent(): void; setStatus(status: SessionStatus): void; startRequest(activity: string | undefined): IDisposable; setLoading(loading: boolean): void; setTitle(title: string): void; /** Applies the session's Git and GitHub state; `sessionWorkingDirectory` is the backend URI of its first folder. */ applySessionMeta(meta: SessionMeta | undefined, sessionWorkingDirectory: string | undefined): boolean; getConfig(): ResolveSessionConfigResult | undefined; getConfigForWrite(): ResolveSessionConfigResult | undefined; getConfigValues(): Record | undefined; /** Only pre-warming benefits from a folder draft, so other drafts keep the picked isolation. */ private _createsInPickedFolder; private _getIsolationProperty; /** * The config the backend draft is created with. With session pre-warming * on, isolation stays local until Send: the draft is created in the picked * folder even when the user picked * (or inherited) a worktree, so the host can pre-warm it, and the first * request sends the picked isolation with the rest of the draft's config * (`AgentHostSessionHandler`). The host creates a picked worktree on that * first send and discards the folder warm-up. The worktree base branch is * dropped with the isolation, so the folder draft uses its checked-out * branch until Send. */ private _getEagerCreateConfigValues; trackConfigResolution(promise: Promise): Promise; waitForConfigResolution(): Promise; trackConfigOperation(operation: Promise): void; /** Whether the backend session may only be created with the resolved initial permissions, mode, or pull request. */ private get _requiresResolvedInitialConfig(); /** Explicit consumers can retry missing configuration; background prewarming only waits. */ waitForConfigurationReady(retryResolution?: () => Promise): Promise; private _clearConfigResolution; private _clearConfigOperation; /** * Optimistically updates a single property in the cached config. * An undefined value removes the property. * Preserves the existing schema so schema-driven pickers don't flash * during the async re-resolve. {@link resolveConfig} replaces both * schema and values when its response lands. */ setConfigValue(property: string, value: unknown, explicitlySet?: boolean): void; wasConfigValueExplicitlySet(property: string): boolean; /** * `true` while a {@link resolveConfig} round-trip is in flight. See * {@link _isResolvingConfig} for why this is distinct from {@link ISession.loading}. */ get isResolvingConfig(): IObservable; get cancellationToken(): CancellationToken; /** Mark a resolve as starting before the optimistic event fires. */ beginResolveConfigSync(): void; /** * Clear the in-flight flag for early-return paths that skip * {@link resolveConfig} (e.g. no connection), where the `finally` * cleanup never runs. */ endResolveConfigSync(): void; /** * Re-resolves the session config against the agent host using the * currently cached values. Ignores its own response if a newer call * superseded it. Returns `true` if the config was applied (i.e. this * call was not stale by the time the response arrived). On failure, the * cached config is cleared so {@link getConfig} returns `undefined`. * @param strict Rethrow the latest resolution error instead of treating the refresh as best effort. */ resolveConfig(connection: IAgentConnection, strict?: boolean): Promise; getConfigCompletions(connection: IAgentConnection, property: string, query: string | undefined): Promise; loadBranches(connection: IAgentConnection): Promise; /** * Eagerly create the session on the agent host so the chat handler can * skip its legacy `createSession`-on-first-message round-trip. * * Wire ordering matters: we must `createSession` *before* opening the * subscription. Subscribing first would race the wire send — the server * receives the `subscribe` before the `createSession` and rejects it as * `AHP_SESSION_NOT_FOUND`, leaving the client subscription in an * unrecoverable error state. The session handler would then fall back * to its legacy create-and-subscribe path on the user's first send, * issuing a duplicate `createSession`. * * If the user switches workspaces or graduates this session before the * `createSession` round-trip completes, this object will have been * disposed (and `_backendUri` cleared) — the bail-out check below skips * opening a stale subscription. * * Failures are non-fatal: the legacy first-message path in * `AgentHostSessionHandler._invokeAgent` re-issues `createSession` if * no session state exists at send time. * * The session is created in the picked folder whatever isolation the * draft shows; see {@link _getEagerCreateConfigValues}. */ eagerCreate(connection: IAgentConnection, canCreate: (() => Promise) | undefined, isAllowed: () => boolean): void; /** Release passive state while preserving the local unsent draft. */ suspend(): void; waitForEagerCreate(): Promise; private updateChatState; private updateChangesets; /** * Release the backend subscription without firing `disposeSession`. * Used on the success path in `sendRequest` when the session has * graduated into a real running session. */ graduate(): void; dispose(): void; } export declare abstract class BaseAgentHostSessionsProvider extends Disposable implements IAgentHostSessionsProvider { protected readonly _chatSessionsService: IChatSessionsService; protected readonly _chatService: IChatService; protected readonly _chatWidgetService: IChatWidgetService; protected readonly _languageModelsService: ILanguageModelsService; protected readonly _baseConfigurationService: IConfigurationService; protected readonly _logService: ILogService; protected readonly _gitHubService: IGitHubService; protected readonly _instantiationService: IInstantiationService; protected readonly _sessionsService: ISessionsService; protected readonly _activeClientService: IAgentHostActiveClientService; private readonly _mcpAppToolsService; protected readonly _storageService: IStorageService; protected readonly _dialogService: IDialogService; protected readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService; protected readonly recentWorkspacesService: ISessionsRecentWorkspacesService; protected readonly _uriIdentityService: IUriIdentityService; abstract readonly id: string; abstract readonly label: string; abstract readonly environment: ISessionEnvironment; abstract readonly icon: ThemeIcon; abstract readonly browseActions: readonly ISessionWorkspaceBrowseAction[]; readonly usesCombinedNewSessionConfigPicker = true; readonly supportsModelConfigurationForCreation = true; readonly supportsPermissionsForCreation = true; readonly supportsAutomationSessionConfiguration = true; getPermissionOptionForSession(sessionId: string): ISessionPermissionOption | undefined; getComparisonPermissionOptionForSession(sessionId: string, sessionTypeId: string): ISessionPermissionOption | undefined; get order(): number; get sessionTypes(): readonly ISessionType[]; protected _sessionTypes: ISessionType[]; private _lastAgents; private readonly _agentCapabilities; protected readonly _onDidChangeSessionTypes: Emitter; readonly onDidChangeSessionTypes: Event; protected readonly _onDidChangeSessions: PauseableEmitter; private readonly _onDidChangeSessionsFromNotifications; protected readonly _onDidChangeSessionsImmediately: Event; readonly onDidChangeSessions: Event; protected readonly _onDidChangeDraftSessions: Emitter; protected readonly _onDidReplaceSession: Emitter<{ readonly from: ISession; readonly to: ISession; }>; readonly onDidReplaceSession: Event<{ readonly from: ISession; readonly to: ISession; }>; private readonly _onDidInvokeChangesetOperation; readonly onDidInvokeChangesetOperation: Event; protected readonly _onDidChangeSessionConfig: Emitter; readonly onDidChangeSessionConfig: Event; private readonly _onDidChangeAgentMergeSessionState; protected readonly _onDidChangeRootConfig: Emitter; readonly onDidChangeRootConfig: Event; protected readonly _onDidChangeCustomAgents: Emitter; readonly onDidChangeCustomAgents: Event; protected readonly _onDidChangeCustomizations: Emitter; readonly onDidChangeCustomizations: Event; readonly onDidChangeModels: Event; /** Last-known root config state (schema + values), seeded from `RootState.config`. */ protected _rootConfig: RootConfigState | undefined; /** * Last-known session state per session ID, seeded from * {@link _applySessionStateUpdate}. Holds the snapshot used to extract * `customizations` and `activeClient.customizations` for the picker. */ protected readonly _lastSessionStates: Map; /** Fires when {@link _lastSessionStates} or {@link _sessionCache} changes, for readers of a backend session's default chat. */ private readonly _backendSessionsChanged; /** Cache of adapted sessions, keyed by exact backend resource. */ private readonly _chatMoveTracker; readonly onDidMoveChat: Event; protected readonly _sessionCache: Map; private readonly _sessionKeysByResource; protected _refreshSessionWorkspaces(): void; /** * Storage key under which {@link _sessionCache} snapshots are persisted, or * `undefined` while persistence is disabled. Set via * {@link _enableSessionCachePersistence}, which subclasses call once their * identity fields are ready. When `undefined`, the cache is in-memory only. */ private _sessionCacheStorageKey; /** * Snapshot of the source metadata for each adapter in {@link _sessionCache}, * keyed by exact backend resource. Captured in {@link createAdapter}/{@link updateAdapter} * and re-used by {@link _persistCache} to serialize sessions without having to * reconstruct every `IAgentSessionMetadata` field from observables. */ private readonly _metadataBySession; /** Un-adopted legacy Copilot CLI rows opened from this list, watched until the host adopts them. */ private readonly _adoptableRowOpens; /** * Set when {@link _sessionCache} has changed since the last persist. The * actual write happens on the next `onWillSaveState` signal from * {@link IStorageService} so that bursts of notifications do not repeatedly * re-serialize the whole cache. */ private _cacheDirty; /** * Renders the agent host's lazy, first-use SDK download as a notification * progress bar. Shared with the editor window so both surfaces render * download progress identically. Fed by the `NotificationType.Progress` * frames received in {@link _attachConnectionListeners}. */ private readonly _downloadProgress; /** * Temporary sessions that have been sent (first turn dispatched) but not yet * committed by the backend session list. Shown in the session list until the * server reports each backend session, at which point it is replaced via * {@link _onDidReplaceSession}. */ protected readonly _pendingSessions: Map; /** * In-flight new sessions — sessions being composed in the new-chat view * before their first message is sent, keyed by `sessionId`. See * {@link NewSession} for the encapsulated state and lifecycle. * * Held as a {@link DisposableMap} so multiple new sessions can be tracked * concurrently (e.g. while one is sending in the background and the composer * re-seeds a fresh one). Entries are disposed individually when sent * ({@link deleteAndDispose}/{@link deleteAndLeak}) or abandoned (via * {@link deleteNewSession}), and all remaining entries are cleaned up when * the provider itself is disposed. */ private readonly _newSessions; /** Keep abandoned drafts hidden until their backend removal is confirmed. */ private readonly _unpublishedDraftSessions; /** The in-flight new session with the given id, if any. */ protected _getNewSession(sessionId: string): NewSession | undefined; private _isUnpublishedDraft; private _publishUsedDraft; getBackendSessionResource(sessionId: string): URI | undefined; protected _getBackendSessionUri(sessionId: string): URI | undefined; protected _hasSession(sessionId: string): boolean; /** * Dispose every in-flight new session, firing each one's `disposeSession` * sentinel so the eagerly-created backend records are freed. Used when the * connection drops and the composed-but-unsent drafts can no longer commit. */ protected _disposeAllNewSessions(): void; deleteNewSession(sessionId: string): void; protected _onNewSessionAbandoned(_sessionId: string, _reason: "discarded" | "sendFailed" | "providerDisposed"): void; protected _getSessionMetadata(sessionId: string): Record | undefined; protected _getSessionMetadataByKey(rawId: string): Record | undefined; /** Full resolved config (schema + values) for running sessions, keyed by session ID. */ protected readonly _runningSessionConfigs: Map; /** * Chat-state subscriptions that supply a chat's own config values, keyed by * backend chat. Created when a chat's config is read and released after * {@link SESSION_STATE_SUBSCRIPTION_IDLE_MS} without reads; the connection * reference-counts them, so an open chat shares its existing subscription. */ private readonly _chatConfigSubscriptions; /** Triggers when a chat config subscription is acquired or released, so held resolving observables follow it. */ private readonly _onDidChangeChatConfigSubscriptions; /** * Backend chats whose config subscription failed, with the session's chat catalog at that time: such a * chat shows its session's values, and is subscribed again once its session's catalog changes. */ private readonly _failedChatConfigs; /** Triggers when a session's chat catalog changes, so the active chats' config subscriptions follow it. */ private readonly _onDidChangeChatCatalogs; private readonly _chatConfigIdleTimers; /** Backend chats active in a visible session, whose config subscriptions are held without an idle timer. */ private readonly _pinnedChatConfigs; private readonly _runningSessionConfigResolveSeq; private readonly _runningModelConfigurations; /** * Model configuration a side chat inherited from its source chat's turn, keyed by chat * resource. Per chat rather than per session so it cannot change the session's other chats; * consumed by the chat's first committed request. */ private readonly _carriedOverChatModelConfigurations; /** * Last authoritatively-resolved schemas for {@link SEEDED_CONFIG_SCHEMA_KEYS}, * seeded into new drafts so their chips survive a workspace/agent switch. Lives * on the provider (not the picker) so it outlives toolbar item reconstruction. */ private readonly _cachedConfigSchemas; /** * Lazy session-state subscriptions used to seed {@link _runningSessionConfigs} * for sessions that already exist on the agent host (e.g. created in a prior * window). The underlying wire subscription is reference-counted by * {@link IAgentConnection.getSubscription}, so when the session handler is * also subscribed (i.e. chat content is loaded) no extra wire subscribe is * issued. Each entry is released after * {@link SESSION_STATE_SUBSCRIPTION_IDLE_MS} of no calls into the keep-alive * helper, so the server-side refcount can drop and any idle restored session * state can be evicted on the agent host. Keyed by session ID. */ protected readonly _sessionStateSubscriptions: DisposableMap; protected readonly _connectionChanged: import("../../../../../base/common/observable.js").IObservableSignal; private _chatProvidersObs; /** * Agent providers a new peer chat may use: those advertising multiple chats and not * disabled by policy, only while the connection advertises chats backed by different * agents, the host's root config still allows them (another window can turn them off * after the handshake), and the user enabled the feature. */ protected get _chatProviders(): IObservable; private readonly _chatCatalogLoading; private readonly _agentMergeSessionStateSubscriptions; private readonly _agentMergeSessionStateIdleTimers; /** Per session, then per chat (`''` for the session folder). */ private readonly _agentMergeSessionStateObservables; /** Number of observed Agent Merge state observables per session. */ private readonly _observedAgentMergeSessionStates; /** Every Agent Merge folder seen per session; see {@link _getAgentMergeValues}. */ private readonly _agentMergeFolders; /** * Idle-release timers paired with {@link _sessionStateSubscriptions}. Each * call to {@link _keepSessionStateAlive} resets the timer for `sessionId`; * when the timer fires, the subscription is disposed and the wire * `unsubscribe` flows through {@link IAgentConnection.getSubscription}'s * refcount to the agent host. */ private readonly _sessionStateIdleTimers; /** Consecutive `onDidError` retry count per session while chat-details references are held. */ private readonly _sessionStateErrorRetries; private static readonly MAX_SESSION_STATE_ERROR_RETRIES; private readonly _sessionChatDetailsReferences; /** Session-state subscription stores whose draft hydration has not started; see {@link _ensureDraftHydration}. */ private readonly _pendingDraftHydrations; private readonly _chatModelRetentionLeases; /** * Session ids whose views are currently visible in the Agents window. Their * state subscription is pinned open (no idle release) so host-driven catalog * changes the user did not initiate — most importantly spawned subagent chats * ({@link ChatOriginKind.Tool}) — keep flowing into `cached.chats` while the * session is on screen. Without this, the idle timer (only refreshed by * client-initiated actions/queries) can release the state listener mid-view, * so a subagent's `chatAdded` is dropped and its inline "Open Subagent" pill * cannot resolve until the session is re-subscribed (e.g. switched away and * back). Driven by {@link _syncVisibleSessionStatePins}. */ private readonly _pinnedSessionStates; /** Sessions whose draft hydration was explicitly requested; re-applied when their subscription is recreated. */ private readonly _hydrationRequestedSessions; protected _cacheInitialized: boolean; private static readonly SESSION_REFRESH_RETRY_MIN_MS; private static readonly SESSION_REFRESH_RETRY_MAX_MS; /** * Backoff timer that retries {@link _refreshSessions} after a failed * attempt. A failed initial list (e.g. the agent threw * `AHP_AUTH_REQUIRED` because its token wasn't yet effective server-side, * or a transient offline/network error) must not leave the session list * permanently empty. The timer is armed only on failure and cancelled on * the next successful refresh. */ private readonly _sessionRefreshRetry; private readonly _artifactIntegrations; /** Current backoff delay (ms) for the session-refresh retry. */ private _sessionRefreshRetryDelay; /** True while a {@link _refreshSessions} call is awaiting `listSessions()`. */ private _sessionRefreshInFlight; private _sessionRefreshGeneration; private readonly _activeSessionScope; private readonly _activeClientSyncCancellation; private _activeSessionScopeSessionType; private _activeSessionScopeRoots; private readonly _lastPublishedActiveClients; constructor(_chatSessionsService: IChatSessionsService, _chatService: IChatService, _chatWidgetService: IChatWidgetService, _languageModelsService: ILanguageModelsService, _baseConfigurationService: IConfigurationService, _logService: ILogService, _gitHubService: IGitHubService, _instantiationService: IInstantiationService, _sessionsService: ISessionsService, _activeClientService: IAgentHostActiveClientService, _mcpAppToolsService: IAgentHostMcpAppToolsService, _storageService: IStorageService, _dialogService: IDialogService, _workspaceTrustManagementService: IWorkspaceTrustManagementService, recentWorkspacesService: ISessionsRecentWorkspacesService, _uriIdentityService: IUriIdentityService); /** Current connection (always present for local; may be undefined while disconnected for remote). */ protected abstract get connection(): IAgentConnection | undefined; /** Provider-level authentication-pending observable used to derive `loading` for sessions. */ protected abstract get authenticationPending(): IObservable; protected abstract registerBackendSession(backendSession: URI, provider: string): void; /** Coalesces the session-resolution notifications of many {@link registerBackendSession} calls. */ protected batchBackendRegistrations(fn: () => T): T; /** Connection state for remote-host sessions. */ protected get remoteConnectionStatus(): IObservable | undefined; /** * Subclass-specific portion of the adapter options. Base fills in * the bits that are uniform across hosts (`icon`, `loading`, * `mapDiffUri`) from the corresponding hooks. */ protected abstract _adapterOptions(agentProvider: string): Pick; /** * Hook to normalize a session's metadata before it is cached, keyed, or * persisted. The default is identity. Subclasses override this when the host * addresses sessions under a scheme that differs from the agent provider * (e.g. a cloud sandbox host that lists sessions as `ahp-session:/` while * its agent provider is `copilot`), so that routing, persistence, and content * resolution all agree on a single scheme. Must preserve the raw session id * (URI path) so cache keys remain stable. */ protected _adoptSessionMeta(meta: IAgentSessionMetadata): IAgentSessionMetadata; /** * Creation addressing for a new draft, negotiated with its owning host. * Committed sessions always use their exact advertised resource. */ protected _backendSessionScheme(agentProvider: string): string; protected _logicalSessionTypeForBackendScheme(backendScheme: string): string; /** * The advertised default chat of a backend session: from its session state, * else from its listing, both received through the protocol client. */ private _backendDefaultChat; private _mapBackendSessionResource; /** Build an adapter for the given metadata. */ protected createAdapter(meta: IAgentSessionMetadata): AgentHostSessionAdapter; /** Ensures an adapter exists in {@link _sessionCache} for `rawMeta`, creating and announcing it when missing. */ protected _ensureSessionInCache(rawMeta: IAgentSessionMetadata): AgentHostSessionAdapter; private _getChatCatalogLoading; protected updateAdapter(adapter: AgentHostSessionAdapter, meta: IAgentSessionMetadata): boolean; /** Resolve host archive state before applying it to the client cache. */ protected _resolveArchivedState(_rawId: string, isArchived: boolean): boolean; /** * Computes the URI resource scheme used to route session URIs to this * provider's content provider for a given agent provider name. Local * uses `agent-host-${provider}`; remote uses a per-connection scheme. * * The resource scheme is host-specific and exists purely for content * provider routing. The logical {@link ISession.sessionType} is the * agent provider name itself, so the same agent (e.g. `copilotcli`) * appears under one shared session type across hosts. */ protected abstract resourceSchemeForProvider(provider: string): string; /** Format the human-readable label for a session type entry (e.g. `Copilot`). */ protected abstract _formatSessionTypeLabel(agentLabel: string): string; /** * Whether `provider` should be advertised as a session type by this host. * Defaults to `true` (advertise everything the host reports). The local * provider overrides this to suppress the agent host's Claude when the * window prefers the extension-host Claude, mirroring the gate * {@link AgentHostContribution} applies to the chat session contribution so * the welcome picker doesn't list Claude twice. */ protected _shouldAdvertiseAgent(_provider: string): boolean; protected _shouldShowSavedSession(provider: string): boolean; protected _isAgentDisabledByPolicy(_provider: string): boolean; private _isSessionDisabledByPolicy; private _assertSessionAvailable; protected _onSessionPolicyChanged(): void; protected _syncRootState(rootState: RootState | Error | undefined): void; private _syncAgentCapabilities; /** * Reconcile {@link _sessionTypes} against the agents advertised by the * host's root state, firing {@link onDidChangeSessionTypes} only if the * id/label set actually changed. */ protected _syncSessionTypesFromRootState(rootState: RootState): void; private _sessionTypesChangedSignal; /** * Presents a harness by the session type of the agent behind it, re-evaluating for `reader` * as the host's advertised agents load or change. `undefined` until that agent is advertised. */ getHarnessPresentation(harness: string, reader?: IReader): IHarnessPresentation | undefined; /** The advertised session type of the agent behind a harness, `undefined` until the host advertises it. */ getHarnessSessionType(harness: string): ISessionType | undefined; /** * Returns the {@link ThemeIcon} associated with a known agent provider, or * `undefined` when the provider is not recognised. */ private iconForAgentProvider; /** * Reconcile {@link _rootConfig} against {@link RootState.config}, firing * {@link onDidChangeRootConfig} only when schema or values actually change. */ protected _syncRootConfigFromRootState(rootState: RootState): void; abstract resolveWorkspace(repositoryUri: URI): ISessionWorkspace | undefined; /** Optional event fired when the underlying connection is lost; used to short-circuit `_waitForNewSession`. */ protected get onConnectionLost(): Event; /** Maps a host working-directory URI into the owning connection's client space. */ protected mapWorkingDirectoryUri(uri: URI): URI; /** Maps a project URI from the session summary to a local URI. Default identity; remote overrides for `file:` paths. */ protected mapProjectUri(uri: URI): URI; getSessionTypes(_repositoryUri: URI): ISessionType[]; private _syncActiveClient; private _dispatchActiveClientWhenResolved; private _clearActiveSessionScope; getSessions(): ISession[]; protected getResourceLabelHomes(): { readonly uri: URI; readonly label: string; }[]; private readonly _resourceLabelHomeRegistrations; private readonly _resourceLabelHomeLabels; private readonly _resourceLabelHomeFormattingEvents; protected updateResourceLabelHomeFormatters(homes: readonly { readonly uri: URI; readonly label: string; }[], labelService: ILabelService): void; protected getResourceLabelHomeLabel(session: ISession): string; protected getKnownSessions(): ISession[]; /** * Reports `agentHost.legacyCopilotCliMigrationOpen` when `resource` is an * un-adopted legacy Copilot CLI row of this list being opened, and returns * whether it is one. Opening such a row subscribes to the session, which the * host adopts without the client probe; without delaying the open, this * waits for the adopted summary that clears the row's adoptable marker. */ protected _reportAdoptableRowOpen(resource: URI, reason: SessionResourceResolveReason | undefined, telemetryService: ITelemetryService): boolean; getSessionByResource(resource: URI): ISession | undefined; createNewSession(workspaceUri: URI, sessionTypeId: string, options?: ISessionsProviderCreateSessionOptions): ISession; startNewSessionRequest(sessionId: string, activity?: string): IDisposable; createQuickChat(sessionTypeId: string, options?: ISessionsProviderCreateSessionOptions): ISession; /** * Builds, tracks, and eagerly starts a {@link NewSession} draft for the * given session type. Shared by {@link createNewSession} (workspace-bound) * and {@link createQuickChat} (workspace-less, `quickChat === true`). */ private _createDraftSession; private _resolveAutomationSessionTemplate; protected _resumeNewSessionAfterAuthenticationSettles(): void; private _startNewSessionBackend; /** * Re-resolves session config and pulses {@link _onDidChangeSessionConfig}. * Expected values are validated after strict resolutions. */ private _refreshNewSessionConfig; /** * Snapshot the well-known {@link SEEDED_CONFIG_SCHEMA_KEYS} schemas from an * authoritative resolve so the next new draft can render those chips * immediately (disabled) instead of blanking. A `undefined` config (failed * resolve) leaves the previous cache intact. */ private _cacheSeededConfigSchemas; /** Seed schema for a fresh draft, or `undefined` when nothing is cached yet. */ private _seededConfigSchema; /** Subclass hook for additional pre-create checks (e.g. remote requires connection). */ protected _validateBeforeCreate(_sessionType: ISessionType): void; /** Localized "no agents" error message. Subclasses can override. */ protected _noAgentsErrorMessage(): string; /** * Initial session-config preferences held locally until schema discovery * validates the advertised writable keys. Portable picks are seeded from a * profile-scoped map. Isolation is seeded from the last session started for * this workspace, falling back to `sessions.useWorktree`. * * The agent-host defaults are controlled by the single * `chat.defaultConfiguration` object setting (with `mode` and * `approvals` properties). Per axis the precedence is: enterprise * **policy** value > the user's **remembered** last pick > the ordinary * configured **setting** value (treated as a plain default) > schema * default. So a normal setting behaves as a default that the remembered * pick overrides, while an enterprise policy still wins outright. The * local-only `chat.permissions.default` setting is intentionally NOT * consulted here. * * Approval seeds retain the user's preference until schema discovery decides * whether host-reported policy or the legacy client restriction applies. * * The user's `git.branchPrefix` setting (resource-scoped to the workspace's * first folder) is seeded into the `worktreeBranchPrefix` slot so the agent * host can prepend it to the branch it creates for an isolated worktree. */ protected _initialNewSessionConfig(workspace?: ISessionWorkspace): Record | undefined; private _derivedNewSessionConfig; private _getSensitiveEditLocations; private _syncSensitiveEditLocations; /** * Re-reads the settings-derived config values of a draft before its first * request. The Agents window loads the settings of the draft's folder only * once the draft is active, so the values seeded at creation can miss them. * The agent host merges the config it receives on first send into the values * it got at creation, so a property whose setting is gone is cleared explicitly. */ private _refreshSettingsDerivedNewSessionConfig; getAutomationModelConfiguration(sessionId: string): AutomationModelConfiguration | undefined; getAutomationSessionConfiguration(sessionId: string): Promise; getSessionSandboxPolicy(sessionId: string): ISessionSandboxPolicy | undefined; getSessionSandboxEnabled(sessionId: string, chat: URI): boolean | undefined; hasSessionSandboxChangeError(sessionId: string, chat: URI): boolean; hasSessionSandboxRejectedSelection(sessionId: string, chat: URI): boolean; /** * The sandbox state the host applied for a chat. A subagent runs in the runtime of the chat that spawned * it. A host that does not track sandboxing per chat, or a chat without its own state, has the session's. */ private _readChatSandboxState; getSessionConfig(sessionId: string, chat: URI): ResolveSessionConfigResult | undefined; /** Whether a running session's chat is backed by an agent other than the session's. */ private _chatUsesOwnAgent; getSessionOwnConfig(sessionId: string): ResolveSessionConfigResult | undefined; /** * The config that applies to a chat: its own or, for a subagent (which has none), that of the chat that * spawned it, from their chat states when those are subscribed; reading never subscribes. */ private _getChatOwnConfigValues; /** The backend chats whose own config values apply to a chat, innermost first (see {@link getChatConfigChain}). */ private _getChatConfigChain; /** * Acquires the chat-state subscription supplying a chat's own config. It is * held while the chat is active in a visible session, and otherwise (after * an explicit write) released after {@link SESSION_STATE_SUBSCRIPTION_IDLE_MS}. */ private _keepChatConfigAlive; private _armChatConfigIdleTimer; getNewSessionCancellationToken(sessionId: string): CancellationToken; whenSessionConfigResolved(sessionId: string, token: CancellationToken): Promise; /** * Observable: `true` while a `resolveSessionConfig` round-trip is in * flight. Distinct from `session.loading` (which also covers the * required-values-missing state) — pickers gate on this so they stay * interactive when the user has to fill in required values. */ isSessionConfigResolving(sessionId: string, chat: URI): IObservable; private _rememberSessionConfigValue; private _getRememberedWorkspaceIsolation; private _rememberWorkspaceIsolation; private _forgetWorkspaceIsolations; setSessionConfigValue(sessionId: string, chat: URI, property: string, value: unknown): Promise; trackSessionConfigOperation(sessionId: string, operation: Promise): void; replaceSessionConfig(sessionId: string, values: Record): Promise; getAgentMergeSessionState(sessionId: string, chat?: URI): AgentMergeSessionState | undefined; private _getAgentMergeSessionState; /** * The session's config values including every Agent Merge folder seen so far: * a write of one folder is applied locally before the host merges it, so * until then the local config holds only that folder. The host never removes * a folder's settings, so earlier folders are still current. */ private _getAgentMergeValues; /** Records the Agent Merge folders of a session state; see {@link _getAgentMergeValues}. */ private _updateAgentMergeFolders; getAgentMergeClientStateObservable(sessionId: string, chat?: URI): IObservable; setAgentMergeEnabled(sessionId: string, enabled: boolean, chat?: URI): Promise; setAgentMergeOverrides(sessionId: string, overrides: AgentMergeSessionOverrides | undefined, chat?: URI): Promise; private _supportsPerFolderAgentMerge; /** * The workspace value of the check exclusions that decide whether a draft * is ready for review, for the folder a chat's Agent Merge settings belong * to. The host already has the user's value, which applies without one. */ private _getAgentMergeReadyIgnoredChecks; /** * Writes the check exclusions of each folder that runs Agent Merge when * their workspace value differs from what the host has. * * @param sessionId Limits the update to one session. * @param fillOnly Only adds a value the host lacks, so that windows with * different workspace values never overwrite each other. Rewriting a value * is left to a change of the setting, or of the folder's Agent Merge * settings, in the window where the user made it. */ private _syncAgentMergeReadyIgnoredChecks; /** * @param keepOwningChat Keeps the chat recorded as having turned Agent Merge * on, rather than recording `chat`, for an update the user did not make. */ private _writeAgentMergeClientState; private _resolveRunningSessionConfig; getSessionConfigCompletions(sessionId: string, property: string, query?: string): Promise; getCreateSessionConfig(sessionId: string): Record | undefined; getNewSessionConfig(sessionId: string): Promise; setIsolationMode(sessionId: string, mode: string): Promise; setWorktreeConfiguration(sessionId: string, configuration: ISessionWorktreeConfiguration): Promise; setBranch(sessionId: string, branch: string): Promise; private _setTransientNewSessionConfigValue; private _setTransientNewSessionConfigValues; clearSessionConfig(sessionId: string): void; getRootConfig(): RootConfigState | undefined; getRootState(): RootState | undefined; getClientId(): string | undefined; mapAgentHostResource(uri: URI): URI; authenticate(params: AuthenticateParams): Promise; setRootConfigValue(property: string, value: unknown): Promise; replaceRootConfig(values: Record): Promise; getModelsSnapshot(sessionId: string, desiredModelId?: string, chat?: URI): ISessionModelsSnapshot; getModelsSnapshotForCreation(_workspaceUri: URI | undefined, sessionTypeId: string, desiredModelId?: string): ISessionModelsSnapshot; private _getModelsSnapshotForTarget; getModelPickerOptions(sessionId: string, chat?: URI): ISessionModelPickerOptions; /** * Resolve a remembered model selection at send time: when it is conclusively * unavailable and the harness supports Auto, return the Auto model identifier * (rather than `undefined`, which would leave an already-running chat pinned * to its stale backend model) so the request is explicitly reset to Auto. */ private _resolveSendModelId; private _resolveSessionResourceScheme; setModel(sessionId: string, chatResource: URI, modelId: string, source: ChatModelSource): void; setAgent(sessionId: string, agent: ISessionAgentRef | undefined): void; getCustomAgents(sessionId: string): readonly AgentCustomization[]; /** The client-space identity the picker and chat modes use for a published, host-authored agent. */ private _toClientAgentUri; /** Whether a published plugin contains a client-space agent source, comparing in client space. */ private _pluginContainsClientSource; private _resolvePublishedDraftAgent; resolveCustomAgent(sessionId: string, uri: string): AgentCustomization | undefined; private _reconcileNewSessionAgent; getCustomizations(sessionId: string): Customization[]; getWorkingDirectory(sessionId: string, reader?: IReader): string | undefined; getBackendChatResource(chatResource: URI): URI | undefined; getSessionContextReference(chatResource: URI): string | undefined; getWorkingDirectories(sessionId: string): readonly string[]; getMcpServers(sessionId: string): readonly IAgentHostMcpServer[]; setCustomizationEnablement(sessionId: string, customizationId: string, enablement: readonly CustomizationEnablement[]): void; handleMcpRequest(channel: string, method: string, params: Record | undefined): Promise; getFeedbackAnnotationsChannel(sessionId: string): { readonly connection: IAgentConnection; readonly annotationsUri: URI; } | undefined; archiveSession(sessionId: string): Promise; importSession(sessionId: string): Promise; canMoveSessionUnder(sessionId: string): boolean; moveSessionUnder(sessionId: string, destinationSessionId: string, after: URI | undefined): Promise; canMoveChat(sessionId: string, chatUri: URI): boolean; moveChat(sessionId: string, chatUri: URI, destination: ISessionChatMoveDestination): Promise; listCanvases(sessionId: string, chatResource: URI): Promise; openCanvas(sessionId: string, chatResource: URI, canvas: ISessionCanvasDefinition, instanceId: string): Promise; closeCanvas(sessionId: string, chatResource: URI, canvas: ISessionCanvas): Promise; observeCanvas(sessionId: string, chatResource: URI, canvasResource: URI): IReference>; observeChatCanvases(sessionId: string, chatResource: URI): IReference> | undefined; /** Resolves the host-supplied backend session and chat that a canvas operation addresses. */ private _getCanvasChatTarget; private _toSessionCanvasDefinition; getSessionWorktreeDiskUsage(sessionId: string, token?: Readonly): Promise; sessionWorktreeExists(sessionId: string, token?: Readonly): Promise; unarchiveSession(sessionId: string): Promise; get supportsForceWorktreeCleanup(): boolean; sessionWorktreeCleanup(sessionId: string, retry: boolean, force?: boolean): Promise; message: import("../../../../../base/common/validation.js").Optional>; }> | undefined>; listManagedWorktrees(knownRepositories?: readonly URI[]): Promise; cleanupManagedWorktree(worktree: IAgentHostManagedWorktree, force?: boolean): Promise; managedWorktreeExists(worktree: IAgentHostManagedWorktree): Promise; archiveChat(sessionId: string, chatResource: URI): Promise; unarchiveChat(sessionId: string, chatResource: URI): Promise; private _setChatArchived; /** * Flips a session's archived state locally and dispatches the owning action * so the host persists it and fans it out to other windows. * * Skips the local flip when disconnected: showing a session as archived when * the change can never be recorded is worse than appearing not to archive. */ protected _setSessionArchived(sessionId: string, isArchived: boolean): boolean; protected _setSessionArchivedLocally(sessionId: string, isArchived: boolean): boolean; setSessionReadState(sessionId: string, isRead: boolean): Promise; setSessionsReadState(sessionIds: readonly string[], isRead: boolean): Promise; setChatReadState(sessionId: string, chatResource: URI, isRead: boolean): Promise; setChatReadStates(sessionId: string, chatResources: readonly URI[], isRead: boolean): Promise; private _setLegacySessionReadState; deleteSession(sessionId: string): Promise; deleteSessions(sessionIds: readonly string[]): Promise; renameChat(sessionId: string, chatUri: URI, title: string): Promise; renameSession(sessionId: string, title: string): Promise; removeSessionArtifact(sessionId: string, artifactId: string): Promise; private _getArtifactIntegrations; acquireArtifactIntegration(sessionId: string, artifactId: string): Promise>; deleteChat(sessionId: string, chatUri: URI, options?: IDeleteChatOptions): Promise; createNewChat(chatId: string, _prompt?: string, options?: ICreateNewChatOptions): Promise; getNestedChatWorkspaceSupport(sessionId: string, chat: URI, reader: IReader | undefined): INestedChatWorkspaceSupport | undefined; resolveNestedChatFolder(sessionId: string, chat: URI, folder: URI, token: CancellationToken): Promise; getNestedChatBranches(sessionId: string, chat: URI, folder: URI, query: string, token: CancellationToken): Promise; applyNestedChatWorkspace(sessionId: string, chat: URI, workspace: INestedChatWorkspace, prompt: string): Promise; /** The session whose new nested chats may choose a workspace; `undefined` when the composer must not offer one. */ private _getNestedChatWorkspaceSession; /** * The agent backing `chat`, a new nested chat of `cached`: its own for a chat using another harness, otherwise * the session's. `undefined` when enterprise policy disables that agent. */ private _getNestedChatAgent; /** Resolves the default configuration of `chat`'s agent for a new chat in `folder`, as a new session draft does. */ private _resolveNestedChatFolderConfig; /** * The agent provider to request for a new peer chat using `harness`, or `undefined` * when the chat uses the session's agent (and the request must not name one). */ private _resolveNewChatProvider; private _createAdditionalChat; forkChat(sessionId: string, sourceChat: URI, turnId: string, options?: IForkChatOptions): Promise; createSideChat(sessionId: string, sourceChat: URI, turnId: string, selection?: ISideChatSelection): Promise; /** * The model a chat is actually running on per the host: its draft model, else the model of * its active or most recent turn. `undefined` when the chat state is not hydrated. */ private _readRunningChatModel; private _resolveBackendSourceChatUri; sendRequest(chatId: string, chatResource: URI, options: ISendRequestOptions): Promise; /** Send the first request for an already-committed peer chat, then clear its `new` flag. */ private _sendCommittedChatRequest; private _updateChatSessionState; private _retainChatSessionModel; private _applyChatSessionState; private _sendNewSessionRequest; /** Localized error message when sendRequest is invoked without a connection. Subclasses can override. */ protected _notConnectedSendErrorMessage(): string; /** * When a session transitions from untitled (new) to committed (running), * carry over the full resolved config (schema + values) so consumers like * the session-settings JSONC editor can round-trip non-mutable values * (`isolation`, `branch`, …) through a replace dispatch. Mutable-vs-readonly * behavior is still driven off the per-property `sessionMutable` flag. */ private _preserveNewSessionConfig; private _preserveNewSessionModelSelection; protected _sessionKeyFromChatId(chatId: string): string | undefined; private _acquireSessionChatDetails; /** * Guesses which of a session's chats an operation meant, for APIs that are keyed by session id * alone and so cannot say. * * A guess, not an answer: it reads whichever session is globally active, so an operation on a * visible peer chat that is not the active one lands on the wrong conversation. Callers that * can name their chat should take it as a parameter instead, as * {@link ISessionsProvider.setModel} does. */ private _activeChatResource; /** * Idle window before a lazily-created session-state subscription is * released. Each call to {@link _keepSessionStateAlive} resets the timer. * Long enough to absorb the open→config-picker churn while a session view * is active; short enough that closed sessions release within a minute or * so, allowing the agent host to evict their cached restored state. */ private static readonly SESSION_STATE_SUBSCRIPTION_IDLE_MS; private static readonly CHAT_MODEL_RETENTION_MS; private _keepAgentMergeSessionStateAlive; private _scheduleAgentMergeSessionStateIdleRelease; /** * Pin the state subscription of every currently-visible session (so * host-driven catalog changes flow into `cached.chats` while it is on * screen) and resume the idle-release timer for sessions that have left the * viewport. Driven reactively by {@link ISessionsService.visibleSessions}. */ private _syncVisibleSessionStatePins; /** Holds the own-config subscription of each visible session's active chat, so its picker never re-resolves while shown. */ private _syncActiveChatConfigPins; /** * Bump the idle-release timer for `sessionId` and lazily create the * underlying subscription if needed. Called from query paths * ({@link getSessionByResource}, {@link getSessionConfig}) that depend on * `_runningSessionConfigs` / `_meta` being in sync but cannot themselves * own a subscription handle. */ private _keepSessionStateAlive; private _keepChatSessionStateAlive; /** * Lazily acquire a session-state subscription for `sessionId` so that * `_runningSessionConfigs` is seeded from the AHP `SessionState.config` * snapshot. Safe to call repeatedly — no-op once a subscription exists. * * The subscription is reference-counted by {@link IAgentConnection.getSubscription}, * so when the session handler is also subscribed (chat content open) this * shares the existing wire subscription rather than opening a new one. * * `hydrateDraft` also restores the draft agent and model, which subscribes the * session's default chat. Passive observers such as session-list rows must * pass `false`: a chat snapshot carries the whole transcript, and fetching it * for chats that are not open delays the chat the user is looking at. */ private _ensureSessionStateSubscription; private _openSessionStateSubscription; /** * Start the one-shot draft agent/model hydration for the session's current * state subscription, if it has not started yet. The hydration lives in the * subscription's store, so a re-created subscription hydrates again on demand. */ private _ensureDraftHydration; /** * Runs `callback` once with the session's default chat: now when it is known, * otherwise when the session state, which may not be hydrated yet, advertises one. */ private _whenBackendDefaultChat; /** * Resume hydration: when a session is (re)loaded and its adapter has no agent * selected, restore the persisted selection from the default chat's * `ChatState.draft.agent` and mirror it onto `session.mode` (the picker's * source of truth). * * The agent is persisted on the chat channel — the session channel * ({@link SessionState}) carries no draft — so we briefly observe the default * chat's state until its draft agent arrives. The subscription is shared and * ref-counted with the chat session handler (no extra wire cost) and lives for * the session-state store's lifetime. Hydration is one-shot: the observer * stops as soon as `mode` is set — by us here, or by a concurrent graduation * seed or user pick (guarded inside * {@link AgentHostSessionAdapter.hydrateSelectedAgent}) — so it neither leaks, * overrides a later selection, nor keeps re-running on every chat update. */ private _hydrateAgentFromDraft; /** * Resume hydration for the model, mirroring {@link _hydrateAgentFromDraft}. * * A reloaded session reports `modelId === undefined` until something tells it otherwise, and an * undefined model reads as "this conversation has never chosen one" — which invites model * selection to seed it from a profile-wide preference and write that through to the backend. * The model the session was actually running on is on the default chat's `ChatState.draft`, so * it is read back the same way the draft agent is. * * One-shot and guarded inside {@link AgentHostSessionAdapter.hydrateSelectedModel}, so it * neither leaks nor overrides a selection made in the meantime. */ private _hydrateModelFromDraft; /** * Fan-out for AHP `SessionState` snapshots: keeps both the running * session config and the cached adapter's `_meta` (e.g. git state) in * sync. */ private _applySessionStateUpdate; /** * Rebase the cached running adapter's selected agent against the host's agent * list from an AHP {@link SessionState}, before the picker is notified. A * session that has moved into an isolated worktree keeps its selection instead * of resetting to the default once the host starts reporting worktree-pathed * agents. See {@link AgentHostSessionAdapter.reconcileSelectedAgent}. */ private _reconcileAgentFromState; /** * Reconcile the per-chat catalog of the cached running adapter from an AHP * {@link SessionState}. The adapter exposes `chats`/`mainChat` as * observables, so updating them here is enough for the chat-tab UI to * re-render reactively. */ private _applyChatCatalogFromState; /** * NewSession variant of {@link _applySessionStateUpdate}: writes the * customizations subset and applies git/GitHub metadata to the draft * workspace. Skips {@link _seedRunningConfigFromState} because NewSession * owns its own config via `NewSession._config`. */ private _handleNewSessionStateUpdate; /** * Folder drafts follow the checked-out branch while untouched worktree drafts * use the repository's default branch. */ private _syncDraftBranch; /** * Cleanup sentinel from {@link NewSession.dispose}: drops the cached * `_lastSessionStates` entry the new session contributed. Fires * `_onDidChangeCustomAgents` so any open picker re-reads and falls * back to the empty list rather than rendering stale agents. */ private _handleNewSessionStateGone; private _applySessionMetadataFromState; /** * Seed {@link _runningSessionConfigs} from the AHP `SessionState.config` * snapshot. Keeps the full schema + values (including non-mutable ones) * so consumers like the JSONC settings editor can round-trip all values * through a replace dispatch. No-op if structurally equal to avoid spurious * `onDidChangeSessionConfig` fires. */ private _seedRunningConfigFromState; /** Mirrors a session's `isolation` pick onto its adapter. See {@link ISession.worktreePending}. */ private _applyWorktreeIsolation; /** * Opt in to persisting {@link _sessionCache} snapshots under `storageKey`. * Subclasses call this at the **end** of their constructor — once the * identity fields that {@link createAdapter}/{@link resourceSchemeForProvider}/ * {@link _adapterOptions} depend on are initialized — because the initial * hydration builds adapters. This is why the base cannot auto-load in its * own constructor. Persisted summaries are hydrated into {@link _sessionCache} * immediately so {@link getSessions} returns them before the first * `listSessions()` round-trip resolves. * * `legacyStorageKeys`, when given, are removed so stale entries are discarded. */ protected _enableSessionCachePersistence(storageKey: string, legacyStorageKeys?: string | readonly string[]): void; /** * Whether {@link _onDidChangeSessions} events should update the persistence * bookkeeping ({@link _cacheDirty} + {@link _metadataBySession}). Default `true`; * the remote provider overrides this to suspend tracking while its cached * sessions are unpublished (offline), so the on-disk snapshot survives. */ protected _shouldTrackSessionCacheChanges(): boolean; /** Allows providers to migrate or reject cached metadata before constructing adapters. */ protected _adoptCachedSessionMeta(meta: IAgentSessionMetadata): IAgentSessionMetadata | undefined; /** Load persisted session summaries into {@link _sessionCache}. */ private _loadCachedSessions; /** * Persist the current {@link _sessionCache} to storage, capping at * {@link CACHED_SESSIONS_MAX_PER_HOST} most-recently-modified entries. * Mutable fields are read from each adapter's observables and overlaid on * top of the original metadata snapshot captured in {@link _metadataBySession}. */ private _persistCache; protected _ensureSessionCache(): void; protected _refreshSessions(announceExistingAsAdded?: boolean): Promise; /** * Whether a cached session the host did not list may be evicted. Subclasses override this to * protect a session that exists but that the host has not materialized yet. */ protected _isSessionEvictable(rawId: string): boolean; /** Raw ids the host listed, reported before eviction runs so subclasses can retire protections. */ protected _onHostListedSessions(_rawIds: ReadonlySet): void; /** Raw ids retained after authoritative-list eviction and partial-provider guards have applied. */ protected _onHostReconciledSessions(_rawIds: ReadonlySet): void; /** * Arm a backoff retry of {@link _refreshSessions}. Used after a failed * refresh so a transient startup failure self-heals without requiring an * unrelated AHP event (a turn completing, a session being added) to force * a re-fetch. Cancelled on the next successful refresh. */ private _scheduleSessionRefreshRetry; /** * Cancel any pending session-refresh retry and reset the backoff. Called * by subclasses when the connection goes away (the stale timer would * otherwise fire against a dead connection and no-op). */ protected _cancelSessionRefreshRetry(): void; /** * Resolves the freshly committed backend session for an in-flight send. * A committed session preserves the draft URI, preventing unrelated sessions from replacing it. */ private _waitForNewSession; /** * Wire AHP notification and action listeners on the given connection. * Subclasses call this from their constructor (local) or `setConnection` * (remote), passing a store that bounds the listeners' lifetime. */ protected _attachConnectionListeners(connection: IAgentConnection, store: DisposableStore): void; private _handleSessionAdded; private _handleSessionRemoved; protected _onBackendSessionRemoved(_rawId: string): void; protected _removeCachedSession(rawId: string, expected?: AgentHostSessionAdapter): AgentHostSessionAdapter | undefined; private _handleTitleChanged; private _handleIsArchivedChanged; private _handleIsReadChanged; private _handleSessionSummaryChanged; private _handleConfigChanged; private _handleSessionMetaChanged; /** * Optional URI mapper used when applying diff changes. Subclasses * override to translate remote diff URIs into agent-host URIs. */ protected _diffUriMapper(): AgentHostUriMapper | undefined; } export {};