-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathCapiProxy.cs
More file actions
275 lines (232 loc) · 10.3 KB
/
Copy pathCapiProxy.cs
File metadata and controls
275 lines (232 loc) · 10.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Json;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace GitHub.Copilot.Test.Harness;
public sealed partial class CapiProxy : IAsyncDisposable
{
private Process? _process;
private Task<string>? _startupTask;
public string? ConnectProxyUrl { get; private set; }
public string? CaFilePath { get; private set; }
public Task<string> StartAsync()
{
return _startupTask ??= StartCoreAsync();
async Task<string> StartCoreAsync()
{
string filename;
string args;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
filename = "cmd.exe";
args = "/c npm.cmd run start";
}
else
{
filename = "npm";
args = "run start";
}
var startInfo = new ProcessStartInfo
{
FileName = filename,
WorkingDirectory = Path.Join(FindRepoRoot(), "test", "harness"),
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
_process = new Process { StartInfo = startInfo };
var tcs = new TaskCompletionSource<string>();
var errorOutput = new StringBuilder();
_process.OutputDataReceived += (_, e) =>
{
if (e.Data == null) return;
var match = Regex.Match(e.Data, @"Listening: (?<url>http://[^\s]+)\s+(?<metadata>\{.*\})$");
if (!match.Success)
{
if (e.Data.Contains("Listening: ", StringComparison.Ordinal))
{
tcs.TrySetException(
new InvalidOperationException(
$"Proxy startup line missing CONNECT proxy metadata: {e.Data}"));
}
return;
}
try
{
var metadata = JsonSerializer.Deserialize(
match.Groups["metadata"].Value,
CapiProxyJsonContext.Default.ProxyStartupMetadata);
ConnectProxyUrl = metadata?.ConnectProxyUrl;
CaFilePath = metadata?.CaFilePath;
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
{
tcs.TrySetException(
new InvalidOperationException(
$"Failed to parse proxy startup metadata: {match.Groups["metadata"].Value}",
ex));
return;
}
if (string.IsNullOrEmpty(ConnectProxyUrl) || string.IsNullOrEmpty(CaFilePath))
{
tcs.TrySetException(
new InvalidOperationException(
$"Proxy startup metadata missing CONNECT proxy details: {e.Data}"));
return;
}
tcs.TrySetResult(match.Groups["url"].Value);
};
_process.ErrorDataReceived += (_, e) =>
{
if (e.Data == null) return;
errorOutput.AppendLine(e.Data);
Console.Error.WriteLine(e.Data);
};
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
_ = _process.WaitForExitAsync().ContinueWith(_ =>
{
if (_process?.ExitCode is int exitCode && exitCode != 0)
{
tcs.TrySetException(new Exception($"Proxy exited with code {_process.ExitCode}: {errorOutput}"));
}
});
// Use longer timeout on Windows due to slower process startup
var timeoutSeconds = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 30 : 10;
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
cts.Token.Register(() => tcs.TrySetException(new TimeoutException("Timeout waiting for proxy")));
return await tcs.Task;
}
}
public async Task StopAsync(bool skipWritingCache = false)
{
if (_startupTask != null)
{
try
{
var url = await _startupTask;
var stopUrl = skipWritingCache ? $"{url}/stop?skipWritingCache=true" : $"{url}/stop";
using var client = new HttpClient();
await client.PostAsync(stopUrl, null);
}
catch { /* Best effort */ }
}
if (_process is { HasExited: false })
{
try { _process.Kill(entireProcessTree: true); await _process.WaitForExitAsync(); }
catch { /* Ignore */ }
}
_process?.Dispose();
_process = null;
_startupTask = null;
}
public async Task ConfigureAsync(string filePath, string workDir)
{
var url = await (_startupTask ?? throw new InvalidOperationException("Proxy not started"));
using var client = new HttpClient();
var response = await client.PostAsJsonAsync($"{url}/config", new ConfigureRequest(filePath, workDir), CapiProxyJsonContext.Default.ConfigureRequest);
response.EnsureSuccessStatusCode();
}
private record ConfigureRequest(string FilePath, string WorkDir);
private record ProxyStartupMetadata(string? ConnectProxyUrl, string? CaFilePath);
public async Task<List<ParsedHttpExchange>> GetExchangesAsync()
{
var url = await (_startupTask ?? throw new InvalidOperationException("Proxy not started"));
using var client = new HttpClient();
return await client.GetFromJsonAsync($"{url}/exchanges", CapiProxyJsonContext.Default.ListParsedHttpExchange)
?? [];
}
public async Task SetCopilotUserByTokenAsync(string token, CopilotUserConfig response)
{
var url = await (_startupTask ?? throw new InvalidOperationException("Proxy not started"));
using var client = new HttpClient();
var payload = new CopilotUserByTokenRequest(token, response);
var resp = await client.PostAsJsonAsync($"{url}/copilot-user-config", payload, CapiProxyJsonContext.Default.CopilotUserByTokenRequest);
resp.EnsureSuccessStatusCode();
}
public async ValueTask DisposeAsync()
{
await StopAsync();
}
private static string FindRepoRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null)
{
if (File.Exists(Path.Combine(dir.FullName, "justfile")))
return dir.FullName;
dir = dir.Parent;
}
throw new InvalidOperationException("Could not find repository root");
}
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(ConfigureRequest))]
[JsonSerializable(typeof(List<ParsedHttpExchange>))]
[JsonSerializable(typeof(CopilotUserByTokenRequest))]
[JsonSerializable(typeof(Dictionary<string, CopilotUserQuotaSnapshot>))]
[JsonSerializable(typeof(ProxyStartupMetadata))]
private partial class CapiProxyJsonContext : JsonSerializerContext;
}
public record CopilotUserByTokenRequest(string Token, CopilotUserConfig Response);
public record CopilotUserConfig(
string Login,
[property: JsonPropertyName("copilot_plan")]
string CopilotPlan,
CopilotUserEndpoints Endpoints,
[property: JsonPropertyName("analytics_tracking_id")]
string AnalyticsTrackingId,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[property: JsonPropertyName("quota_snapshots")]
IReadOnlyDictionary<string, CopilotUserQuotaSnapshot>? QuotaSnapshots = null);
public record CopilotUserEndpoints(string Api, string Telemetry);
public record CopilotUserQuotaSnapshot(
[property: JsonPropertyName("entitlement")]
int Entitlement,
[property: JsonPropertyName("overage_count")]
int OverageCount,
[property: JsonPropertyName("overage_permitted")]
bool OveragePermitted,
[property: JsonPropertyName("percent_remaining")]
double PercentRemaining,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[property: JsonPropertyName("timestamp_utc")]
string? TimestampUtc = null,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[property: JsonPropertyName("unlimited")]
bool? Unlimited = null);
public record ParsedHttpExchange(
ChatCompletionRequest Request,
ChatCompletionResponse? Response,
Dictionary<string, JsonElement>? RequestHeaders);
public record ChatCompletionRequest(
string Model,
List<ChatCompletionMessage> Messages,
List<ChatCompletionTool>? Tools);
public record ChatCompletionMessage(
string Role,
JsonElement? Content,
[property: JsonPropertyName("tool_call_id")] string? ToolCallId,
[property: JsonPropertyName("tool_calls")] List<ChatCompletionToolCall>? ToolCalls)
{
/// <summary>
/// Returns Content as a string when the JSON value is a string, or null otherwise.
/// </summary>
[JsonIgnore]
public string? StringContent => Content is { ValueKind: JsonValueKind.String } c ? c.GetString() : null;
}
public record ChatCompletionToolCall(string Id, string Type, ChatCompletionToolCallFunction Function);
public record ChatCompletionToolCallFunction(string Name, string? Arguments);
public record ChatCompletionTool(string Type, ChatCompletionToolFunction Function);
public record ChatCompletionToolFunction(string Name, string? Description, JsonElement? Parameters);
public record ChatCompletionResponse(string Id, string Model, List<ChatCompletionChoice> Choices);
public record ChatCompletionChoice(int Index, ChatCompletionMessage Message, [property: JsonPropertyName("finish_reason")] string FinishReason);