-
Notifications
You must be signed in to change notification settings - Fork 39.5k
Expand file tree
/
Copy pathremoteAgentHost.contribution.ts
More file actions
645 lines (583 loc) · 30.4 KB
/
remoteAgentHost.contribution.ts
File metadata and controls
645 lines (583 loc) · 30.4 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable, DisposableMap, DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js';
import { observableValue } from '../../../../base/common/observable.js';
import { isEqualOrParent } from '../../../../base/common/resources.js';
import { URI } from '../../../../base/common/uri.js';
import * as nls from '../../../../nls.js';
import { agentHostAuthority } from '../../../../platform/agentHost/common/agentHostUri.js';
import { type AgentProvider, type IAgentConnection } from '../../../../platform/agentHost/common/agentService.js';
import { IRemoteAgentHostConnectionInfo, IRemoteAgentHostEntry, IRemoteAgentHostService, RemoteAgentHostAutoConnectSettingId, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId, RemoteAgentHostsSettingId, getEntryAddress } from '../../../../platform/agentHost/common/remoteAgentHostService.js';
import { TunnelAgentHostsSettingId } from '../../../../platform/agentHost/common/tunnelAgentHost.js';
import { type IProtectedResourceMetadata, type URI as ProtocolURI } from '../../../../platform/agentHost/common/state/protocol/state.js';
import { type IAgentInfo, type ICustomizationRef, type IRootState } from '../../../../platform/agentHost/common/state/sessionState.js';
import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js';
import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js';
import { IDefaultAccountService } from '../../../../platform/defaultAccount/common/defaultAccount.js';
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
import { ILogService } from '../../../../platform/log/common/log.js';
import product from '../../../../platform/product/common/product.js';
import { Registry } from '../../../../platform/registry/common/platform.js';
import { IStorageService } from '../../../../platform/storage/common/storage.js';
import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js';
import { AgentCustomizationSyncProvider } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentCustomizationSyncProvider.js';
import { resolveTokenForResource } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostAuth.js';
import { AgentHostLanguageModelProvider } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostLanguageModelProvider.js';
import { AgentHostSessionHandler } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.js';
import { LoggingAgentConnection } from '../../../../workbench/contrib/chat/browser/agentSessions/agentHost/loggingAgentConnection.js';
import { IChatSessionsService } from '../../../../workbench/contrib/chat/common/chatSessionsService.js';
import { ICustomizationHarnessService } from '../../../../workbench/contrib/chat/common/customizationHarnessService.js';
import { ILanguageModelsService } from '../../../../workbench/contrib/chat/common/languageModels.js';
import { IAgentPluginService } from '../../../../workbench/contrib/chat/common/plugins/agentPluginService.js';
import { PromptsType } from '../../../../workbench/contrib/chat/common/promptSyntax/promptTypes.js';
import { IAgentHostFileSystemService } from '../../../../workbench/services/agentHost/common/agentHostFileSystemService.js';
import { IAuthenticationService } from '../../../../workbench/services/authentication/common/authentication.js';
import { ISessionsProvidersService } from '../../../services/sessions/browser/sessionsProvidersService.js';
import { remoteAgentHostSessionTypeId } from '../common/remoteAgentHostSessionType.js';
import { createRemoteAgentHarnessDescriptor, RemoteAgentCustomizationItemProvider } from './remoteAgentHostCustomizationHarness.js';
import { RemoteAgentHostSessionsProvider } from './remoteAgentHostSessionsProvider.js';
import { SyncedCustomizationBundler } from './syncedCustomizationBundler.js';
import { ISSHRemoteAgentHostService } from '../../../../platform/agentHost/common/sshRemoteAgentHost.js';
/** Per-connection state bundle, disposed when a connection is removed. */
class ConnectionState extends Disposable {
readonly store = this._register(new DisposableStore());
readonly agents = this._register(new DisposableMap<AgentProvider, DisposableStore>());
readonly modelProviders = new Map<AgentProvider, AgentHostLanguageModelProvider>();
readonly loggedConnection: LoggingAgentConnection;
constructor(
readonly name: string | undefined,
connection: IAgentConnection,
channelId: string,
channelLabel: string,
@IInstantiationService instantiationService: IInstantiationService,
) {
super();
this.loggedConnection = this._register(instantiationService.createInstance(LoggingAgentConnection, connection, channelId, channelLabel));
}
}
/**
* Discovers available agents from each connected remote agent host and
* dynamically registers each one as a chat session type with its own
* session handler and language model provider.
*
* Uses the same unified {@link AgentHostSessionHandler} as the local
* agent host, obtaining per-connection {@link IAgentConnection}
* instances from {@link IRemoteAgentHostService.getConnection}.
*/
export class RemoteAgentHostContribution extends Disposable implements IWorkbenchContribution {
static readonly ID = 'sessions.contrib.remoteAgentHostContribution';
/** Per-connection state: client state + per-agent registrations. */
private readonly _connections = this._register(new DisposableMap<string, ConnectionState>());
/** Per-address sessions provider, registered for all configured entries. */
private readonly _providerStores = this._register(new DisposableMap<string, DisposableStore>());
private readonly _providerInstances = new Map<string, RemoteAgentHostSessionsProvider>();
private readonly _pendingSSHReconnects = new Set<string>();
constructor(
@IRemoteAgentHostService private readonly _remoteAgentHostService: IRemoteAgentHostService,
@IChatSessionsService private readonly _chatSessionsService: IChatSessionsService,
@ILanguageModelsService private readonly _languageModelsService: ILanguageModelsService,
@ILogService private readonly _logService: ILogService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IAuthenticationService private readonly _authenticationService: IAuthenticationService,
@IDefaultAccountService private readonly _defaultAccountService: IDefaultAccountService,
@ISessionsProvidersService private readonly _sessionsProvidersService: ISessionsProvidersService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IAgentHostFileSystemService private readonly _agentHostFileSystemService: IAgentHostFileSystemService,
@ISSHRemoteAgentHostService private readonly _sshService: ISSHRemoteAgentHostService,
@ICustomizationHarnessService private readonly _customizationHarnessService: ICustomizationHarnessService,
@IStorageService private readonly _storageService: IStorageService,
@IAgentPluginService private readonly _agentPluginService: IAgentPluginService,
) {
super();
// Reconcile providers when configured entries change
this._register(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(RemoteAgentHostsSettingId) || e.affectsConfiguration(RemoteAgentHostsEnabledSettingId) || e.affectsConfiguration(RemoteAgentHostAutoConnectSettingId)) {
this._reconcile();
}
}));
// Reconcile when connections change (added/removed/reconnected)
this._register(this._remoteAgentHostService.onDidChangeConnections(() => {
this._reconcile();
}));
// Push auth token whenever the default account or sessions change
this._register(this._defaultAccountService.onDidChangeDefaultAccount(() => this._authenticateAllConnections()));
this._register(this._authenticationService.onDidChangeSessions(() => this._authenticateAllConnections()));
// Initial setup for configured entries and connected remotes
this._reconcile();
}
private _reconcile(): void {
this._reconcileProviders();
this._reconcileConnections();
this._reconnectSSHEntries();
// Ensure every live connection is wired to its provider.
// This covers the case where a provider was recreated (e.g. name
// change) while a connection for that address already existed —
// we need to re-expose both the connection and the output channel,
// otherwise `Show Output` on the recreated provider would break.
for (const [address, connState] of this._connections) {
const connectionInfo = this._remoteAgentHostService.connections.find(c => c.address === address);
const provider = this._providerInstances.get(address);
if (provider) {
provider.setConnection(connState.loggedConnection, connectionInfo?.defaultDirectory);
provider.setOutputChannelId(connState.loggedConnection.channelId);
}
}
// Update connection status on all providers (including those
// that are reconnecting and don't have an active connection).
for (const [address, provider] of this._providerInstances) {
const connectionInfo = this._remoteAgentHostService.connections.find(c => c.address === address);
if (connectionInfo) {
provider.setConnectionStatus(connectionInfo.status);
} else {
provider.setConnectionStatus(RemoteAgentHostConnectionStatus.Disconnected);
}
}
}
private _reconcileProviders(): void {
const enabled = this._configurationService.getValue<boolean>(RemoteAgentHostsEnabledSettingId);
const entries = enabled ? this._remoteAgentHostService.configuredEntries : [];
const desiredAddresses = new Set(entries.map(e => getEntryAddress(e)));
// Remove providers no longer configured
for (const [address] of this._providerStores) {
if (!desiredAddresses.has(address)) {
this._providerStores.deleteAndDispose(address);
}
}
// Add or recreate providers for configured entries
for (const entry of entries) {
const address = getEntryAddress(entry);
const existing = this._providerInstances.get(address);
if (existing && existing.label !== (entry.name || address)) {
// Name changed — recreate since ISessionsProvider.label is readonly
this._providerStores.deleteAndDispose(address);
}
if (!this._providerStores.has(address)) {
this._createProvider(entry);
}
}
}
private _createProvider(entry: IRemoteAgentHostEntry): void {
const address = getEntryAddress(entry);
const store = new DisposableStore();
const provider = this._instantiationService.createInstance(
RemoteAgentHostSessionsProvider, { address, name: entry.name });
store.add(provider);
store.add(this._sessionsProvidersService.registerProvider(provider));
this._providerInstances.set(address, provider);
store.add(toDisposable(() => this._providerInstances.delete(address)));
this._providerStores.set(address, store);
}
/**
* Re-establish SSH connections for configured entries that have an
* sshConfigHost but no active connection.
*/
private _reconnectSSHEntries(): void {
const autoConnect = this._configurationService.getValue<boolean>(RemoteAgentHostAutoConnectSettingId);
const entries = this._remoteAgentHostService.configuredEntries;
for (const entry of entries) {
if (entry.connection.type !== RemoteAgentHostEntryType.SSH || !entry.connection.sshConfigHost) {
continue;
}
const address = getEntryAddress(entry);
const sshConfigHost = entry.connection.sshConfigHost;
// Skip if already connected or reconnecting
const hasConnection = this._remoteAgentHostService.connections.some(
c => c.address === address && c.status === RemoteAgentHostConnectionStatus.Connected
);
if (hasConnection || this._pendingSSHReconnects.has(sshConfigHost)) {
continue;
}
if (!autoConnect) {
continue;
}
this._pendingSSHReconnects.add(sshConfigHost);
this._logService.info(`[RemoteAgentHost] Re-establishing SSH tunnel for ${sshConfigHost}`);
this._sshService.reconnect(sshConfigHost, entry.name).then(() => {
this._pendingSSHReconnects.delete(sshConfigHost);
this._logService.info(`[RemoteAgentHost] SSH tunnel re-established for ${sshConfigHost}`);
}).catch(err => {
this._pendingSSHReconnects.delete(sshConfigHost);
this._logService.error(`[RemoteAgentHost] SSH reconnect failed for ${sshConfigHost}`, err);
// Host is unreachable — unpublish any cached sessions we
// were showing so the UI doesn't list stale entries for a
// host we cannot currently reach.
this._providerInstances.get(address)?.unpublishCachedSessions();
});
}
}
private _reconcileConnections(): void {
const currentConnections = this._remoteAgentHostService.connections;
const connectedAddresses = new Set(
currentConnections
.filter(c => c.status === RemoteAgentHostConnectionStatus.Connected)
.map(c => c.address)
);
const allAddresses = new Set(currentConnections.map(c => c.address));
// Remove contribution state for connections that are no longer present at all
for (const [address] of this._connections) {
if (!allAddresses.has(address)) {
this._logService.info(`[RemoteAgentHost] Removing contribution for ${address}`);
this._providerInstances.get(address)?.clearConnection();
this._connections.deleteAndDispose(address);
} else if (!connectedAddresses.has(address)) {
// Connection exists but is not connected (reconnecting or disconnected).
// Keep the contribution state but don't clear the provider —
// the session cache is preserved during reconnect.
}
}
// Add or update connections
for (const connectionInfo of currentConnections) {
// Only set up contribution state for connected entries
if (connectionInfo.status !== RemoteAgentHostConnectionStatus.Connected) {
continue;
}
const existing = this._connections.get(connectionInfo.address);
if (existing) {
// If the name or clientId changed, tear down and re-register
if (existing.name !== connectionInfo.name || existing.loggedConnection.clientId !== connectionInfo.clientId) {
this._logService.info(`[RemoteAgentHost] Reconnecting contribution for ${connectionInfo.address}`);
this._connections.deleteAndDispose(connectionInfo.address);
this._setupConnection(connectionInfo);
}
} else {
this._setupConnection(connectionInfo);
}
}
}
private _setupConnection(connectionInfo: IRemoteAgentHostConnectionInfo): void {
const connection = this._remoteAgentHostService.getConnection(connectionInfo.address);
if (!connection) {
return;
}
const { address, name } = connectionInfo;
const channelLabel = `Agent Host (${name || address})`;
const connState = this._instantiationService.createInstance(ConnectionState, name, connection, `agenthost.${connection.clientId}`, channelLabel);
const loggedConnection = connState.loggedConnection;
this._connections.set(address, connState);
const store = connState.store;
// Track authority -> connection mapping for FS provider routing
const authority = agentHostAuthority(address);
store.add(this._agentHostFileSystemService.registerAuthority(authority, connection));
// React to root state changes (agent discovery)
store.add(loggedConnection.rootState.onDidChange(rootState => {
this._handleRootStateChange(address, loggedConnection, rootState);
}));
// If root state is already available, process it immediately
const initialRootState = loggedConnection.rootState.value;
if (initialRootState && !(initialRootState instanceof Error)) {
this._handleRootStateChange(address, loggedConnection, initialRootState);
}
// Wire connection to existing sessions provider
const provider = this._providerInstances.get(address);
if (provider) {
provider.setConnection(loggedConnection, connectionInfo.defaultDirectory);
// Expose the output channel ID so the workspace picker can offer "Show Output"
provider.setOutputChannelId(loggedConnection.channelId);
}
}
private _handleRootStateChange(address: string, loggedConnection: LoggingAgentConnection, rootState: IRootState): void {
const connState = this._connections.get(address);
if (!connState) {
return;
}
const incoming = new Set(rootState.agents.map(a => a.provider));
// Remove agents no longer present
for (const [provider] of connState.agents) {
if (!incoming.has(provider)) {
connState.agents.deleteAndDispose(provider);
connState.modelProviders.delete(provider);
}
}
// Authenticate using protectedResources from agent info
this._authenticateWithConnection(address, loggedConnection, rootState.agents)
.catch(() => { /* best-effort */ });
// Register new agents, push model updates to existing ones
for (const agent of rootState.agents) {
if (!connState.agents.has(agent.provider)) {
this._registerAgent(address, loggedConnection, agent, connState.name);
} else {
const modelProvider = connState.modelProviders.get(agent.provider);
modelProvider?.updateModels(agent.models);
}
}
}
private _registerAgent(address: string, loggedConnection: LoggingAgentConnection, agent: IAgentInfo, configuredName: string | undefined): void {
const connState = this._connections.get(address);
if (!connState) {
return;
}
const agentStore = new DisposableStore();
connState.agents.set(agent.provider, agentStore);
connState.store.add(agentStore);
const sanitized = agentHostAuthority(address);
const providerId = `agenthost-${sanitized}`;
const sessionType = remoteAgentHostSessionTypeId(sanitized, agent.provider);
const agentId = sessionType;
const vendor = sessionType;
// User-facing display name for this agent. We always include the
// agent's own name so that a host exposing multiple agents (e.g.
// `copilot` + `openai` from the same machine) produces distinct
// labels instead of collapsing to a single `configuredName`.
const hostLabel = configuredName || address;
const agentLabel = agent.displayName?.trim() || agent.provider;
const displayName = `${agentLabel} [${hostLabel}]`;
// Per-agent working directory cache, scoped to the agent store lifetime
const sessionWorkingDirs = new Map<string, URI>();
agentStore.add(toDisposable(() => sessionWorkingDirs.clear()));
// Capture the working directory from the session that is being created.
const resolveWorkingDirectory = (sessionResource: URI): URI | undefined => {
const resourceKey = sessionResource.toString();
const cached = sessionWorkingDirs.get(resourceKey);
if (cached) {
return cached;
}
const provider = this._sessionsProvidersService.getProvider<RemoteAgentHostSessionsProvider>(providerId);
const session = provider?.getSessionByResource(sessionResource);
const repository = session?.workspace.get()?.repositories[0];
const workingDirectory = repository?.workingDirectory ?? repository?.uri;
if (workingDirectory) {
sessionWorkingDirs.set(resourceKey, workingDirectory);
return workingDirectory;
}
return undefined;
};
// Chat session contribution
agentStore.add(this._chatSessionsService.registerChatSessionContribution({
type: sessionType,
name: agentId,
displayName,
description: agent.description,
canDelegate: true,
requiresCustomModels: true,
supportsDelegation: false,
capabilities: {
supportsCheckpoints: true,
},
}));
// Customization harness for this remote agent
const itemProvider = agentStore.add(new RemoteAgentCustomizationItemProvider(agent, loggedConnection));
const syncProvider = agentStore.add(new AgentCustomizationSyncProvider(sessionType, this._storageService));
const harnessDescriptor = createRemoteAgentHarnessDescriptor(sessionType, displayName, itemProvider, syncProvider);
agentStore.add(this._customizationHarnessService.registerExternalHarness(harnessDescriptor));
// Bundler for packaging individual files into a virtual Open Plugin
const bundler = agentStore.add(this._instantiationService.createInstance(SyncedCustomizationBundler, sessionType));
// Agent-level customizations observable
const customizations = observableValue<ICustomizationRef[]>('agentCustomizations', []);
const updateCustomizations = async () => {
const refs = await this._resolveCustomizations(syncProvider, bundler);
customizations.set(refs, undefined);
};
agentStore.add(syncProvider.onDidChange(() => updateCustomizations()));
updateCustomizations(); // resolve initial state
// Session handler (unified)
const sessionHandler = agentStore.add(this._instantiationService.createInstance(
AgentHostSessionHandler, {
provider: agent.provider,
agentId,
sessionType,
fullName: displayName,
description: agent.description,
connection: loggedConnection,
connectionAuthority: sanitized,
extensionId: 'vscode.remote-agent-host',
extensionDisplayName: 'Remote Agent Host',
resolveWorkingDirectory,
resolveAuthentication: (resources) => this._resolveAuthenticationInteractively(loggedConnection, resources),
customizations,
}));
agentStore.add(this._chatSessionsService.registerChatSessionContentProvider(sessionType, sessionHandler));
// Language model provider.
// Order matters: `updateModels` must be called after
// `registerLanguageModelProvider` so the initial `onDidChange` is observed.
const vendorDescriptor = { vendor, displayName, configuration: undefined, managementCommand: undefined, when: undefined };
this._languageModelsService.deltaLanguageModelChatProviderDescriptors([vendorDescriptor], []);
agentStore.add(toDisposable(() => this._languageModelsService.deltaLanguageModelChatProviderDescriptors([], [vendorDescriptor])));
const modelProvider = agentStore.add(new AgentHostLanguageModelProvider(sessionType, vendor));
connState.modelProviders.set(agent.provider, modelProvider);
agentStore.add(toDisposable(() => connState.modelProviders.delete(agent.provider)));
agentStore.add(this._languageModelsService.registerLanguageModelProvider(vendor, modelProvider));
modelProvider.updateModels(agent.models);
this._logService.info(`[RemoteAgentHost] Registered agent ${agent.provider} from ${address} as ${sessionType}`);
}
/**
* Resolves the customizations to include in the active client set.
*
* Entries are classified as either:
* - **Plugin**: A selected URI matches an installed plugin's root URI.
* - **Individual file**: All other selected files are bundled into a
* synthetic Open Plugin via {@link SyncedCustomizationBundler}.
*/
private async _resolveCustomizations(
syncProvider: AgentCustomizationSyncProvider,
bundler: SyncedCustomizationBundler,
): Promise<ICustomizationRef[]> {
const entries = syncProvider.getSelectedEntries();
if (entries.length === 0) {
return [];
}
const plugins = this._agentPluginService.plugins.get();
const refs: ICustomizationRef[] = [];
const individualFiles: { uri: URI; type: PromptsType }[] = [];
for (const entry of entries) {
const plugin = plugins.find(p => isEqualOrParent(entry.uri, p.uri));
if (plugin) {
refs.push({
uri: plugin.uri.toString() as ProtocolURI,
displayName: plugin.label,
});
} else if (entry.type) {
individualFiles.push({ uri: entry.uri, type: entry.type });
}
}
if (individualFiles.length > 0) {
const result = await bundler.bundle(individualFiles);
if (result) {
refs.push(result.ref);
}
}
return refs;
}
private _authenticateAllConnections(): void {
for (const [address, connState] of this._connections) {
const rootState = connState.loggedConnection.rootState.value;
if (rootState && !(rootState instanceof Error)) {
this._authenticateWithConnection(address, connState.loggedConnection, rootState.agents).catch(() => { /* best-effort */ });
}
}
}
/**
* Authenticate using protectedResources from agent info in root state.
* Resolves tokens via the standard VS Code authentication service.
*
* Marks the matching provider's `authenticationPending` observable while
* the auth pass is in flight so that sessions surface as still loading.
*/
private async _authenticateWithConnection(address: string, loggedConnection: LoggingAgentConnection, agents: readonly IAgentInfo[]): Promise<void> {
const providerId = `agenthost-${agentHostAuthority(address)}`;
const provider = this._sessionsProvidersService.getProvider<RemoteAgentHostSessionsProvider>(providerId);
provider?.setAuthenticationPending(true);
try {
for (const agent of agents) {
for (const resource of agent.protectedResources ?? []) {
const resourceUri = URI.parse(resource.resource);
const token = await this._resolveTokenForResource(resourceUri, resource.authorization_servers ?? [], resource.scopes_supported ?? []);
if (token) {
this._logService.info(`[RemoteAgentHost] Authenticating for resource: ${resource.resource}`);
await loggedConnection.authenticate({ resource: resource.resource, token });
} else {
this._logService.info(`[RemoteAgentHost] No token resolved for resource: ${resource.resource}`);
}
}
}
} catch (err) {
this._logService.error('[RemoteAgentHost] Failed to authenticate with connection', err);
loggedConnection.logError('authenticateWithConnection', err);
} finally {
provider?.setAuthenticationPending(false);
}
}
/**
* Resolve a bearer token for a set of authorization servers using the
* standard VS Code authentication service provider resolution.
*/
private _resolveTokenForResource(resourceServer: URI, authorizationServers: readonly string[], scopes: readonly string[]): Promise<string | undefined> {
return resolveTokenForResource(resourceServer, authorizationServers, scopes, this._authenticationService, this._logService, '[RemoteAgentHost]');
}
/**
* Interactively prompt the user to authenticate when the server requires it.
* Returns true if authentication succeeded.
*/
private async _resolveAuthenticationInteractively(loggedConnection: LoggingAgentConnection, protectedResources: readonly IProtectedResourceMetadata[]): Promise<boolean> {
try {
for (const resource of protectedResources) {
for (const server of resource.authorization_servers ?? []) {
const serverUri = URI.parse(server);
const resourceUri = URI.parse(resource.resource);
const token = await this._resolveTokenForResource(resourceUri, resource.authorization_servers ?? [], resource.scopes_supported ?? []);
if (token) {
await loggedConnection.authenticate({
resource: resource.resource,
token,
});
} else {
const providerId = await this._authenticationService.getOrActivateProviderIdForServer(serverUri, resourceUri);
if (!providerId) {
continue;
}
const scopes = [...(resource.scopes_supported ?? [])];
const session = await this._authenticationService.createSession(providerId, scopes, {
activateImmediate: true,
authorizationServer: serverUri,
});
await loggedConnection.authenticate({
resource: resource.resource,
token: session.accessToken,
});
}
this._logService.info(`[RemoteAgentHost] Interactive authentication succeeded for ${resource.resource}`);
return true;
}
}
} catch (err) {
this._logService.error('[RemoteAgentHost] Interactive authentication failed', err);
loggedConnection.logError('resolveAuthenticationInteractively', err);
}
return false;
}
}
registerWorkbenchContribution2(RemoteAgentHostContribution.ID, RemoteAgentHostContribution, WorkbenchPhase.AfterRestored);
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
properties: {
[RemoteAgentHostsEnabledSettingId]: {
type: 'boolean',
description: nls.localize('chat.remoteAgentHosts.enabled', "Enable connecting to remote agent hosts."),
default: product.quality !== 'stable',
scope: ConfigurationScope.APPLICATION,
tags: ['experimental', 'advanced'],
},
[RemoteAgentHostAutoConnectSettingId]: {
type: 'boolean',
description: nls.localize('chat.remoteAgentHosts.autoConnect', "Automatically connect to online dev tunnel and SSH-configured remote agent hosts on startup. When disabled, cached sessions are still shown but connections are established only on demand."),
default: true,
scope: ConfigurationScope.APPLICATION,
tags: ['experimental', 'advanced'],
},
'chat.sshRemoteAgentHostCommand': {
type: 'string',
description: nls.localize('chat.sshRemoteAgentHostCommand', "For development: Override the command used to start the remote agent host over SSH. When set, skips automatic CLI installation and runs this command instead. The command must print a WebSocket URL matching ws://127.0.0.1:PORT (optionally with ?tkn=TOKEN) to stdout or stderr./"),
default: '',
scope: ConfigurationScope.APPLICATION,
tags: ['experimental', 'advanced'],
},
[RemoteAgentHostsSettingId]: {
type: 'array',
items: {
type: 'object',
properties: {
address: { type: 'string', description: nls.localize('chat.remoteAgentHosts.address', "The address of the remote agent host (e.g. \"localhost:3000\").") },
name: { type: 'string', description: nls.localize('chat.remoteAgentHosts.name', "A display name for this remote agent host.") },
connectionToken: { type: 'string', description: nls.localize('chat.remoteAgentHosts.connectionToken', "An optional connection token for authenticating with the remote agent host.") },
sshConfigHost: { type: 'string', description: nls.localize('chat.remoteAgentHosts.sshConfigHost', "SSH config host alias for automatic reconnection via SSH tunnel.") },
},
required: ['address', 'name'],
},
description: nls.localize('chat.remoteAgentHosts', "A list of remote agent host addresses to connect to (e.g. \"localhost:3000\")."),
default: [],
scope: ConfigurationScope.APPLICATION,
tags: ['experimental', 'advanced'],
},
[TunnelAgentHostsSettingId]: {
type: 'array',
items: { type: 'string' },
description: nls.localize('chat.remoteAgentTunnels', "Additional dev tunnel names to look for when connecting to remote agent hosts. These are looked up in addition to tunnels automatically enumerated from your account."),
default: [],
scope: ConfigurationScope.APPLICATION,
tags: ['experimental', 'advanced'],
},
},
});
// Side-effect registrations for the remote agent host feature
import './remoteAgentHostActions.js';
import '../../chat/browser/agentHostModelPicker.js';