-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathCopilotRequestHandler.cs
More file actions
1055 lines (903 loc) · 37.2 KB
/
Copy pathCopilotRequestHandler.cs
File metadata and controls
1055 lines (903 loc) · 37.2 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.
*--------------------------------------------------------------------------------------------*/
using GitHub.Copilot.Rpc;
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Net.WebSockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Channels;
namespace GitHub.Copilot;
/// <summary>
/// Transport the runtime would otherwise use to issue an intercepted
/// model-layer request.
/// </summary>
[Experimental(Diagnostics.Experimental)]
public enum CopilotRequestTransport
{
/// <summary>
/// Plain HTTP or a streamed SSE response. Each body chunk is an opaque
/// byte range.
/// </summary>
Http,
/// <summary>
/// Full-duplex WebSocket channel. Each request-body chunk is one inbound
/// WebSocket message and each response-body write is one outbound message.
/// </summary>
WebSocket,
}
/// <summary>
/// Per-request context handed to every <see cref="CopilotRequestHandler"/> hook.
/// Exposes the routing and cancellation details of a single intercepted request
/// so overrides can observe or rewrite it.
/// </summary>
[Experimental(Diagnostics.Experimental)]
public sealed class CopilotRequestContext
{
/// <summary>
/// Creates an instance of <see cref="CopilotRequestContext"/> by copying the values from another instance.
/// </summary>
/// <param name="original">A <see cref="CopilotRequestContext"/> instance to copy values from.</param>
public CopilotRequestContext(CopilotRequestContext original)
: this(original.RequestId, original.Url, original.Headers)
{
SessionId = original.SessionId;
Transport = original.Transport;
CancellationToken = original.CancellationToken;
WebSocketResponse = original.WebSocketResponse;
}
internal CopilotRequestContext(string requestId, string url, IReadOnlyDictionary<string, IReadOnlyList<string>> headers)
{
RequestId = requestId;
Url = url;
Headers = headers;
}
/// <summary>Opaque runtime-minted id, stable across the request lifecycle.</summary>
public string RequestId { get; init; }
/// <summary>Runtime session id that triggered the request, if any.</summary>
public string? SessionId { get; init; }
/// <summary>Transport the runtime would otherwise use.</summary>
public CopilotRequestTransport Transport { get; init; }
/// <summary>Request URL.</summary>
public string Url { get; init; }
/// <summary>Request headers.</summary>
public IReadOnlyDictionary<string, IReadOnlyList<string>> Headers { get; init; }
/// <summary>
/// Cancelled when the runtime aborts this in-flight request. Subclasses that
/// issue their own I/O should pass this through so the upstream call is torn
/// down too.
/// </summary>
public CancellationToken CancellationToken { get; init; }
internal LlmWebSocketResponseBridge? WebSocketResponse { get; set; }
}
/// <summary>A single WebSocket message exchanged through a <see cref="CopilotRequestHandler"/> hook.</summary>
[Experimental(Diagnostics.Experimental)]
public readonly struct CopilotWebSocketMessage(ReadOnlyMemory<byte> data, bool isBinary)
{
/// <summary>The message payload bytes.</summary>
public ReadOnlyMemory<byte> Data { get; } = data;
/// <summary>True for a binary frame; false for a UTF-8 text frame.</summary>
public bool IsBinary { get; } = isBinary;
/// <summary>Decodes the payload as UTF-8 text.</summary>
public string GetText() => Encoding.UTF8.GetString(Data.Span);
/// <summary>Creates a text message from a UTF-8 string.</summary>
public static CopilotWebSocketMessage FromText(string text) => new(Encoding.UTF8.GetBytes(text), isBinary: false);
}
/// <summary>
/// Terminal status for a callback-owned WebSocket connection.
/// </summary>
[Experimental(Diagnostics.Experimental)]
public sealed class CopilotWebSocketCloseStatus
{
/// <summary>The close description, if any.</summary>
public string? Description { get; init; }
/// <summary>
/// Optional error code surfaced to the runtime when the close is a failure
/// rather than a clean end-of-stream.
/// </summary>
public string? ErrorCode { get; init; }
/// <summary>The error that terminated the connection, if any.</summary>
public Exception? Error { get; init; }
/// <summary>Shared normal-closure instance.</summary>
public static CopilotWebSocketCloseStatus NormalClosure { get; } = new();
}
/// <summary>
/// Lower-level WebSocket handler with no upstream connection. This is the
/// abstract base shared by all WebSocket handlers; it does not open or forward
/// to any upstream server on its own. Subclass it directly only to service a
/// fully synthetic connection yourself. For the common case of mutating and
/// forwarding traffic to the real upstream, subclass
/// <see cref="CopilotWebSocketForwarder"/> instead, which connects upstream and
/// forwards by default.
/// </summary>
[Experimental(Diagnostics.Experimental)]
public abstract class CopilotWebSocketHandler : IAsyncDisposable
{
private readonly TaskCompletionSource<CopilotWebSocketCloseStatus> _completion =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _closed;
private bool _suppressCloseOnDispose;
/// <summary>Request context for this WebSocket connection.</summary>
protected CopilotRequestContext Context { get; }
internal Task<CopilotWebSocketCloseStatus> Completion => _completion.Task;
/// <summary>
/// Initializes a per-connection handler for the supplied request context.
/// </summary>
protected CopilotWebSocketHandler(CopilotRequestContext context)
{
Context = context;
_ = context.WebSocketResponse ?? throw new InvalidOperationException("WebSocket response bridge is not attached.");
}
/// <summary>
/// Send a message from the runtime to the upstream connection.
/// </summary>
public abstract Task SendRequestMessageAsync(CopilotWebSocketMessage message);
/// <summary>
/// Send a message from the upstream connection back to the runtime.
/// Override to mutate or duplicate messages; call <c>base</c> to emit.
/// </summary>
public virtual Task SendResponseMessageAsync(CopilotWebSocketMessage message) =>
Context.WebSocketResponse!.WriteAsync(message);
/// <summary>
/// Close the connection and finalise the runtime-facing response.
/// </summary>
public virtual async Task CloseAsync(CopilotWebSocketCloseStatus status)
{
if (Interlocked.Exchange(ref _closed, 1) != 0)
{
return;
}
if (status.Error is not null)
{
await Context.WebSocketResponse!
.ErrorAsync(status.Description ?? status.Error.Message, status.ErrorCode)
.ConfigureAwait(false);
}
else
{
await Context.WebSocketResponse!.EndAsync().ConfigureAwait(false);
}
_completion.TrySetResult(status);
}
internal void SuppressCloseOnDispose() => _suppressCloseOnDispose = true;
internal virtual Task OpenAsync() => Task.CompletedTask;
/// <inheritdoc />
public virtual async ValueTask DisposeAsync()
{
GC.SuppressFinalize(this);
if (!_suppressCloseOnDispose && Volatile.Read(ref _closed) == 0)
{
await CloseAsync(CopilotWebSocketCloseStatus.NormalClosure).ConfigureAwait(false);
}
}
}
/// <summary>
/// WebSocket handler that connects to the real upstream and forwards traffic by
/// default. This is the type returned by the default
/// <see cref="CopilotRequestHandler.OpenWebSocketAsync"/>. Override nothing to
/// get full pass-through. To mutate traffic, subclass this type and override a
/// send method, then call the base implementation to keep forwarding upstream.
/// (Subclassing <see cref="CopilotWebSocketHandler"/> instead would drop
/// forwarding entirely.)
/// </summary>
[Experimental(Diagnostics.Experimental)]
public class CopilotWebSocketForwarder : CopilotWebSocketHandler
{
private WebSocket? _upstream;
private CancellationTokenSource? _pumpCts;
private Task? _responsePump;
/// <summary>
/// Initializes a forwarding handler that will open the upstream socket on
/// demand using the supplied URL/headers from <paramref name="context"/>.
/// </summary>
public CopilotWebSocketForwarder(CopilotRequestContext context)
: base(context)
{
}
/// <summary>
/// Opens the upstream socket and starts the built-in response pump.
/// </summary>
internal override async Task OpenAsync()
{
if (_upstream is not null)
{
return;
}
var socket = new ClientWebSocket();
foreach (var (name, values) in Context.Headers)
{
if (LlmInferenceHeaders.Forbidden.Contains(name))
{
continue;
}
try
{
socket.Options.SetRequestHeader(name, string.Join(", ", values));
}
catch
{
// Some headers are managed by the handshake; ignore rejections.
}
}
await socket.ConnectAsync(ToWebSocketUri(Context.Url), Context.CancellationToken).ConfigureAwait(false);
_upstream = socket;
_pumpCts = CancellationTokenSource.CreateLinkedTokenSource(Context.CancellationToken);
// Start the pump without a cancellation token on Task.Run itself: if the
// linked token is already cancelled, we still want PumpResponsesAsync to
// run so its cleanup (closing the upstream and finalising the response)
// executes rather than the task being cancelled before it ever starts.
_responsePump = Task.Run(() => PumpResponsesAsync(_pumpCts.Token));
}
/// <summary>
/// Sends a message from the runtime to the upstream connection. Subclasses may override to mutate messages.
/// </summary>
/// <param name="message">The message to send.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public override Task SendRequestMessageAsync(CopilotWebSocketMessage message)
{
if (_upstream?.State != WebSocketState.Open)
{
return Task.CompletedTask;
}
var type = message.IsBinary ? WebSocketMessageType.Binary : WebSocketMessageType.Text;
return _upstream.SendAsync(
message.Data,
type,
endOfMessage: true,
Context.CancellationToken).AsTask();
}
/// <inheritdoc />
public override async Task CloseAsync(CopilotWebSocketCloseStatus status)
{
_pumpCts?.Cancel();
if (_upstream is not null)
{
await CloseWebSocketQuietlyAsync(_upstream).ConfigureAwait(false);
}
await base.CloseAsync(status).ConfigureAwait(false);
}
/// <inheritdoc />
public override async ValueTask DisposeAsync()
{
GC.SuppressFinalize(this);
try
{
await base.DisposeAsync().ConfigureAwait(false);
}
finally
{
_pumpCts?.Cancel();
_pumpCts?.Dispose();
_upstream?.Dispose();
if (_responsePump is not null)
{
await ObserveQuietlyAsync(_responsePump).ConfigureAwait(false);
}
}
}
private async Task PumpResponsesAsync(CancellationToken cancellationToken)
{
if (_upstream is null)
{
return;
}
try
{
while (_upstream.State == WebSocketState.Open)
{
var message = await ReceiveMessageAsync(_upstream, cancellationToken).ConfigureAwait(false);
if (message is null)
{
break;
}
await SendResponseMessageAsync(message.Value).ConfigureAwait(false);
}
await CloseAsync(CopilotWebSocketCloseStatus.NormalClosure).ConfigureAwait(false);
}
catch (OperationCanceledException) when (Context.CancellationToken.IsCancellationRequested)
{
// Runtime-side cancellation aborts the request pump; the outer
// handler rethrows that cancellation rather than finalising here.
}
catch (Exception ex)
{
await CloseAsync(new CopilotWebSocketCloseStatus
{
Description = ex.Message,
Error = ex,
}).ConfigureAwait(false);
}
}
private static async Task<CopilotWebSocketMessage?> ReceiveMessageAsync(WebSocket socket, CancellationToken cancellationToken)
{
var buffer = ArrayPool<byte>.Shared.Rent(16 * 1024);
try
{
using var assembled = new MemoryStream();
ValueWebSocketReceiveResult result;
do
{
try
{
result = await socket.ReceiveAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return null;
}
catch (WebSocketException)
{
return null;
}
if (result.MessageType == WebSocketMessageType.Close)
{
return null;
}
assembled.Write(buffer, 0, result.Count);
}
while (!result.EndOfMessage);
return new CopilotWebSocketMessage(assembled.ToArray(), result.MessageType == WebSocketMessageType.Binary);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private static async Task CloseWebSocketQuietlyAsync(WebSocket socket)
{
try
{
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, statusDescription: null, CancellationToken.None).ConfigureAwait(false);
}
}
catch
{
// Best-effort; the socket may already be closed.
}
}
[SuppressMessage("Usage", "CA1031:Do not catch general exception types", Justification = "Best-effort teardown of the losing pump.")]
private static async Task ObserveQuietlyAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch
{
// Best-effort teardown only.
}
}
private static Uri ToWebSocketUri(string url)
{
var builder = new UriBuilder(url);
if (builder.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
{
builder.Scheme = "wss";
}
else if (builder.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
{
builder.Scheme = "ws";
}
return builder.Uri;
}
}
/// <summary>
/// Base class for SDK consumers who want to observe or mutate the LLM inference
/// requests the runtime issues (for both CAPI and BYOK providers). Subclass and
/// override <see cref="SendRequestAsync"/> or <see cref="OpenWebSocketAsync"/>.
/// </summary>
[Experimental(Diagnostics.Experimental)]
public class CopilotRequestHandler
{
private static readonly HttpClient s_sharedHttpClient = new();
private readonly HttpClient _httpClient;
/// <summary>
/// Initializes a new instance that issues upstream requests using a shared
/// process-wide <see cref="HttpClient"/>.
/// </summary>
public CopilotRequestHandler()
: this(null)
{
}
/// <summary>
/// Initializes a new instance that issues upstream requests using the supplied
/// <see cref="HttpClient"/>, or a shared process-wide instance when <paramref name="httpClient"/> is <see langword="null"/>.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> to use, or <see langword="null"/> to use the shared instance.</param>
public CopilotRequestHandler(HttpClient? httpClient)
{
_httpClient = httpClient ?? s_sharedHttpClient;
}
/// <summary>
/// Issue the upstream HTTP request. Override to mutate the request before
/// calling <c>base</c>, mutate the returned response after, or replace the
/// call entirely.
/// </summary>
protected virtual Task<HttpResponseMessage> SendRequestAsync(HttpRequestMessage request, CopilotRequestContext ctx) =>
_httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ctx.CancellationToken);
/// <summary>
/// Open the upstream WebSocket connection. Override to return a custom
/// <see cref="CopilotWebSocketHandler"/> or to construct a
/// <see cref="CopilotWebSocketForwarder"/> against a rewritten URL.
/// </summary>
protected virtual Task<CopilotWebSocketHandler> OpenWebSocketAsync(CopilotRequestContext ctx) =>
Task.FromResult<CopilotWebSocketHandler>(new CopilotWebSocketForwarder(ctx));
/// <summary>
/// Entry point invoked by the adapter once per intercepted request. Routes to
/// the HTTP or WebSocket flow and drives the consumer's overridable hooks.
/// </summary>
internal Task HandleAsync(LlmInferenceExchange exchange) =>
exchange.Context.Transport == CopilotRequestTransport.WebSocket
? HandleWebSocketAsync(exchange)
: HandleHttpAsync(exchange);
private async Task HandleHttpAsync(LlmInferenceExchange exchange)
{
using var request = await BuildHttpRequestAsync(exchange).ConfigureAwait(false);
using var response = await SendRequestAsync(request, exchange.Context).ConfigureAwait(false);
await StreamResponseAsync(response, exchange).ConfigureAwait(false);
}
private static async Task<HttpRequestMessage> BuildHttpRequestAsync(LlmInferenceExchange exchange)
{
var method = new HttpMethod(exchange.Method);
var message = new HttpRequestMessage(method, exchange.Context.Url);
var hasBody = method != HttpMethod.Get && method != HttpMethod.Head;
var body = await DrainAsync(exchange.RequestBody).ConfigureAwait(false);
if (hasBody && body.Length > 0)
{
message.Content = new ByteArrayContent(body);
}
foreach (var (name, values) in exchange.Context.Headers)
{
if (LlmInferenceHeaders.Forbidden.Contains(name))
{
continue;
}
if (!message.Headers.TryAddWithoutValidation(name, values))
{
message.Content ??= new ByteArrayContent([]);
message.Content.Headers.TryAddWithoutValidation(name, values);
}
}
return message;
}
private static async Task StreamResponseAsync(HttpResponseMessage response, LlmInferenceExchange exchange)
{
await exchange.StartResponseAsync(
(int)response.StatusCode,
response.ReasonPhrase,
HeadersToMultiMap(response)).ConfigureAwait(false);
var ct = exchange.Context.CancellationToken;
using var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
var buffer = new byte[16 * 1024];
int read;
while ((read = await stream.ReadAsync(buffer.AsMemory(), ct).ConfigureAwait(false)) > 0)
{
await exchange.WriteResponseAsync(new ReadOnlyMemory<byte>(buffer, 0, read)).ConfigureAwait(false);
}
await exchange.EndResponseAsync().ConfigureAwait(false);
}
private async Task HandleWebSocketAsync(LlmInferenceExchange exchange)
{
var ctx = exchange.Context;
var bridge = new LlmWebSocketResponseBridge(exchange);
ctx.WebSocketResponse = bridge;
var handler = await OpenWebSocketAsync(ctx).ConfigureAwait(false);
try
{
await handler.OpenAsync().ConfigureAwait(false);
// The runtime blocks the WebSocket connect until it receives the
// 101 response head (the upgrade acknowledgement) and only then
// begins forwarding inbound messages as request-body chunks. Emit
// it eagerly here — waiting for the first upstream message would
// deadlock, since the upstream stays silent until it receives a
// request message the runtime won't send before the upgrade
// completes.
await bridge.StartAsync().ConfigureAwait(false);
var clientPump = Task.Run(async () =>
{
await foreach (var chunk in exchange.RequestBody.WithCancellation(ctx.CancellationToken).ConfigureAwait(false))
{
await handler.SendRequestMessageAsync(new CopilotWebSocketMessage(chunk, isBinary: false)).ConfigureAwait(false);
}
}, ctx.CancellationToken);
var first = await Task.WhenAny(clientPump, handler.Completion).ConfigureAwait(false);
if (first == clientPump)
{
if (clientPump.IsFaulted || clientPump.IsCanceled)
{
handler.SuppressCloseOnDispose();
await clientPump.ConfigureAwait(false);
}
await handler.CloseAsync(CopilotWebSocketCloseStatus.NormalClosure).ConfigureAwait(false);
await handler.Completion.ConfigureAwait(false);
return;
}
var closeStatus = await handler.Completion.ConfigureAwait(false);
if (closeStatus.Error is not null)
{
throw closeStatus.Error;
}
}
finally
{
await handler.DisposeAsync().ConfigureAwait(false);
}
}
private static async Task<byte[]> DrainAsync(IAsyncEnumerable<ReadOnlyMemory<byte>> stream)
{
using var buffer = new MemoryStream();
await foreach (var chunk in stream.ConfigureAwait(false))
{
if (chunk.Length > 0)
{
buffer.Write(chunk.Span);
}
}
return buffer.ToArray();
}
private static Dictionary<string, IReadOnlyList<string>> HeadersToMultiMap(HttpResponseMessage response)
{
var result = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase);
foreach (var header in response.Headers)
{
result[header.Key] = [.. header.Value];
}
if (response.Content is not null)
{
foreach (var header in response.Content.Headers)
{
result[header.Key] = [.. header.Value];
}
}
return result;
}
}
/// <summary>
/// One intercepted request in flight. Carries the request context plus the body
/// byte stream the runtime feeds in via <c>httpRequestChunk</c> frames, and
/// emits the consumer's response straight back to the runtime through the
/// generated <c>llmInference</c> server API. Replaces the former
/// provider/sink/response-channel indirection with a single object the adapter
/// owns and the handler writes to.
/// </summary>
internal sealed class LlmInferenceExchange
{
private readonly Func<ServerRpc?> _getServerRpc;
private readonly Channel<BodyItem> _body = Channel.CreateUnbounded<BodyItem>(
new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });
private bool _started;
private bool _finished;
private bool _cancelled;
internal LlmInferenceExchange(string requestId, Func<ServerRpc?> getServerRpc)
{
RequestId = requestId;
_getServerRpc = getServerRpc;
}
internal string RequestId { get; }
internal string Method { get; set; } = "GET";
internal CopilotRequestContext Context { get; set; } = null!;
internal CancellationTokenSource Abort { get; } = new();
internal bool Started => _started;
internal bool Finished => _finished;
internal bool Cancelled => _cancelled;
// --- Request body feed (driven by the adapter as chunk frames arrive) ---
internal void PushChunk(byte[] data) => _body.Writer.TryWrite(new BodyItem { Chunk = data });
internal void PushEnd() => _body.Writer.TryWrite(new BodyItem { End = true });
internal void PushCancel(string? reason)
{
_cancelled = true;
Abort.Cancel();
_body.Writer.TryWrite(new BodyItem { Cancel = true, CancelReason = reason });
}
/// <summary>
/// Request body bytes, yielded as they arrive. A cancel frame surfaces as an
/// <see cref="OperationCanceledException"/> so the consumer's upstream call
/// is torn down.
/// </summary>
internal IAsyncEnumerable<ReadOnlyMemory<byte>> RequestBody => ReadBodyAsync(Abort.Token);
private async IAsyncEnumerable<ReadOnlyMemory<byte>> ReadBodyAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
while (await _body.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
{
while (_body.Reader.TryRead(out var item))
{
if (item.Cancel)
{
_body.Writer.TryComplete();
throw new OperationCanceledException(
item.CancelReason is null
? "Request cancelled by runtime"
: $"Request cancelled by runtime: {item.CancelReason}");
}
if (item.End)
{
_body.Writer.TryComplete();
yield break;
}
if (item.Chunk is { Length: > 0 })
{
yield return item.Chunk;
}
}
}
}
// --- Response emit (driven by the handler). Strict state machine: ---
// StartResponseAsync once -> zero or more WriteResponseAsync -> exactly one
// of EndResponseAsync / ErrorResponseAsync.
internal async Task StartResponseAsync(int status, string? statusText, IReadOnlyDictionary<string, IReadOnlyList<string>>? headers)
{
if (_started)
{
throw new InvalidOperationException("LLM inference response StartAsync() called twice.");
}
if (_finished)
{
throw new InvalidOperationException("LLM inference response already finished.");
}
_started = true;
await ServerRpc()
.LlmInference.HttpResponseStartAsync(RequestId, status, ToWireHeaders(headers), statusText)
.ConfigureAwait(false);
}
internal Task WriteResponseAsync(ReadOnlyMemory<byte> data) =>
WriteChunkAsync(Convert.ToBase64String(data.ToArray()), binary: true);
internal Task WriteResponseAsync(string text)
{
ArgumentNullException.ThrowIfNull(text);
return WriteChunkAsync(text, binary: false);
}
internal async Task EndResponseAsync()
{
if (_finished)
{
return;
}
_finished = true;
await ServerRpc().LlmInference.HttpResponseChunkAsync(RequestId, string.Empty, end: true).ConfigureAwait(false);
}
internal async Task ErrorResponseAsync(string message, string? code = null)
{
ArgumentNullException.ThrowIfNull(message);
if (_finished)
{
return;
}
_finished = true;
await ServerRpc()
.LlmInference.HttpResponseChunkAsync(
RequestId,
string.Empty,
end: true,
error: new LlmInferenceHttpResponseChunkError { Message = message, Code = code })
.ConfigureAwait(false);
}
private async Task WriteChunkAsync(string data, bool binary)
{
if (_cancelled)
{
throw new InvalidOperationException("LLM inference request was cancelled by the runtime.");
}
if (!_started)
{
throw new InvalidOperationException("LLM inference response WriteAsync() called before StartAsync().");
}
if (_finished)
{
throw new InvalidOperationException("LLM inference response WriteAsync() called after EndAsync()/ErrorAsync().");
}
await ServerRpc()
.LlmInference.HttpResponseChunkAsync(RequestId, data, binary: binary, end: false)
.ConfigureAwait(false);
}
private ServerRpc ServerRpc() =>
_getServerRpc() ?? throw new InvalidOperationException("LLM inference response used after RPC connection closed.");
private static Dictionary<string, IList<string>> ToWireHeaders(IReadOnlyDictionary<string, IReadOnlyList<string>>? headers)
{
var result = new Dictionary<string, IList<string>>(StringComparer.OrdinalIgnoreCase);
if (headers is null)
{
return result;
}
foreach (var (name, values) in headers)
{
result[name] = values as IList<string> ?? [.. values];
}
return result;
}
private struct BodyItem
{
public byte[]? Chunk;
public bool End;
public bool Cancel;
public string? CancelReason;
}
}
/// <summary>
/// Adapts the generated <see cref="ILlmInferenceHandler"/> RPC entry points onto
/// a consumer's <see cref="CopilotRequestHandler"/>. Each <c>httpRequestStart</c>
/// allocates an <see cref="LlmInferenceExchange"/> and runs the handler in the
/// background; subsequent <c>httpRequestChunk</c> frames feed its body stream.
/// </summary>
internal sealed class LlmInferenceAdapter(CopilotRequestHandler handler, Func<ServerRpc?> getServerRpc) : ILlmInferenceHandler
{
private readonly CopilotRequestHandler _handler = handler ?? throw new ArgumentNullException(nameof(handler));
private readonly Func<ServerRpc?> _getServerRpc = getServerRpc ?? throw new ArgumentNullException(nameof(getServerRpc));
private readonly ConcurrentDictionary<string, LlmInferenceExchange> _pending = new(StringComparer.Ordinal);
public Task<LlmInferenceHttpRequestStartResult> HttpRequestStartAsync(LlmInferenceHttpRequestStartRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var transport = request.Transport == LlmInferenceHttpRequestStartTransport.Websocket
? CopilotRequestTransport.WebSocket
: CopilotRequestTransport.Http;
// The runtime dispatches httpRequestStart and httpRequestChunk frames
// concurrently, so body chunks (including the terminal end frame) can
// arrive before this start frame runs. GetOrAdd adopts any exchange a
// racing chunk already created — with its buffered body — instead of
// dropping those frames and hanging the body drain.
var exchange = _pending.GetOrAdd(request.RequestId, id => new LlmInferenceExchange(id, _getServerRpc));
exchange.Method = request.Method;
exchange.Context = new CopilotRequestContext(request.RequestId, request.Url, ToReadOnlyHeaders(request.Headers))
{
SessionId = request.SessionId,
Transport = transport,
CancellationToken = exchange.Abort.Token,
};
// Return from httpRequestStart immediately (after registering state) so
// the runtime's RPC reply is not gated on the consumer's I/O. The actual
// handler work runs asynchronously, exactly once per request.
_ = RunAsync(exchange);
return Task.FromResult(new LlmInferenceHttpRequestStartResult());
}
public Task<LlmInferenceHttpRequestChunkResult> HttpRequestChunkAsync(LlmInferenceHttpRequestChunkRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
// A chunk may arrive before its matching httpRequestStart (frames are
// dispatched concurrently). GetOrAdd buffers the body into the
// exchange's channel so no chunk — in particular the terminal end
// frame — is ever lost; the start frame later adopts this same exchange.
var exchange = _pending.GetOrAdd(request.RequestId, id => new LlmInferenceExchange(id, _getServerRpc));
RouteChunk(exchange, request);
return Task.FromResult(new LlmInferenceHttpRequestChunkResult());
}
private async Task RunAsync(LlmInferenceExchange exchange)
{
try
{
await _handler.HandleAsync(exchange).ConfigureAwait(false);
if (!exchange.Finished)
{
await FinalizeAsync(exchange, 502, "LLM inference handler returned without finalising the response (call ResponseBody.EndAsync() or .ErrorAsync()).", code: null).ConfigureAwait(false);
}
}
catch (Exception ex)
{
if (exchange.Cancelled || exchange.Abort.IsCancellationRequested)
{
// The runtime already cancelled this request; the handler's throw
// is just the abort propagating out of its upstream call.
await FinalizeAsync(exchange, 499, "Request cancelled by runtime", code: "cancelled").ConfigureAwait(false);
return;
}
await FinalizeAsync(exchange, 502, ex.Message, code: null).ConfigureAwait(false);
}
finally
{
_pending.TryRemove(exchange.RequestId, out _);
}
}
private static async Task FinalizeAsync(LlmInferenceExchange exchange, int status, string message, string? code)
{
if (exchange.Finished)
{
return;
}
try
{
if (!exchange.Started)
{
await exchange.StartResponseAsync(status, statusText: null, headers: null).ConfigureAwait(false);
}
await exchange.ErrorResponseAsync(message, code).ConfigureAwait(false);
}
catch
{
// Best-effort — the connection may already be dead.
}
}
private static void RouteChunk(LlmInferenceExchange exchange, LlmInferenceHttpRequestChunkRequest chunk)
{
if (chunk.Cancel == true)
{
exchange.PushCancel(chunk.CancelReason);
return;
}
if (!string.IsNullOrEmpty(chunk.Data))
{
exchange.PushChunk(DecodeChunkData(chunk.Data, chunk.Binary == true));
}
if (chunk.End == true)
{
exchange.PushEnd();
}
}
private static byte[] DecodeChunkData(string data, bool binary) =>
binary ? Convert.FromBase64String(data) : Encoding.UTF8.GetBytes(data);
private static Dictionary<string, IReadOnlyList<string>> ToReadOnlyHeaders(IDictionary<string, IList<string>> headers)
{
var result = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, values) in headers)
{
result[name] = values as IReadOnlyList<string> ?? [.. values];
}
return result;
}
}
/// <summary>
/// Forwards upstream WebSocket messages back to the owning
/// <see cref="LlmInferenceExchange"/>. The 101 upgrade head is emitted eagerly
/// via <see cref="StartAsync"/> (the runtime gates the connect on it);
/// thereafter writes are serialised so the head always precedes any body or
/// terminal frame.
/// </summary>
internal sealed class LlmWebSocketResponseBridge(LlmInferenceExchange exchange)
{
private readonly SemaphoreSlim _gate = new(1, 1);
private bool _started;
private bool _completed;
/// <summary>Emit the 101 upgrade head now, acknowledging the WebSocket connect.</summary>
internal Task StartAsync() => RunAsync(terminal: false, () => Task.CompletedTask);
internal Task WriteAsync(CopilotWebSocketMessage message) => RunAsync(terminal: false, () =>
message.IsBinary