forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilotApi.ts
More file actions
346 lines (317 loc) · 10.5 KB
/
Copy pathcopilotApi.ts
File metadata and controls
346 lines (317 loc) · 10.5 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import fetch from 'cross-fetch';
import JSZip from 'jszip';
import * as vscode from 'vscode';
import { AuthProvider } from '../common/authentication';
import { COPILOT_SWE_AGENT } from '../common/copilot';
import Logger from '../common/logger';
import { ITelemetry } from '../common/telemetry';
import { CredentialStore, GitHub } from './credentials';
import { PRType } from './interface';
import { LoggingOctokit } from './loggingOctokit';
import { PullRequestModel } from './pullRequestModel';
import { RepositoriesManager } from './repositoriesManager';
import { hasEnterpriseUri } from './utils';
const LEARN_MORE_URL = 'https://aka.ms/coding-agent-docs';
const PREMIUM_REQUESTS_URL = 'https://docs.github.com/en/copilot/concepts/copilot-billing/understanding-and-managing-requests-in-copilot#what-are-premium-requests';
export interface RemoteAgentJobPayload {
problem_statement: string;
event_type: string;
pull_request?: {
title?: string;
body_placeholder?: string;
body_suffix?: string;
base_ref?: string;
head_ref?: string;
};
run_name?: string;
}
export interface RemoteAgentJobResponse {
pull_request: {
html_url: string;
number: number;
}
}
export interface ChatSessionWithPR extends vscode.ChatSessionItem {
pullRequest: PullRequestModel;
}
export class CopilotApi {
protected static readonly ID = 'copilotApi';
constructor(
private octokit: LoggingOctokit,
private token: string,
private credentialStore: CredentialStore,
private telemetry: ITelemetry
) { }
private get baseUrl(): string {
return 'https://api.githubcopilot.com';
}
async postRemoteAgentJob(
owner: string,
name: string,
payload: RemoteAgentJobPayload,
): Promise<RemoteAgentJobResponse> {
const repoSlug = `${owner}/${name}`;
const apiUrl = `${this.baseUrl}/agents/swe/v0/jobs/${repoSlug}`;
let status: number | undefined;
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Copilot-Integration-Id': 'copilot-developer-dev',
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(payload)
});
status = response.status;
if (!response.ok) {
throw new Error(await this.formatRemoteAgentJobError(status, repoSlug, response));
}
const data = await response.json();
this.validateRemoteAgentJobResponse(data);
/*
__GDPR__
"remoteAgent.postRemoteAgentJob" : {
"status" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryEvent('remoteAgent.postRemoteAgentJob', {
status: status.toString(),
});
return data;
} catch (error) {
/* __GDPR__
"remoteAgent.postRemoteAgentJob" : {
"status" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetry.sendTelemetryErrorEvent('remoteAgent.postRemoteAgentJob', {
status: status?.toString() || '999',
});
throw error;
}
}
// https://github.com/github/sweagentd/blob/371ea6db280b9aecf790ccc20660e39a7ecb8d1c/internal/api/jobapi/handler.go#L110-L120
private async formatRemoteAgentJobError(status: number, repoSlug: string, response: Response): Promise<string> {
Logger.error(`Error in remote agent job: ${await response.text()}`, CopilotApi.ID);
switch (status) {
case 400:
return vscode.l10n.t('Bad request');
case 401:
return vscode.l10n.t('Unauthorized');
case 402:
return vscode.l10n.t('[Premium request]({0}) quota exceeded', PREMIUM_REQUESTS_URL);
case 403:
return vscode.l10n.t('[GitHub coding agent]({0}) is not enabled for repository \'{1}\'', LEARN_MORE_URL, repoSlug);
case 404:
return vscode.l10n.t('Repository \'{0}\' not found', repoSlug);
case 409:
return vscode.l10n.t('A coding agent pull request already exists');
case 500:
return vscode.l10n.t('Server error. Please see logs for details.');
default:
return vscode.l10n.t('Error: {0}. Please see logs for details', status);
}
}
private validateRemoteAgentJobResponse(data: any): asserts data is RemoteAgentJobResponse {
if (!data || typeof data !== 'object') {
throw new Error('Invalid response from coding agent');
}
if (!data.pull_request || typeof data.pull_request !== 'object') {
throw new Error('Invalid pull_request in response');
}
if (typeof data.pull_request.html_url !== 'string') {
throw new Error('Invalid pull_request.html_url in response');
}
if (typeof data.pull_request.number !== 'number') {
throw new Error('Invalid pull_request.number in response');
}
}
public async getLogsFromZipUrl(logsUrl: string): Promise<string[]> {
const logsZip = await fetch(logsUrl, {
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/json',
},
});
if (!logsZip.ok) {
throw new Error(`Failed to fetch logs zip: ${logsZip.statusText}`);
}
const logsText = await logsZip.arrayBuffer();
const copilotSteps: string[] = [];
const zip = await JSZip.loadAsync(logsText);
for (const fileName of Object.keys(zip.files)) {
const file = zip.files[fileName];
if (!file.dir && fileName.endsWith('Processing Request.txt')) {
const content = await file.async('string');
copilotSteps.push(...content.split('\n'));
}
}
return copilotSteps;
}
public async getAllSessions(pullRequestId: number | undefined): Promise<SessionInfo[]> {
const response = await fetch(
pullRequestId
? `https://api.githubcopilot.com/agents/sessions/resource/pull/${pullRequestId}`
: 'https://api.githubcopilot.com/agents/sessions',
{
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/json',
},
});
if (!response.ok) {
throw new Error(`Failed to fetch sessions: ${response.statusText}`);
}
const sessions = await response.json();
return sessions.sessions;
}
public async getAllCodingAgentPRs(repositoriesManager: RepositoriesManager): Promise<PullRequestModel[]> {
const hub = this.getHub();
const username = (await hub?.currentUser)?.login;
if (!username) {
Logger.error('Failed to get GitHub username from auth provider', CopilotApi.ID);
return [];
}
const query = `is:open author:${COPILOT_SWE_AGENT}[bot] assignee:${username} is:pr repo:\${owner}/\${repository}`;
const allItems = await Promise.all(
repositoriesManager.folderManagers.map(async fm => {
const result = await fm.getPullRequests(PRType.Query, undefined, query);
return result.items;
})
);
return allItems.flat();
}
public async getSessionInfo(sessionId: string): Promise<SessionInfo> {
const response = await fetch(`https://api.githubcopilot.com/agents/sessions/${sessionId}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${this.token}`,
'Accept': 'application/json'
}
});
if (!response.ok) {
throw new Error(`Failed to fetch session: ${response.statusText}`);
}
return (await response.json()) as SessionInfo;
}
public async getLogsFromSession(sessionId: string): Promise<string> {
const logsResponse = await fetch(`https://api.githubcopilot.com/agents/sessions/${sessionId}/logs`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
},
});
if (!logsResponse.ok) {
throw new Error(`Failed to fetch logs: ${logsResponse.statusText}`);
}
return await logsResponse.text();
}
public async getJobBySessionId(owner: string, repo: string, sessionId: string): Promise<JobInfo | undefined> {
try {
const response = await fetch(`${this.baseUrl}/agents/swe/v0/jobs/${owner}/${repo}/session/${sessionId}`, {
method: 'GET',
headers: {
'Copilot-Integration-Id': 'copilot-developer-dev',
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (!response.ok) {
Logger.warn(`Failed to fetch job info for session ${sessionId}: ${response.statusText}`, CopilotApi.ID);
return undefined;
}
const data = await response.json() as JobInfo;
return data;
} catch (error) {
Logger.warn(`Error fetching job info for session ${sessionId}: ${error}`, CopilotApi.ID);
return undefined;
}
}
private getHub(): GitHub | undefined {
let authProvider: AuthProvider | undefined;
if (this.credentialStore.isAuthenticated(AuthProvider.githubEnterprise) && hasEnterpriseUri()) {
authProvider = AuthProvider.githubEnterprise;
} else if (this.credentialStore.isAuthenticated(AuthProvider.github)) {
authProvider = AuthProvider.github;
} else {
return;
}
return this.credentialStore.getHub(authProvider);
}
}
export interface SessionInfo {
id: string;
name: string;
user_id: number;
agent_id: number;
logs: string;
logs_blob_id: string;
state: 'completed' | 'in_progress' | 'failed' | (string & {});
owner_id: number;
repo_id: number;
resource_type: string;
resource_id: number;
last_updated_at: string;
created_at: string;
completed_at: string;
event_type: string;
workflow_run_id: number;
premium_requests: number;
error: string | null;
}
export interface SessionSetupStep {
name: string;
status: 'completed' | 'in_progress' | 'queued';
}
export interface JobInfo {
job_id: string;
session_id: string;
problem_statement: string;
content_filter_mode?: string;
status: string;
result?: string;
actor: {
id: number;
login: string;
};
created_at: string;
updated_at: string;
pull_request: {
id: number;
number: number;
};
workflow_run?: {
id: number;
};
error?: {
message: string;
};
event_type?: string;
event_url?: string;
event_identifiers?: string[];
}
export async function getCopilotApi(credentialStore: CredentialStore, telemetry: ITelemetry, authProvider?: AuthProvider): Promise<CopilotApi | undefined> {
if (!authProvider) {
if (credentialStore.isAuthenticated(AuthProvider.githubEnterprise) && hasEnterpriseUri()) {
authProvider = AuthProvider.githubEnterprise;
} else if (credentialStore.isAuthenticated(AuthProvider.github)) {
authProvider = AuthProvider.github;
} else {
return;
}
}
const github = credentialStore.getHub(authProvider);
if (!github || !github.octokit) {
return;
}
const { token } = await github.octokit.api.auth() as { token: string };
return new CopilotApi(github.octokit, token, credentialStore, telemetry);
}