forked from microsoft/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextHostChatContext.ts
More file actions
358 lines (318 loc) · 14.3 KB
/
extHostChatContext.ts
File metadata and controls
358 lines (318 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { CancellationToken } from '../../../base/common/cancellation.js';
import { URI, UriComponents } from '../../../base/common/uri.js';
import { ExtHostChatContextShape, MainContext, MainThreadChatContextShape } from './extHost.protocol.js';
import { DocumentSelector, MarkdownString } from './extHostTypeConverters.js';
import { IExtHostRpcService } from './extHostRpcService.js';
import { IChatContextItem } from '../../contrib/chat/common/contextContrib/chatContext.js';
import { Disposable, DisposableStore } from '../../../base/common/lifecycle.js';
import { IExtHostCommands } from './extHostCommands.js';
type ProviderType = 'workspace' | 'explicit' | 'resource';
interface ProviderEntry {
type: ProviderType;
provider: vscode.ChatWorkspaceContextProvider | vscode.ChatExplicitContextProvider | vscode.ChatResourceContextProvider;
disposables: DisposableStore;
}
export class ExtHostChatContext extends Disposable implements ExtHostChatContextShape {
declare _serviceBrand: undefined;
private _proxy: MainThreadChatContextShape;
private _handlePool: number = 0;
private _providers: Map<number, ProviderEntry> = new Map();
private _itemPool: number = 0;
/** Global map of itemHandle -> original item for command execution with reference equality */
private _globalItems: Map<number, vscode.ChatContextItem> = new Map();
/** Track which items belong to which provider for cleanup */
private _providerItems: Map<number, Set<number>> = new Map(); // providerHandle -> Set<itemHandle>
/** Track insertion order for LRU eviction */
private _itemInsertionOrder: number[] = [];
/** Maximum number of global items to prevent unbounded growth */
private static readonly MAX_GLOBAL_ITEMS = 10000;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostCommands private readonly _commands: IExtHostCommands,
) {
super();
this._proxy = extHostRpc.getProxy(MainContext.MainThreadChatContext);
}
// Workspace context provider methods
async $provideWorkspaceChatContext(handle: number, token: CancellationToken): Promise<IChatContextItem[]> {
this._clearProviderItems(handle);
const entry = this._providers.get(handle);
if (!entry || entry.type !== 'workspace') {
throw new Error('Workspace context provider not found');
}
const provider = entry.provider as vscode.ChatWorkspaceContextProvider;
const result = (await provider.provideWorkspaceChatContext?.(token)) ?? (await provider.provideChatContext?.(token)) ?? [];
return this._convertItems(handle, result);
}
// Explicit context provider methods
async $provideExplicitChatContext(handle: number, token: CancellationToken): Promise<IChatContextItem[]> {
this._clearProviderItems(handle);
const entry = this._providers.get(handle);
if (!entry || entry.type !== 'explicit') {
throw new Error('Explicit context provider not found');
}
const provider = entry.provider as vscode.ChatExplicitContextProvider;
const result = (await provider.provideExplicitChatContext?.(token)) ?? (await provider.provideChatContext?.(token)) ?? [];
return this._convertItems(handle, result);
}
async $resolveExplicitChatContext(handle: number, context: IChatContextItem, token: CancellationToken): Promise<IChatContextItem> {
const entry = this._providers.get(handle);
if (!entry || entry.type !== 'explicit') {
throw new Error('Explicit context provider not found');
}
const provider = entry.provider as vscode.ChatExplicitContextProvider;
const extItem = this._globalItems.get(context.handle);
if (!extItem) {
throw new Error('Chat context item not found');
}
return this._doResolve((provider.resolveExplicitChatContext ?? provider.resolveChatContext)?.bind(provider), context, extItem, token);
}
// Resource context provider methods
async $provideResourceChatContext(handle: number, options: { resource: UriComponents; withValue: boolean }, token: CancellationToken): Promise<IChatContextItem | undefined> {
const entry = this._providers.get(handle);
if (!entry || entry.type !== 'resource') {
throw new Error('Resource context provider not found');
}
const provider = entry.provider as vscode.ChatResourceContextProvider;
const result = (await provider.provideResourceChatContext?.({ resource: URI.revive(options.resource) }, token)) ?? (await provider.provideChatContext?.({ resource: URI.revive(options.resource) }, token));
if (!result) {
return undefined;
}
if (result.label === undefined && result.resourceUri === undefined) {
throw new Error('ChatContextItem must have either a label or a resourceUri');
}
const itemHandle = this._addTrackedItem(handle, result);
const item: IChatContextItem = {
handle: itemHandle,
icon: result.icon,
label: result.label,
resourceUri: result.resourceUri,
modelDescription: result.modelDescription,
tooltip: result.tooltip ? MarkdownString.from(result.tooltip) : undefined,
value: options.withValue ? result.value : undefined,
command: result.command ? { id: result.command.command } : undefined
};
if (options.withValue && !item.value) {
const resolved = await (provider.resolveResourceChatContext ?? provider.resolveChatContext)?.bind(provider)(result, token);
item.value = resolved?.value;
item.tooltip = resolved?.tooltip ? MarkdownString.from(resolved.tooltip) : item.tooltip;
}
return item;
}
async $resolveResourceChatContext(handle: number, context: IChatContextItem, token: CancellationToken): Promise<IChatContextItem> {
const entry = this._providers.get(handle);
if (!entry || entry.type !== 'resource') {
throw new Error('Resource context provider not found');
}
const provider = entry.provider as vscode.ChatResourceContextProvider;
const extItem = this._globalItems.get(context.handle);
if (!extItem) {
throw new Error('Chat context item not found');
}
return this._doResolve((provider.resolveResourceChatContext ?? provider.resolveChatContext)?.bind(provider), context, extItem, token);
}
// Command execution
async $executeChatContextItemCommand(itemHandle: number): Promise<void> {
const extItem = this._globalItems.get(itemHandle);
if (!extItem) {
throw new Error('Chat context item not found');
}
if (!extItem.command) {
throw new Error('Chat context item has no command');
}
// Execute the command with the original extension item as an argument (reference equality)
const args = extItem.command.arguments ? [extItem, ...extItem.command.arguments] : [extItem];
await this._commands.executeCommand(extItem.command.command, ...args);
}
// Registration methods
registerChatWorkspaceContextProvider(id: string, provider: vscode.ChatWorkspaceContextProvider): vscode.Disposable {
const handle = this._handlePool++;
const disposables = new DisposableStore();
this._providers.set(handle, { type: 'workspace', provider, disposables });
this._listenForWorkspaceContextChanges(handle, provider, disposables);
this._proxy.$registerChatWorkspaceContextProvider(handle, id);
return {
dispose: () => {
this._providers.delete(handle);
this._clearProviderItems(handle);
this._providerItems.delete(handle);
this._proxy.$unregisterChatContextProvider(handle);
disposables.dispose();
}
};
}
registerChatExplicitContextProvider(id: string, provider: vscode.ChatExplicitContextProvider): vscode.Disposable {
const handle = this._handlePool++;
const disposables = new DisposableStore();
this._providers.set(handle, { type: 'explicit', provider, disposables });
this._proxy.$registerChatExplicitContextProvider(handle, id);
return {
dispose: () => {
this._providers.delete(handle);
this._clearProviderItems(handle);
this._providerItems.delete(handle);
this._proxy.$unregisterChatContextProvider(handle);
disposables.dispose();
}
};
}
registerChatResourceContextProvider(selector: vscode.DocumentSelector, id: string, provider: vscode.ChatResourceContextProvider): vscode.Disposable {
const handle = this._handlePool++;
const disposables = new DisposableStore();
this._providers.set(handle, { type: 'resource', provider, disposables });
this._proxy.$registerChatResourceContextProvider(handle, id, DocumentSelector.from(selector));
return {
dispose: () => {
this._providers.delete(handle);
this._clearProviderItems(handle);
this._providerItems.delete(handle);
this._proxy.$unregisterChatContextProvider(handle);
disposables.dispose();
}
};
}
/**
* @deprecated Use registerChatWorkspaceContextProvider, registerChatExplicitContextProvider, or registerChatResourceContextProvider instead.
*/
registerChatContextProvider(selector: vscode.DocumentSelector | undefined, id: string, provider: vscode.ChatContextProvider): vscode.Disposable {
const disposables: vscode.Disposable[] = [];
// Register workspace context provider if the provider supports it
if (provider.provideWorkspaceChatContext) {
const workspaceProvider: vscode.ChatWorkspaceContextProvider = {
onDidChangeWorkspaceChatContext: provider.onDidChangeWorkspaceChatContext,
provideWorkspaceChatContext: (token) => provider.provideWorkspaceChatContext!(token)
};
disposables.push(this.registerChatWorkspaceContextProvider(id, workspaceProvider));
}
// Register explicit context provider if the provider supports it
if (provider.provideChatContextExplicit) {
const explicitProvider: vscode.ChatExplicitContextProvider = {
provideExplicitChatContext: (token) => provider.provideChatContextExplicit!(token),
resolveExplicitChatContext: provider.resolveChatContext
? (context, token) => provider.resolveChatContext!(context, token)
: (context) => context
};
disposables.push(this.registerChatExplicitContextProvider(id, explicitProvider));
}
// Register resource context provider if the provider supports it and has a selector
if (provider.provideChatContextForResource && selector) {
const resourceProvider: vscode.ChatResourceContextProvider = {
provideResourceChatContext: (options, token) => provider.provideChatContextForResource!(options, token),
resolveResourceChatContext: provider.resolveChatContext
? (context, token) => provider.resolveChatContext!(context, token)
: (context) => context
};
disposables.push(this.registerChatResourceContextProvider(selector, id, resourceProvider));
}
return {
dispose: () => {
for (const disposable of disposables) {
disposable.dispose();
}
}
};
}
// Helper methods
private _clearProviderItems(handle: number): void {
const itemHandles = this._providerItems.get(handle);
if (itemHandles) {
for (const itemHandle of itemHandles) {
this._globalItems.delete(itemHandle);
const idx = this._itemInsertionOrder.indexOf(itemHandle);
if (idx !== -1) {
this._itemInsertionOrder.splice(idx, 1);
}
}
itemHandles.clear();
}
}
private _addTrackedItem(providerHandle: number, item: vscode.ChatContextItem): number {
const itemHandle = this._itemPool++;
this._evictOldestIfNecessary();
this._globalItems.set(itemHandle, item);
this._itemInsertionOrder.push(itemHandle);
if (!this._providerItems.has(providerHandle)) {
this._providerItems.set(providerHandle, new Set());
}
this._providerItems.get(providerHandle)!.add(itemHandle);
return itemHandle;
}
private _evictOldestIfNecessary(): void {
if (this._globalItems.size < ExtHostChatContext.MAX_GLOBAL_ITEMS) {
return;
}
const itemsToEvict = Math.ceil(ExtHostChatContext.MAX_GLOBAL_ITEMS * 0.1);
for (let i = 0; i < itemsToEvict && this._itemInsertionOrder.length > 0; i++) {
const oldestHandle = this._itemInsertionOrder.shift()!;
this._globalItems.delete(oldestHandle);
}
}
private _convertItems(handle: number, items: vscode.ChatContextItem[]): IChatContextItem[] {
const result: IChatContextItem[] = [];
for (const item of items) {
if (item.label === undefined && item.resourceUri === undefined) {
throw new Error('ChatContextItem must have either a label or a resourceUri');
}
const itemHandle = this._addTrackedItem(handle, item);
result.push({
handle: itemHandle,
icon: item.icon,
label: item.label,
resourceUri: item.resourceUri,
modelDescription: item.modelDescription,
tooltip: item.tooltip ? MarkdownString.from(item.tooltip) : undefined,
value: item.value,
command: item.command ? { id: item.command.command } : undefined
});
}
return result;
}
private async _doResolve(
resolveFn: (item: vscode.ChatContextItem, token: CancellationToken) => vscode.ProviderResult<vscode.ChatContextItem>,
context: IChatContextItem,
extItem: vscode.ChatContextItem,
token: CancellationToken
): Promise<IChatContextItem> {
const extResult = await resolveFn(extItem, token);
if (extResult) {
return {
handle: context.handle,
icon: extResult.icon,
label: extResult.label,
resourceUri: extResult.resourceUri,
modelDescription: extResult.modelDescription,
tooltip: extResult.tooltip ? MarkdownString.from(extResult.tooltip) : undefined,
value: extResult.value,
command: extResult.command ? { id: extResult.command.command } : undefined
};
}
return context;
}
private _listenForWorkspaceContextChanges(handle: number, provider: vscode.ChatWorkspaceContextProvider, disposables: DisposableStore): void {
if (!provider.onDidChangeWorkspaceChatContext) {
return;
}
const provideWorkspaceContext = async () => {
const workspaceContexts = (await provider.provideWorkspaceChatContext?.(CancellationToken.None) ?? await provider.provideChatContext?.(CancellationToken.None));
const resolvedContexts = this._convertItems(handle, workspaceContexts ?? []);
return this._proxy.$updateWorkspaceContextItems(handle, resolvedContexts);
};
disposables.add(provider.onDidChangeWorkspaceChatContext(async () => provideWorkspaceContext()));
// kick off initial workspace context fetch
provideWorkspaceContext();
}
public override dispose(): void {
super.dispose();
for (const { disposables } of this._providers.values()) {
disposables.dispose();
}
this._globalItems.clear();
this._itemInsertionOrder = [];
this._providerItems.clear();
}
}