-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathcopilotRemoteAgent.ts
More file actions
1327 lines (1152 loc) · 48.1 KB
/
copilotRemoteAgent.ts
File metadata and controls
1327 lines (1152 loc) · 48.1 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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as pathLib from 'path';
import * as marked from 'marked';
import vscode from 'vscode';
import { parseSessionLogs, parseToolCallDetails, StrReplaceEditorToolData } from '../../common/sessionParsing';
import { COPILOT_ACCOUNTS } from '../common/comment';
import { CopilotRemoteAgentConfig } from '../common/config';
import { COPILOT_LOGINS, COPILOT_SWE_AGENT, CopilotPRStatus, mostRecentCopilotEvent } from '../common/copilot';
import { commands } from '../common/executeCommands';
import { Disposable } from '../common/lifecycle';
import Logger from '../common/logger';
import { GitHubRemote } from '../common/remote';
import { CODING_AGENT, CODING_AGENT_AUTO_COMMIT_AND_PUSH } from '../common/settingKeys';
import { ITelemetry } from '../common/telemetry';
import { toOpenPullRequestWebviewUri } from '../common/uri';
import { copilotEventToSessionStatus, copilotPRStatusToSessionStatus, IAPISessionLogs, ICopilotRemoteAgentCommandArgs, ICopilotRemoteAgentCommandResponse, OctokitCommon, RemoteAgentResult, RepoInfo } from './common';
import { ChatSessionWithPR, CopilotApi, getCopilotApi, RemoteAgentJobPayload, SessionInfo, SessionSetupStep } from './copilotApi';
import { CopilotPRWatcher, CopilotStateModel } from './copilotPrWatcher';
import { ChatSessionContentBuilder } from './copilotRemoteAgent/chatSessionContentBuilder';
import { GitOperationsManager } from './copilotRemoteAgent/gitOperationsManager';
import { CredentialStore } from './credentials';
import { FolderRepositoryManager, ReposManagerState } from './folderRepositoryManager';
import { GitHubRepository } from './githubRepository';
import { GithubItemStateEnum } from './interface';
import { issueMarkdown, PlainTextRenderer } from './markdownUtils';
import { PullRequestModel } from './pullRequestModel';
import { chooseItem } from './quickPicks';
import { RepositoriesManager } from './repositoriesManager';
const LEARN_MORE = vscode.l10n.t('Learn about coding agent');
// Without Pending Changes
const CONTINUE = vscode.l10n.t('Continue');
// With Pending Changes
const PUSH_CHANGES = vscode.l10n.t('Include changes');
const CONTINUE_WITHOUT_PUSHING = vscode.l10n.t('Ignore changes');
const CONTINUE_AND_DO_NOT_ASK_AGAIN = vscode.l10n.t('Continue and don\'t ask again');
const COPILOT = '@copilot';
const body_suffix = vscode.l10n.t('Created from VS Code via the [GitHub Pull Request](https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-pull-request-github) extension.');
const PREFERRED_GITHUB_CODING_AGENT_REMOTE_WORKSPACE_KEY = 'PREFERRED_GITHUB_CODING_AGENT_REMOTE';
export class CopilotRemoteAgentManager extends Disposable {
public static ID = 'CopilotRemoteAgentManager';
private readonly _stateModel: CopilotStateModel;
private readonly _onDidChangeStates = this._register(new vscode.EventEmitter<void>());
readonly onDidChangeStates = this._onDidChangeStates.event;
private readonly _onDidChangeNotifications = this._register(new vscode.EventEmitter<PullRequestModel[]>());
readonly onDidChangeNotifications = this._onDidChangeNotifications.event;
private readonly _onDidCreatePullRequest = this._register(new vscode.EventEmitter<number>());
readonly onDidCreatePullRequest = this._onDidCreatePullRequest.event;
private readonly _onDidChangeChatSessions = this._register(new vscode.EventEmitter<void>());
readonly onDidChangeChatSessions = this._onDidChangeChatSessions.event;
private readonly gitOperationsManager: GitOperationsManager;
constructor(private credentialStore: CredentialStore, public repositoriesManager: RepositoriesManager, private telemetry: ITelemetry, private context: vscode.ExtensionContext) {
super();
this.gitOperationsManager = new GitOperationsManager(CopilotRemoteAgentManager.ID);
this._register(this.credentialStore.onDidChangeSessions((e: vscode.AuthenticationSessionsChangeEvent) => {
if (e.provider.id === 'github') {
this._copilotApiPromise = undefined; // Invalidate cached session
}
}));
this._stateModel = new CopilotStateModel();
this._register(new CopilotPRWatcher(this.repositoriesManager, this._stateModel));
this._register(this._stateModel.onDidChangeStates(() => {
this._onDidChangeStates.fire();
this._onDidChangeChatSessions.fire();
}));
this._register(this._stateModel.onDidChangeNotifications(items => this._onDidChangeNotifications.fire(items)));
this._register(this.repositoriesManager.onDidChangeFolderRepositories((event) => {
if (event.added) {
this._register(event.added.onDidChangeAssignableUsers(() => {
this.updateAssignabilityContext();
}));
}
this.updateAssignabilityContext();
}));
this.repositoriesManager.folderManagers.forEach(manager => {
this._register(manager.onDidChangeAssignableUsers(() => {
this.updateAssignabilityContext();
}));
});
this._register(vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration(CODING_AGENT)) {
this.updateAssignabilityContext();
}
}));
// Set initial context
this.updateAssignabilityContext();
}
private _copilotApiPromise: Promise<CopilotApi | undefined> | undefined;
private get copilotApi(): Promise<CopilotApi | undefined> {
if (!this._copilotApiPromise) {
this._copilotApiPromise = this.initializeCopilotApi();
}
return this._copilotApiPromise;
}
private async initializeCopilotApi(): Promise<CopilotApi | undefined> {
return await getCopilotApi(this.credentialStore, this.telemetry);
}
public get enabled(): boolean {
return CopilotRemoteAgentConfig.getEnabled();
}
public get autoCommitAndPushEnabled(): boolean {
return CopilotRemoteAgentConfig.getAutoCommitAndPushEnabled();
}
private _repoManagerInitializationPromise: Promise<void> | undefined;
private async waitRepoManagerInitialization() {
if (this.repositoriesManager.state === ReposManagerState.RepositoriesLoaded || this.repositoriesManager.state === ReposManagerState.NeedsAuthentication) {
return;
}
if (!this._repoManagerInitializationPromise) {
this._repoManagerInitializationPromise = new Promise((resolve) => {
const disposable = this.repositoriesManager.onDidChangeState(() => {
if (this.repositoriesManager.state === ReposManagerState.RepositoriesLoaded || this.repositoriesManager.state === ReposManagerState.NeedsAuthentication) {
disposable.dispose();
resolve();
}
});
});
}
return this._repoManagerInitializationPromise;
}
async isAssignable(): Promise<boolean> {
const repoInfo = await this.repoInfo();
if (!repoInfo) {
return false;
}
const { fm } = repoInfo;
try {
// Ensure assignable users are loaded
await fm.getAssignableUsers();
const allAssignableUsers = fm.getAllAssignableUsers();
if (!allAssignableUsers) {
return false;
}
// Check if any of the copilot logins are in the assignable users
return allAssignableUsers.some(user => COPILOT_LOGINS.includes(user.login));
} catch (error) {
// If there's an error fetching assignable users, assume not assignable
return false;
}
}
async isAvailable(): Promise<boolean> {
// Check if the manager is enabled, copilot API is available, and it's assignable
if (!CopilotRemoteAgentConfig.getEnabled()) {
return false;
}
if (!this.credentialStore.isAnyAuthenticated()) {
// If not signed in, then we optimistically say it's available.
return true;
}
const repoInfo = await this.repoInfo();
if (!repoInfo) {
return false;
}
const copilotApi = await this.copilotApi;
if (!copilotApi) {
return false;
}
return await this.isAssignable();
}
private async updateAssignabilityContext(): Promise<void> {
try {
const available = await this.isAvailable();
commands.setContext('copilotCodingAgentAssignable', available);
} catch (error) {
// Presume false
commands.setContext('copilotCodingAgentAssignable', false);
}
}
private firstFolderManager(): FolderRepositoryManager | undefined {
if (!this.repositoriesManager.folderManagers.length) {
return;
}
return this.repositoriesManager.folderManagers[0];
}
private chooseFolderManager(): Promise<FolderRepositoryManager | undefined> {
return chooseItem<FolderRepositoryManager>(
this.repositoriesManager.folderManagers,
itemValue => pathLib.basename(itemValue.repository.rootUri.fsPath),
);
}
public async resetCodingAgentPreferences() {
await this.context.workspaceState.update(PREFERRED_GITHUB_CODING_AGENT_REMOTE_WORKSPACE_KEY, undefined);
}
public async promptAndUpdatePreferredGitHubRemote(skipIfValueAlreadyCached = false): Promise<void> {
if (skipIfValueAlreadyCached) {
const cachedValue = await this.context.workspaceState.get(PREFERRED_GITHUB_CODING_AGENT_REMOTE_WORKSPACE_KEY);
if (cachedValue) {
return;
}
}
const fm = this.firstFolderManager();
if (!fm) {
return;
}
const ghRemotes = await fm.getAllGitHubRemotes();
Logger.trace(`There are ${ghRemotes.length} GitHub remotes available to select from`, CopilotRemoteAgentManager.ID);
if (!ghRemotes || ghRemotes.length <= 1) {
Logger.trace('No need to select a coding agent GitHub remote, skipping prompt', CopilotRemoteAgentManager.ID);
return;
}
const result = await chooseItem<GitHubRemote>(
ghRemotes,
itemValue => `${itemValue.remoteName} (${itemValue.owner}/${itemValue.repositoryName})`,
{
title: vscode.l10n.t('Set the GitHub remote to target when creating a coding agent session'),
}
);
if (!result) {
Logger.warn('No coding agent GitHub remote selected. Clearing preferences.', CopilotRemoteAgentManager.ID);
return;
}
Logger.appendLine(`Updated '${result.remoteName}' as preferred coding agent remote`, CopilotRemoteAgentManager.ID);
await this.context.workspaceState.update(PREFERRED_GITHUB_CODING_AGENT_REMOTE_WORKSPACE_KEY, result.remoteName);
}
async repoInfo(fm?: FolderRepositoryManager): Promise<RepoInfo | undefined> {
fm = fm || this.firstFolderManager();
const repository = fm?.repository;
const ghRepository = fm?.gitHubRepositories.find(repo => repo.remote instanceof GitHubRemote) as GitHubRepository | undefined;
if (!fm || !repository || !ghRepository) {
return;
}
const baseRef = repository.state.HEAD?.name; // TODO: Consider edge cases
const preferredRemoteName = this.context.workspaceState.get(PREFERRED_GITHUB_CODING_AGENT_REMOTE_WORKSPACE_KEY);
const ghRemotes = await fm.getGitHubRemotes();
if (!ghRemotes || ghRemotes.length === 0) {
return;
}
const remote =
preferredRemoteName
? ghRemotes.find(remote => remote.remoteName === preferredRemoteName) // Cached preferred value
: (ghRemotes.find(remote => remote.remoteName === 'origin') || ghRemotes[0]); // Fallback to the first remote
if (!remote) {
Logger.error(`no valid remotes for coding agent`, CopilotRemoteAgentManager.ID);
// Clear preference, something is wrong
this.context.workspaceState.update(PREFERRED_GITHUB_CODING_AGENT_REMOTE_WORKSPACE_KEY, undefined);
return;
}
// Extract repo data from target remote
const { owner, repositoryName: repo } = remote;
if (!owner || !repo || !baseRef || !repository) {
return;
}
return { owner, repo, baseRef, remote, repository, ghRepository, fm };
}
async addFollowUpToExistingPR(pullRequestNumber: number, userPrompt: string, summary?: string): Promise<string | undefined> {
const repoInfo = await this.repoInfo();
if (!repoInfo) {
return;
}
try {
const ghRepo = repoInfo.ghRepository;
const pr = await ghRepo.getPullRequest(pullRequestNumber);
if (!pr) {
Logger.error(`Could not find pull request #${pullRequestNumber}`, CopilotRemoteAgentManager.ID);
return;
}
// Add a comment tagging @copilot with the user's prompt
const commentBody = `${COPILOT} ${userPrompt} \n\n --- \n\n ${summary ?? ''}`;
const commentResult = await pr.createIssueComment(commentBody);
if (!commentResult) {
Logger.error(`Failed to add comment to PR #${pullRequestNumber}`, CopilotRemoteAgentManager.ID);
return;
}
Logger.appendLine(`Added comment ${commentResult.htmlUrl}`, CopilotRemoteAgentManager.ID);
// allow-any-unicode-next-line
return vscode.l10n.t('🚀 Follow-up comment added to [#{0}]({1})', pullRequestNumber, commentResult.htmlUrl);
} catch (err) {
Logger.error(`Failed to add follow-up comment to PR #${pullRequestNumber}: ${err}`, CopilotRemoteAgentManager.ID);
return;
}
}
async tryPromptForAuthAndRepo(): Promise<FolderRepositoryManager | undefined> {
const authResult = await this.credentialStore.tryPromptForCopilotAuth();
if (!authResult) {
return undefined;
}
// Wait for repos to update
const fm = await this.chooseFolderManager();
await fm?.updateRepositories();
return fm;
}
async commandImpl(args?: ICopilotRemoteAgentCommandArgs): Promise<string | ICopilotRemoteAgentCommandResponse | undefined> {
if (!args) {
return;
}
const { userPrompt, summary, source, followup, _version } = args;
const fm = await this.tryPromptForAuthAndRepo();
if (!fm) {
return;
}
/* __GDPR__
"remoteAgent.command.args" : {
"source" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"isFollowup" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"userPromptLength" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"summaryLength" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"version" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryEvent('remoteAgent.command.args', {
source: source?.toString() || 'unknown',
isFollowup: !!followup ? 'true' : 'false',
userPromptLength: userPrompt.length.toString(),
summaryLength: summary ? summary.length.toString() : '0',
version: _version?.toString() || 'unknown'
});
if (!userPrompt || userPrompt.trim().length === 0) {
return;
}
const repoInfo = await this.repoInfo(fm);
if (!repoInfo) {
/* __GDPR__
"remoteAgent.command.result" : {
"reason" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryErrorEvent('remoteAgent.command.result', { reason: 'noRepositoryInfo' });
return;
}
const { repository, owner, repo } = repoInfo;
const repoName = `${owner}/${repo}`;
const hasChanges = repository.state.workingTreeChanges.length > 0 || repository.state.indexChanges.length > 0;
const learnMoreCb = async () => {
/* __GDPR__
"remoteAgent.command.result" : {
"reason" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryErrorEvent('remoteAgent.command.result', { reason: 'learnMore' });
vscode.env.openExternal(vscode.Uri.parse('https://aka.ms/coding-agent-docs'));
};
let autoPushAndCommit = false;
const message = vscode.l10n.t('Copilot coding agent will continue your work in \'{0}\'.', repoName);
const detail = vscode.l10n.t('Your chat context will be used to continue work in a new pull request.');
if (source !== 'prompt' && hasChanges && CopilotRemoteAgentConfig.getAutoCommitAndPushEnabled()) {
// Pending changes modal
const modalResult = await vscode.window.showInformationMessage(
message,
{
modal: true,
detail,
},
PUSH_CHANGES,
CONTINUE_WITHOUT_PUSHING,
LEARN_MORE,
);
if (!modalResult) {
/* __GDPR__
"remoteAgent.command.result" : {
"reason" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryErrorEvent('remoteAgent.command.result', { reason: 'cancel' });
return;
}
if (modalResult === LEARN_MORE) {
learnMoreCb();
return;
}
if (modalResult === PUSH_CHANGES) {
autoPushAndCommit = true;
}
} else if (CopilotRemoteAgentConfig.getPromptForConfirmation()) {
// No pending changes modal
const modalResult = await vscode.window.showInformationMessage(
source !== 'prompt' ? message : vscode.l10n.t('Copilot coding agent will implement the specification outlined in this prompt file'),
{
modal: true,
detail: source !== 'prompt' ? detail : undefined
},
CONTINUE,
CONTINUE_AND_DO_NOT_ASK_AGAIN,
LEARN_MORE,
);
if (!modalResult) {
return;
}
if (modalResult === CONTINUE_AND_DO_NOT_ASK_AGAIN) {
await CopilotRemoteAgentConfig.disablePromptForConfirmation();
}
if (modalResult === LEARN_MORE) {
learnMoreCb();
return;
}
}
const result = await this.invokeRemoteAgent(
userPrompt,
summary || userPrompt,
autoPushAndCommit,
);
if (result.state !== 'success') {
/* __GDPR__
"remoteAgent.command.result" : {
"reason" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryErrorEvent('remoteAgent.command.result', { reason: 'invocationFailure' });
vscode.window.showErrorMessage(result.error);
return;
}
const { webviewUri, link, number } = result;
/* __GDPR__
"remoteAgent.command.success" : {
"source" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"hasFollowup" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryEvent('remoteAgent.command.success', {
source: source || 'unknown',
hasFollowup: (!!followup).toString(),
outcome: 'success'
});
const viewLocationSetting = vscode.workspace.getConfiguration('chat').get('agentSessionsViewLocation');
const pr = await (async () => {
const capi = await this.copilotApi;
if (!capi) {
return;
}
const sessions = await capi.getAllCodingAgentPRs(this.repositoriesManager);
return sessions.find(session => session.number === number);
})();
if (!viewLocationSetting || viewLocationSetting === 'disabled') {
vscode.commands.executeCommand('vscode.open', webviewUri);
} else {
await this.provideChatSessions(new vscode.CancellationTokenSource().token);
if (pr) {
vscode.window.showChatSession(COPILOT_SWE_AGENT, `${pr.number}`, {});
}
}
if (pr && (_version && _version === 2)) { /* version 2 means caller knows how to render this */
const plaintextBody = marked.parse(pr.body, { renderer: new PlainTextRenderer(), }).trim();
return {
uri: webviewUri.toString(),
title: pr.title,
description: plaintextBody,
author: COPILOT_ACCOUNTS[pr.author.login].name,
linkTag: `#${pr.number}`
};
}
// allow-any-unicode-next-line
return vscode.l10n.t('🚀 Coding agent will continue work in [#{0}]({1}). Track progress [here]({2}).', number, link, webviewUri.toString());
}
async invokeRemoteAgent(prompt: string, problemContext: string, autoPushAndCommit = true): Promise<RemoteAgentResult> {
const capiClient = await this.copilotApi;
if (!capiClient) {
return { error: vscode.l10n.t('Failed to initialize Copilot API'), state: 'error' };
}
await this.promptAndUpdatePreferredGitHubRemote(true);
const repoInfo = await this.repoInfo();
if (!repoInfo) {
return { error: vscode.l10n.t('No repository information found. Please open a workspace with a GitHub repository.'), state: 'error' };
}
const { owner, repo, remote, repository, ghRepository, baseRef } = repoInfo;
// NOTE: This is as unobtrusive as possible with the current high-level APIs.
// We only create a new branch and commit if there are staged or working changes.
// This could be improved if we add lower-level APIs to our git extension (e.g. in-memory temp git index).
let ref = baseRef;
const hasChanges = autoPushAndCommit && (repository.state.workingTreeChanges.length > 0 || repository.state.indexChanges.length > 0);
if (hasChanges) {
if (!CopilotRemoteAgentConfig.getAutoCommitAndPushEnabled()) {
return { error: vscode.l10n.t('Uncommitted changes detected. Please commit or stash your changes before starting the remote agent. Enable \'{0}\' to push your changes automatically.', CODING_AGENT_AUTO_COMMIT_AND_PUSH), state: 'error' };
}
try {
await this.gitOperationsManager.commitAndPushChanges(repoInfo);
} catch (error) {
return { error: error.message, state: 'error' };
}
}
const base_ref = hasChanges ? baseRef : ref;
try {
if (!(await ghRepository.hasBranch(base_ref))) {
if (!CopilotRemoteAgentConfig.getAutoCommitAndPushEnabled()) {
// We won't auto-push a branch if the user has disabled the setting
return { error: vscode.l10n.t('The branch \'{0}\' does not exist on the remote repository \'{1}/{2}\'. Please create the remote branch first.', base_ref, owner, repo), state: 'error' };
}
// Push the branch
Logger.appendLine(`Base ref needs to exist on remote. Auto pushing base_ref '${base_ref}' to remote repository '${owner}/${repo}'`, CopilotRemoteAgentManager.ID);
await repository.push(remote.remoteName, base_ref, true);
}
} catch (error) {
return { error: vscode.l10n.t('Failed to configure base branch \'{0}\' does not exist on the remote repository \'{1}/{2}\'. Please create the remote branch first.', base_ref, owner, repo), state: 'error' };
}
let title = prompt;
const titleMatch = problemContext.match(/TITLE: \s*(.*)/i);
if (titleMatch && titleMatch[1]) {
title = titleMatch[1].trim();
}
const formatBodyPlaceholder = (problemContext: string): string => {
const header = vscode.l10n.t('Coding agent has begun work on **{0}** and will replace this description as work progresses.', title);
const collapsedContext = `<details><summary>${vscode.l10n.t('See problem context')}</summary>\n\n${problemContext}\n\n</details>`;
return `${header}\n\n${collapsedContext}`;
};
const problemStatement: string = `${prompt} ${problemContext ? `: ${problemContext}` : ''}`;
const payload: RemoteAgentJobPayload = {
problem_statement: problemStatement,
event_type: 'visual_studio_code_remote_agent_tool_invoked',
pull_request: {
title,
body_placeholder: formatBodyPlaceholder(problemContext),
base_ref,
body_suffix,
...(hasChanges && { head_ref: ref })
}
};
try {
const { pull_request } = await capiClient.postRemoteAgentJob(owner, repo, payload);
this._onDidCreatePullRequest.fire(pull_request.number);
const webviewUri = await toOpenPullRequestWebviewUri({ owner, repo, pullRequestNumber: pull_request.number });
const prLlmString = `The remote agent has begun work and has created a pull request. Details about the pull request are being shown to the user. If the user wants to track progress or iterate on the agent's work, they should use the pull request.`;
return {
state: 'success',
number: pull_request.number,
link: pull_request.html_url,
webviewUri,
llmDetails: hasChanges ? `The pending changes have been pushed to branch '${ref}'. ${prLlmString}` : prLlmString
};
} catch (error) {
return { error: error.message, state: 'error' };
}
}
async getSessionLogsFromAction(pullRequest: PullRequestModel) {
const capi = await this.copilotApi;
if (!capi) {
return [];
}
const lastRun = await this.getLatestCodingAgentFromAction(pullRequest);
if (!lastRun) {
return [];
}
return await capi.getLogsFromZipUrl(lastRun.logs_url);
}
async getWorkflowStepsFromAction(pullRequest: PullRequestModel): Promise<SessionSetupStep[]> {
const lastRun = await this.getLatestCodingAgentFromAction(pullRequest, 0, false);
if (!lastRun) {
return [];
}
try {
const jobs = await pullRequest.githubRepository.getWorkflowJobs(lastRun.id);
const steps: SessionSetupStep[] = [];
for (const job of jobs) {
if (job.steps) {
for (const step of job.steps) {
steps.push({ name: step.name, status: step.status });
}
}
}
return steps;
} catch (error) {
Logger.error(`Failed to get workflow steps: ${error}`, CopilotRemoteAgentManager.ID);
return [];
}
}
async getLatestCodingAgentFromAction(pullRequest: PullRequestModel, sessionIndex = 0, completedOnly = true): Promise<OctokitCommon.WorkflowRun | undefined> {
const capi = await this.copilotApi;
if (!capi) {
return;
}
const runs = await pullRequest.githubRepository.getWorkflowRunsFromAction(pullRequest.createdAt);
const workflowRuns = runs.flatMap(run => run.workflow_runs);
const padawanRuns = workflowRuns
.filter(run => run.path && run.path.startsWith(`dynamic/${COPILOT_SWE_AGENT}`))
.filter(run => run.pull_requests?.some(pr => pr.id === pullRequest.id));
const session = padawanRuns.filter(s => !completedOnly || s.status === 'completed').at(sessionIndex);
if (!session) {
return;
}
return this.getLatestRun(padawanRuns);
}
async getSessionLogFromPullRequest(pullRequest: PullRequestModel, sessionIndex = 0, completedOnly = true): Promise<IAPISessionLogs | undefined> {
const capi = await this.copilotApi;
if (!capi) {
return undefined;
}
const sessions = await capi.getAllSessions(pullRequest.id);
const session = sessions.filter(s => !completedOnly || s.state === 'completed').at(sessionIndex);
if (!session) {
return undefined;
}
const logs = await capi.getLogsFromSession(session.id);
// If session is in progress, try to fetch workflow steps to show setup progress
let setupSteps: SessionSetupStep[] | undefined;
if (session.state === 'in_progress' || logs.trim().length === 0) {
try {
// Get workflow steps instead of logs
setupSteps = await this.getWorkflowStepsFromAction(pullRequest);
} catch (error) {
// If we can't fetch workflow steps, don't fail the entire request
Logger.warn(`Failed to fetch workflow steps for session ${session.id}: ${error}`, CopilotRemoteAgentManager.ID);
}
}
return { info: session, logs, setupSteps };
}
async getSessionUrlFromPullRequest(pullRequest: PullRequestModel): Promise<string | undefined> {
const capi = await this.copilotApi;
if (!capi) {
return;
}
const sessions = await this.getLatestCodingAgentFromAction(pullRequest);
if (!sessions) {
return;
}
return sessions.html_url;
}
private getLatestRun<T extends { last_updated_at?: string; updated_at?: string }>(runs: T[]): T {
return runs
.slice()
.sort((a, b) => {
const dateA = new Date(a.last_updated_at ?? a.updated_at ?? 0).getTime();
const dateB = new Date(b.last_updated_at ?? b.updated_at ?? 0).getTime();
return dateB - dateA;
})[0];
}
get notificationsCount(): number {
return this._stateModel.notifications.size;
}
hasNotification(owner: string, repo: string, pullRequestNumber: number): boolean {
const key = this._stateModel.makeKey(owner, repo, pullRequestNumber);
return this._stateModel.notifications.has(key);
}
getStateForPR(owner: string, repo: string, prNumber: number): CopilotPRStatus {
return this._stateModel.get(owner, repo, prNumber);
}
getCounts(): { total: number; inProgress: number; error: number } {
return this._stateModel.getCounts();
}
public async provideNewChatSessionItem(options: { prompt?: string; history: ReadonlyArray<vscode.ChatRequestTurn | vscode.ChatResponseTurn>; metadata?: any; }, _token: vscode.CancellationToken): Promise<ChatSessionWithPR> {
const { prompt } = options;
if (!prompt) {
throw new Error(`Prompt is expected to provide a new chat session item`);
}
const result = await this.invokeRemoteAgent(
prompt,
prompt,
false,
);
if (result.state !== 'success') {
Logger.error(`Failed to provide new chat session item: ${result.error}`, CopilotRemoteAgentManager.ID);
throw new Error(`Failed to provide new chat session item: ${result.error}`);
}
const { number } = result;
const session = await this.findPullRequestById(number, true);
if (!session) {
throw new Error(`Failed to find session for pull request: ${number}`);
}
const timeline = await session.getCopilotTimelineEvents(session);
const status = copilotEventToSessionStatus(mostRecentCopilotEvent(timeline));
const tooltip = await issueMarkdown(session, this.context, this.repositoriesManager);
const timestampNumber = new Date(session.createdAt).getTime();
return {
id: `${session.number}`,
label: session.title || `Session ${session.number}`,
iconPath: this.getIconForSession(status),
pullRequest: session,
tooltip,
status,
timing: {
startTime: timestampNumber
}
};
}
public async provideChatSessions(token: vscode.CancellationToken): Promise<ChatSessionWithPR[]> {
try {
const capi = await this.copilotApi;
if (!capi) {
return [];
}
// Check if the token is already cancelled
if (token.isCancellationRequested) {
return [];
}
await this.waitRepoManagerInitialization();
const codingAgentPRs = this._stateModel.all;
return await Promise.all(codingAgentPRs.map(async prAndStatus => {
const timestampNumber = new Date(prAndStatus.item.createdAt).getTime();
const status = copilotPRStatusToSessionStatus(prAndStatus.status);
const pullRequest = prAndStatus.item;
const tooltip = await issueMarkdown(pullRequest, this.context, this.repositoriesManager);
return {
id: `${pullRequest.number}`,
label: pullRequest.title || `Session ${pullRequest.number}`,
iconPath: this.getIconForSession(status),
pullRequest: pullRequest,
tooltip,
status,
description: `PR #${pullRequest.number} • +300/-50`,
timing: {
startTime: timestampNumber
}
};
}));
} catch (error) {
Logger.error(`Failed to provide coding agents information: ${error}`, CopilotRemoteAgentManager.ID);
}
return [];
}
public async provideChatSessionContent(id: string, token: vscode.CancellationToken): Promise<vscode.ChatSession> {
try {
const capi = await this.copilotApi;
if (!capi || token.isCancellationRequested) {
return this.createEmptySession();
}
const pullRequestNumber = parseInt(id);
if (isNaN(pullRequestNumber)) {
Logger.error(`Invalid pull request number: ${id}`, CopilotRemoteAgentManager.ID);
return this.createEmptySession();
}
await this.waitRepoManagerInitialization();
const pullRequest = await this.findPullRequestById(pullRequestNumber, true);
if (!pullRequest) {
Logger.error(`Pull request not found: ${pullRequestNumber}`, CopilotRemoteAgentManager.ID);
return this.createEmptySession();
}
const sessions = await capi.getAllSessions(pullRequest.id);
if (!sessions || sessions.length === 0) {
Logger.warn(`No sessions found for pull request ${pullRequestNumber}`, CopilotRemoteAgentManager.ID);
return this.createEmptySession();
}
if (!Array.isArray(sessions)) {
Logger.error(`getAllSessions returned non-array: ${typeof sessions}`, CopilotRemoteAgentManager.ID);
return this.createEmptySession();
}
const contentBuilder = new ChatSessionContentBuilder(CopilotRemoteAgentManager.ID, COPILOT, () => this.getChangeModels(pullRequest));
const history = await contentBuilder.buildSessionHistory(sessions, pullRequest, capi);
const activeResponseCallback = this.findActiveResponseCallback(sessions, pullRequest);
const requestHandler = this.createRequestHandlerIfNeeded(pullRequest);
return {
history,
activeResponseCallback,
requestHandler
};
} catch (error) {
Logger.error(`Failed to provide chat session content: ${error}`, CopilotRemoteAgentManager.ID);
return this.createEmptySession();
}
}
private findActiveResponseCallback(
sessions: SessionInfo[],
pullRequest: PullRequestModel
): ((stream: vscode.ChatResponseStream, token: vscode.CancellationToken) => Thenable<void>) | undefined {
// Only the latest in-progress session gets activeResponseCallback
const inProgressSession = sessions
.slice()
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
.find(session => session.state === 'in_progress');
if (inProgressSession) {
return this.createActiveResponseCallback(pullRequest, inProgressSession.id);
}
return undefined;
}
private createRequestHandlerIfNeeded(pullRequest: PullRequestModel): vscode.ChatRequestHandler | undefined {
return (pullRequest.state === GithubItemStateEnum.Open)
? this.createRequestHandler(pullRequest)
: undefined;
}
private createEmptySession(): vscode.ChatSession {
return {
history: [],
requestHandler: undefined
};
}
private createActiveResponseCallback(pullRequest: PullRequestModel, sessionId: string): (stream: vscode.ChatResponseStream, token: vscode.CancellationToken) => Thenable<void> {
return async (stream: vscode.ChatResponseStream, token: vscode.CancellationToken) => {
// Use the shared streaming logic
return this.streamSessionLogs(stream, pullRequest, sessionId, token);
};
}
private async streamNewLogContent(pullRequest: PullRequestModel, stream: vscode.ChatResponseStream, newLogContent: string): Promise<{ hasStreamedContent: boolean; hasSetupStepProgress: boolean }> {
try {
if (!newLogContent.trim()) {
return { hasStreamedContent: false, hasSetupStepProgress: false };
}
// Parse the new log content
const logChunks = parseSessionLogs(newLogContent);
let hasStreamedContent = false;
let hasSetupStepProgress = false;
for (const chunk of logChunks) {
for (const choice of chunk.choices) {
const delta = choice.delta;
if (delta.role === 'assistant') {
// Handle special case for run_custom_setup_step
if (choice.finish_reason === 'tool_calls' && delta.tool_calls?.length && delta.tool_calls[0].function.name === 'run_custom_setup_step') {
const toolCall = delta.tool_calls[0];
let args: any = {};
try {
args = JSON.parse(toolCall.function.arguments);
} catch {
// fallback to empty args
}
if (delta.content && delta.content.trim()) {
// Finished setup step - create/update tool part
const toolPart = this.createToolInvocationPart(pullRequest, toolCall, args.name || delta.content);
if (toolPart) {
stream.push(toolPart);
hasStreamedContent = true;
}
} else {
// Running setup step - just track progress
hasSetupStepProgress = true;
Logger.appendLine(`Setup step in progress: ${args.name || 'Unknown step'}`, CopilotRemoteAgentManager.ID);
}
} else {
if (delta.content) {
if (!delta.content.startsWith('<pr_title>')) {
stream.markdown(delta.content);
hasStreamedContent = true;
}
}
if (delta.tool_calls) {
for (const toolCall of delta.tool_calls) {
const toolPart = this.createToolInvocationPart(pullRequest, toolCall, delta.content || '');
if (toolPart) {
stream.push(toolPart);
hasStreamedContent = true;
}
}
}
}
}
// Handle finish reasons
if (choice.finish_reason && choice.finish_reason !== 'null') {
Logger.appendLine(`Streaming finish_reason: ${choice.finish_reason}`, CopilotRemoteAgentManager.ID);
}
}
}
if (hasStreamedContent) {
Logger.appendLine(`Streamed content (markdown or tool parts), progress should be cleared`, CopilotRemoteAgentManager.ID);
} else if (hasSetupStepProgress) {
Logger.appendLine(`Setup step progress detected, keeping progress indicator`, CopilotRemoteAgentManager.ID);
} else {
Logger.appendLine(`No actual content streamed, progress may still be showing`, CopilotRemoteAgentManager.ID);
}
return { hasStreamedContent, hasSetupStepProgress };
} catch (error) {
Logger.error(`Error streaming new log content: ${error}`, CopilotRemoteAgentManager.ID);
return { hasStreamedContent: false, hasSetupStepProgress: false };
}
}
private async streamSessionLogs(stream: vscode.ChatResponseStream, pullRequest: PullRequestModel, sessionId: string, token: vscode.CancellationToken): Promise<void> {
const capi = await this.copilotApi;
if (!capi || token.isCancellationRequested) {
return;
}
let lastLogLength = 0;
let lastProcessedLength = 0;
let hasActiveProgress = false;
const pollingInterval = 3000; // 3 seconds
return new Promise<void>((resolve, reject) => {
let cancellationListener: vscode.Disposable | undefined;
let isCompleted = false;
const complete = async () => {
if (isCompleted) {
return;
}
isCompleted = true;
cancellationListener?.dispose();
await pullRequest.getFileChangesInfo();
const multiDiffPart = await this.getFileChangesMultiDiffPart(pullRequest);
if (multiDiffPart) {
stream.push(multiDiffPart);
}
resolve();
};
cancellationListener = token.onCancellationRequested(async () => {
if (isCompleted) {
return;
}