src/vs/platform/agentHost/node/agentPeerChats.ts

354 LOC · 324 covered · 30 uncovered · 98 ranges · 1352 concepts · 45 introducers · 664 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- agentPeerChats.ts ×25
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Disposable, DisposableMap, IDisposable } from '../../../base/common/lifecycle.js';
7 > import { renderResponseMarkdown, truncateMiddle } from '../common/agentHostConversationContext.js';
8 > import { type ActiveTurn, type ModelSelection, type Turn } from '../common/state/protocol/state.js';
9 >
10 > const SIDE_CHAT_CONTEXT_START = '<side-chat-context>';
11 > const SIDE_CHAT_CONTEXT_END = '</side-chat-context>';
12 > const SIDE_CHAT_CONTEXT_LENGTH_PREFIX = 'length=';
13 > const SIDE_CHAT_GUIDANCE = 'This is a side conversation. Prefer explanation over action; do not make changes or carry out work unless the user explicitly asks.';
14 > export const MAX_SIDE_CHAT_CONTEXT_CHARS = 20_000;
15 >
16 > export interface IPersistedSideChat {
17 > readonly source: string;
18 > readonly turnId: string;
19 > readonly selection?: { readonly text: string; readonly responsePartId?: string };
20 > readonly providerAnchorTurnId?: string;
21 > readonly inheritedTurnCount: number;
22 > readonly partialResponse?: string;
23 > readonly context?: string;
24 > }
25 >
26 > export function buildSideChatSourceContext(turns: readonly Turn[], activeTurn?: ActiveTurn): string | undefined {
27 > const blocks: string[] = []; agentPeerChats.ts ×7
28 > for (const turn of turns) {
29 > const block = buildSideChatContextBlock(turn.message.text, renderResponseMarkdown(turn.responseParts)); agentPeerChats.ts ×2
30 > if (block) {
31 > blocks.push(block);
32 > }
33 > }
34 > if (activeTurn) { agentPeerChats.ts ×7
35 > const block = buildSideChatContextBlock(activeTurn.message.text, undefined); agentPeerChats.ts ×1
36 > if (block) {
37 > blocks.push(block);
38 > }
39 > }
40 > if (blocks.length === 0) { agentPeerChats.ts ×7
41 return undefined;
42 }
43 > const conversation = blocks.join('\n\n---\n\n'); agentPeerChats.ts ×7
44 > return conversation.length > MAX_SIDE_CHAT_CONTEXT_CHARS ? truncateMiddle(conversation, MAX_SIDE_CHAT_CONTEXT_CHARS) : conversation;
45 > }
47 > export function getSideChatPartialResponse(activeTurn: ActiveTurn | undefined): string | undefined {
48 > if (!activeTurn) { agentPeerChats.ts ×2
49 > return undefined; agentPeerChats.ts ×1
50 > }
51 > const responseMarkdown = renderResponseMarkdown(activeTurn.responseParts); agentPeerChats.ts ×2
52 > return responseMarkdown ? truncateMiddle(responseMarkdown, MAX_SIDE_CHAT_CONTEXT_CHARS) : undefined; agentPeerChats.ts ×2
53 > }
55 > export function buildBoundedSideChatSourceContext(turns: readonly Turn[], turnId: string, activeTurn?: ActiveTurn): string | undefined {
56 > if (activeTurn?.id === turnId) { agentService.ts ×3
57 > return buildSideChatSourceContext(turns, activeTurn); agentPeerChats.ts ×2
58 > }
59 > const turnIndex = turns.findIndex(turn => turn.id === turnId); agentPeerChats.ts ×1
60 > return turnIndex === -1 ? undefined : buildSideChatSourceContext(turns.slice(0, turnIndex + 1)); agentService.ts ×3
61 > }
63 > export function injectSideChatContext(prompt: string, partialResponse?: string, sourceContext?: string, selectionText?: string): string {
64 > const context = [SIDE_CHAT_GUIDANCE]; agentPeerChats.ts ×5
65 > if (selectionText) {
66 > context.push( agentPeerChats.ts ×1
67 > '',
68 > 'Selected text:',
69 > '',
70 > selectionText,
71 > );
72 > }
73 > if (sourceContext) { agentPeerChats.ts ×5
74 > context.push( agentPeerChats.ts ×1
75 > '',
76 > 'Source conversation up to the branching point:',
77 > '',
78 > sourceContext,
79 > );
80 > }
81 > if (partialResponse) { agentPeerChats.ts ×5
82 > context.push( agentPeerChats.ts ×1
83 > '',
84 > 'The side chat was created while the source assistant was still responding.',
85 > 'The user-visible response had produced the following text at that moment:',
86 > '',
87 > partialResponse,
88 > );
89 > }
90 > const contextBody = context.join('\n'); agentPeerChats.ts ×5
91 > return [SIDE_CHAT_CONTEXT_START, `${SIDE_CHAT_CONTEXT_LENGTH_PREFIX}${contextBody.length}`, contextBody, SIDE_CHAT_CONTEXT_END, '', prompt].join('\n');
92 > }
94 > export function prepareSideChatPrompt(prompt: string, turns: readonly Turn[], sideChat: IPersistedSideChat | undefined): string {
95 > if (!sideChat || turns.length > sideChat.inheritedTurnCount) { agentPeerChats.ts ×3
96 > return prompt; agentPeerChats.ts ×1
97 > }
98 > const selectedSourceTurn = turns.find(turn => turn.id === sideChat.turnId); agentPeerChats.ts ×5
99 > const sourceContext = selectedSourceTurn ? undefined : sideChat.context; agentPeerChats.ts ×3
100 > let partialResponse = sideChat.partialResponse;
101 > if (partialResponse) {
102 > const inheritedResponse = selectedSourceTurn ? renderResponseMarkdown(selectedSourceTurn.responseParts) : ''; agentPeerChats.ts ×2
103 > if (inheritedResponse.includes(partialResponse)) {
104 > partialResponse = undefined; agentPeerChats.ts ×1
105 > }
107 > return injectSideChatContext(prompt, partialResponse, sourceContext, sideChat.selection?.text); agentPeerChats.ts ×3
108 > }
110 > function buildSideChatContextBlock(message: string, response: string | undefined): string | undefined { agentPeerChats.ts ×7
111 > const userText = message.trim();
112 > const responseText = response?.trim();
113 > if (!userText && !responseText) {
114 return undefined;
115 }
116 > return responseText agentPeerChats.ts ×7
117 > ? `User request:\n${userText}\n\nAgent response:\n${responseText}` agentPeerChats.ts ×2
118 > : `User request:\n${userText}`; agentPeerChats.ts ×1
121 > export function stripSideChatContext(turns: readonly Turn[], sideChat: IPersistedSideChat | undefined): readonly Turn[] {
122 > if (!sideChat || turns.length === 0) { agentPeerChats.ts ×1
123 > return turns; agentPeerChats.ts ×1
124 > }
125 > const first = turns[0]; agentPeerChats.ts ×3
126 > const text = first.message.text;
127 > if (!text.startsWith(SIDE_CHAT_CONTEXT_START)) {
128 return turns;
129 }
130 > const lengthHeaderStart = SIDE_CHAT_CONTEXT_START.length + 1; agentPeerChats.ts ×3
131 > if (text.slice(lengthHeaderStart).startsWith(SIDE_CHAT_CONTEXT_LENGTH_PREFIX)) {
132 > const lengthLineEnd = text.indexOf('\n', lengthHeaderStart);
133 > const parsedLength = lengthLineEnd > 0
134 > ? Number.parseInt(text.slice(lengthHeaderStart + SIDE_CHAT_CONTEXT_LENGTH_PREFIX.length, lengthLineEnd), 10)
135 : Number.NaN;
136 > if (Number.isInteger(parsedLength) && parsedLength >= 0) { agentPeerChats.ts ×3
137 > const contextStart = lengthLineEnd + 1;
138 > const contextEnd = contextStart + parsedLength;
139 > if (text.slice(contextEnd, contextEnd + SIDE_CHAT_CONTEXT_END.length + 1) === `\n${SIDE_CHAT_CONTEXT_END}`) {
140 > const userPrompt = text.slice(contextEnd + SIDE_CHAT_CONTEXT_END.length + 1).trimStart();
141 > return [{ ...first, message: { ...first.message, text: userPrompt } }, ...turns.slice(1)];
142 > }
143 > }
144 > }
145 const endIndex = text.lastIndexOf(SIDE_CHAT_CONTEXT_END);
146 if (endIndex < 0) {
147 return turns;
148 }
149 const userPrompt = text.slice(endIndex + SIDE_CHAT_CONTEXT_END.length).trimStart();
150 return [{ ...first, message: { ...first.message, text: userPrompt } }, ...turns.slice(1)];
151 }
153 > /**
154 > * In-memory backing for an additional (non-default) peer chat. Records the SDK
155 > * chat id that backs the chat so it can be re-resumed after a process restart,
156 > * along with any model override chosen at creation time. This is also the shape
157 > * serialized into the opaque, agent-owned `providerData` blob the orchestrator
158 > * persists in its chat catalog and hands back on restore.
159 > */
160 > export interface IPersistedChat {
161 > readonly sdkSessionId: string;
162 > readonly model?: ModelSelection;
163 > readonly sideChat?: IPersistedSideChat;
164 > }
165 >
166 > export interface IResolvedAgentChat<TSession extends IDisposable> {
167 > readonly chatSession: TSession;
168 > readonly isDefault: boolean;
169 > }
170 >
171 > /**
172 > * Serializes a peer-chat backing into the opaque `providerData` token the
173 > * orchestrator persists verbatim. The encoding is the agent's private business
174 > * — today it is the JSON of {@link IPersistedChat}.
175 > */
176 > export function encodeProviderData(backing: IPersistedChat): string {
177 > return JSON.stringify(backing); agentPeerChats.ts ×1
178 > }
180 > /**
181 > * Decodes an opaque `providerData` token produced by {@link encodeProviderData}
182 > * back into a peer-chat backing, tolerating corrupt/foreign blobs by returning
183 > * `undefined` (the same drop-on-corrupt policy as the legacy chat catalog read).
184 > */
185 > export function decodeProviderData(providerData: string): IPersistedChat | undefined {
186 > try { agentPeerChats.ts ×7
187 > const value = JSON.parse(providerData) as { sdkSessionId?: unknown; model?: unknown; sideChat?: unknown };
188 > if (!value || typeof value !== 'object') {
189 return undefined;
190 }
191 > const { sdkSessionId, model } = value; agentPeerChats.ts ×2
192 > if (typeof sdkSessionId !== 'string' || !sdkSessionId) { agentPeerChats.ts ×7
193 return undefined;
194 }
195 > // The blob is client-influenced and may be corrupted or shape-shifted by agentPeerChats.ts ×2
196 > // a future serialization change: only accept a `model` that actually
197 > // looks like a `ModelSelection`.
198 > const validModel = model && typeof model === 'object' && typeof (model as { id?: unknown }).id === 'string' agentPeerChats.ts ×7
199 > ? model as ModelSelection claudeAgent.ts ×7
200 > : undefined; agentPeerChats.ts ×1
201 > const sideChat = value.sideChat as { source?: unknown; turnId?: unknown; selection?: unknown; providerAnchorTurnId?: unknown; inheritedTurnCount?: unknown; partialResponse?: unknown; context?: unknown } | undefined; agentPeerChats.ts ×7
202 > const validSelection = sideChat?.selection
203 > && typeof sideChat.selection === 'object' agentPeerChats.ts ×2
204 > && typeof (sideChat.selection as { text?: unknown }).text === 'string'
205 > && (((sideChat.selection as { responsePartId?: unknown }).responsePartId) === undefined || typeof (sideChat.selection as { responsePartId?: unknown }).responsePartId === 'string')
206 > ? {
207 > text: (sideChat.selection as { text: string }).text,
208 > ...((sideChat.selection as { responsePartId?: string }).responsePartId ? { responsePartId: (sideChat.selection as { responsePartId?: string }).responsePartId } : {}),
209 > }
210 > : undefined; agentPeerChats.ts ×2
211 > const validSideChat = sideChat agentPeerChats.ts ×7
212 > && typeof sideChat.source === 'string' agentPeerChats.ts ×2
213 > && typeof sideChat.turnId === 'string'
214 > && (sideChat.providerAnchorTurnId === undefined || typeof sideChat.providerAnchorTurnId === 'string')
215 > && typeof sideChat.inheritedTurnCount === 'number'
216 > && (sideChat.partialResponse === undefined || typeof sideChat.partialResponse === 'string')
217 > && (sideChat.context === undefined || typeof sideChat.context === 'string')
218 > ? {
219 > source: sideChat.source,
220 > turnId: sideChat.turnId,
221 > ...(validSelection ? { selection: validSelection } : {}),
222 > ...(sideChat.providerAnchorTurnId ? { providerAnchorTurnId: sideChat.providerAnchorTurnId } : {}),
223 > inheritedTurnCount: sideChat.inheritedTurnCount,
224 > ...(sideChat.partialResponse ? { partialResponse: sideChat.partialResponse } : {}),
225 > ...(sideChat.context ? { context: sideChat.context } : {}),
226 > }
227 > : undefined; agentPeerChats.ts ×2
228 > return { sdkSessionId, ...(validModel ? { model: validModel } : {}), ...(validSideChat ? { sideChat: validSideChat } : {}) }; agentPeerChats.ts ×7
229 > } catch {
230 > return undefined; copilotAgent.ts ×8
231 > }
234 > /**
235 > * Per-session container shared by the multi-chat agents. Keeps ALL chats of a
236 > * session — the default (main) chat and any additional peer chats — together in
237 > * ONE per-agent map keyed by each chat's channel URI string (no parallel maps,
238 > * no default-vs-peer storage split). The default chat is just the entry marked
239 > * as default, so send/abort/model/agent/history operations resolve any chat by a
240 > * single uniform {@link getChat} lookup with no default-chat resolution branch.
241 > *
242 > * Each entry can act as a leaf (wrapping one {@link ownSession} plus its
243 > * event-forwarding disposables) or as the container (holding the chat map).
244 > * Disposing the container disposes every chat leaf it holds.
245 > */
246 > export class AgentSessionEntry<TSession extends IDisposable> extends Disposable {
247 > /** All chats of the session (default + peers) as leaf entries, keyed by chat-URI string. */
248 > private readonly _chats = this._register(new DisposableMap<string, AgentSessionEntry<TSession>>());
249 > /** The key of the session's default (main) chat within {@link _chats}. */
250 > private _defaultChatKey: string | undefined;
251 > /** This leaf's own chat session (set when the entry wraps a single chat). */
252 > private _ownSession: TSession | undefined;
253 >
254 > constructor(session?: TSession) {
255 > super(); agentPeerChats.ts ×1
256 > if (session) {
257 > this._ownSession = session;
258 > this._register(session);
259 > }
260 > }
262 > /** This leaf's own chat session, or `undefined` for a bare container. */
263 > get ownSession(): TSession | undefined {
264 > return this._ownSession; agentPeerChats.ts ×1
265 > }
267 > addDisposable(disposable: IDisposable): void {
268 > this._register(disposable); claudeAgent.ts ×3
269 > }
271 > // ---- Uniform chat map (default + peers) --------------------------------
272 >
273 > /** Register the session's default (main) chat leaf under its chat-URI key. */
274 > setDefaultChat(chatKey: string, entry: AgentSessionEntry<TSession>): void {
275 > this._chats.set(chatKey, entry); agentPeerChats.ts ×1
276 > this._defaultChatKey = chatKey;
277 > }
279 > /** Dispose the default chat leaf (e.g. a config-driven restart) while keeping peer chats. */
280 > clearDefaultChat(): void {
281 > if (this._defaultChatKey !== undefined) { copilotAgent.ts ×3
282 > this._chats.deleteAndDispose(this._defaultChatKey);
283 > this._defaultChatKey = undefined;
284 > }
285 > }
287 > /** The session's materialized default (main) chat, or `undefined` while provisional. */
288 > get defaultChat(): TSession | undefined {
289 > return this._defaultChatKey !== undefined ? this._chats.get(this._defaultChatKey)?.ownSession : undefined; agentPeerChats.ts ×1
290 > }
292 > /** Uniform lookup: the chat's session (default OR peer) by its chat-URI key. */
293 > getChat(chatKey: string): TSession | undefined {
294 > return this._chats.get(chatKey)?.ownSession; claudeAgent.ts ×6
295 > }
297 > /** Uniform lookup with default-vs-peer identity from the entry that resolved the chat. */
298 > resolveChat(chatKey: string): IResolvedAgentChat<TSession> | undefined {
299 > const chatSession = this._chats.get(chatKey)?.ownSession; agentPeerChats.ts ×2
300 > if (!chatSession) {
301 > return undefined; agentPeerChats.ts ×1
302 > }
303 > return { chatSession, isDefault: chatKey === this._defaultChatKey }; agentPeerChats.ts ×1
306 > /** Every live chat session — the default chat plus all peers. */
307 > allChatSessions(): TSession[] {
308 > const sessions: TSession[] = []; agentPeerChats.ts ×1
309 > for (const entry of this._chats.values()) {
310 > if (entry.ownSession) {
311 > sessions.push(entry.ownSession);
312 > }
313 > }
314 > return sessions;
315 > }
317 > // ---- Peer chats (every chat except the default) ------------------------
318 >
319 > getPeerChat(chatKey: string): TSession | undefined {
320 > return chatKey === this._defaultChatKey ? undefined : this._chats.get(chatKey)?.ownSession; agentPeerChats.ts ×1
321 > }
323 > hasPeerChat(chatKey: string): boolean {
324 > return chatKey !== this._defaultChatKey && this._chats.has(chatKey); agentPeerChats.ts ×1
325 > }
327 > registerPeerChat(chatKey: string, entry: AgentSessionEntry<TSession>): void {
328 > this._chats.set(chatKey, entry); agentPeerChats.ts ×1
329 > }
331 > disposePeerChat(chatKey: string): void {
332 > if (chatKey !== this._defaultChatKey) { agentPeerChats.ts ×1
333 > this._chats.deleteAndDispose(chatKey);
334 > }
335 > }
337 > peerChatKeys(): string[] {
338 > return [...this._chats.keys()].filter(key => key !== this._defaultChatKey); agentPeerChats.ts ×1
339 > }
341 > peerChatSessions(): TSession[] {
342 const sessions: TSession[] = [];
343 for (const key of this._chats.keys()) {
344 if (key === this._defaultChatKey) {
345 continue;
346 }
347 const session = this._chats.get(key)?.ownSession;
348 if (session) {
349 sessions.push(session);
350 }
351 }
352 return sessions;
353 }