-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcopilotRequestHandler.ts
More file actions
818 lines (735 loc) · 26.3 KB
/
Copy pathcopilotRequestHandler.ts
File metadata and controls
818 lines (735 loc) · 26.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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import type {
LlmInferenceHandler,
LlmInferenceHeaders,
LlmInferenceHttpRequestChunkRequest,
LlmInferenceHttpRequestChunkResult,
LlmInferenceHttpRequestStartRequest,
LlmInferenceHttpRequestStartResult,
} from "./generated/rpc.js";
import type { createServerRpc } from "./generated/rpc.js";
type ServerRpc = ReturnType<typeof createServerRpc>;
const sharedTextDecoder = new TextDecoder("utf-8", { fatal: false });
const sharedTextEncoder = new TextEncoder();
const kBridge = Symbol("copilotWebSocketResponseBridge");
const kCompletion = Symbol("copilotWebSocketCompletion");
const kOpen = Symbol("copilotWebSocketOpen");
const kSuppressCloseOnDispose = Symbol("copilotWebSocketSuppressCloseOnDispose");
const kHandle = Symbol("copilotRequestHandle");
type InternalContext = CopilotRequestContext & { [kBridge]: CopilotWebSocketResponseBridge };
/**
* Per-request context handed to every {@link CopilotRequestHandler} hook.
*
* @experimental
*/
export interface CopilotRequestContext {
readonly requestId: string;
readonly sessionId?: string;
readonly transport: "http" | "websocket";
url: string;
headers: LlmInferenceHeaders;
readonly signal: AbortSignal;
}
/**
* Terminal status for a callback-owned WebSocket connection.
*
* @experimental
*/
export class CopilotWebSocketCloseStatus {
static readonly normalClosure = new CopilotWebSocketCloseStatus();
constructor(
readonly description?: string,
readonly errorCode?: string,
readonly error?: Error
) {}
}
/**
* 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 when
* you want to service a fully synthetic connection yourself (e.g. answer the
* runtime without any real backend). For the common case of mutating and
* forwarding traffic to the real upstream, subclass {@link CopilotWebSocketForwarder}
* instead, which connects upstream and forwards by default.
*
* @experimental
*/
export abstract class CopilotWebSocketHandler implements AsyncDisposable {
readonly #response: CopilotWebSocketResponseBridge;
readonly #completion: Promise<CopilotWebSocketCloseStatus>;
#resolveCompletion!: (status: CopilotWebSocketCloseStatus) => void;
#closed = false;
[kSuppressCloseOnDispose] = false;
protected readonly context: CopilotRequestContext;
protected constructor(context: CopilotRequestContext) {
this.context = context;
const bridge = (context as Partial<InternalContext>)[kBridge];
if (!bridge) {
throw new Error("WebSocket response bridge is not attached");
}
this.#response = bridge;
this.#completion = new Promise<CopilotWebSocketCloseStatus>((resolve) => {
this.#resolveCompletion = resolve;
});
}
async sendResponseMessage(data: string | Uint8Array): Promise<void> {
await this.#response.write(data);
}
async close(
status: CopilotWebSocketCloseStatus = CopilotWebSocketCloseStatus.normalClosure
): Promise<void> {
if (this.#closed) {
return;
}
this.#closed = true;
if (status.error) {
await this.#response.error({
message: status.description ?? status.error.message,
code: status.errorCode,
});
} else {
await this.#response.end();
}
this.#resolveCompletion(status);
}
abstract sendRequestMessage(data: string | Uint8Array): Promise<void> | void;
async [Symbol.asyncDispose](): Promise<void> {
if (!this[kSuppressCloseOnDispose] && !this.#closed) {
await this.close(CopilotWebSocketCloseStatus.normalClosure);
}
}
/** @internal */
get [kCompletion](): Promise<CopilotWebSocketCloseStatus> {
return this.#completion;
}
/** @internal */
async [kOpen](): Promise<void> {}
}
/**
* WebSocket handler that connects to the real upstream and forwards traffic by
* default. This is the type returned by the default
* {@link CopilotRequestHandler.openWebSocket}.
*
* Override nothing to get full pass-through. To mutate traffic, subclass this
* type and override a message hook, then call `super` to keep forwarding to the
* upstream. (Subclassing {@link CopilotWebSocketHandler} instead would drop
* forwarding entirely.)
*
* @experimental
*/
export class CopilotWebSocketForwarder extends CopilotWebSocketHandler {
#upstream: WebSocket | null = null;
constructor(context: CopilotRequestContext) {
super(context);
}
override sendRequestMessage(data: string | Uint8Array): void {
if (this.#upstream?.readyState !== WebSocket.OPEN) {
return;
}
this.#upstream.send(data);
}
/** @internal */
override async [kOpen](): Promise<void> {
if (this.#upstream) {
return;
}
const upstream = new WebSocket(this.context.url);
upstream.binaryType = "arraybuffer";
this.#upstream = upstream;
upstream.addEventListener("message", (event) => {
void this.sendResponseMessage(normalizeWsData(event.data)).catch(
async (err: unknown) => {
await this.close(
new CopilotWebSocketCloseStatus(
err instanceof Error ? err.message : String(err),
undefined,
err instanceof Error ? err : new Error(String(err))
)
);
}
);
});
upstream.addEventListener("close", () => {
void this.close(CopilotWebSocketCloseStatus.normalClosure);
});
upstream.addEventListener("error", () => {
void this.close(
new CopilotWebSocketCloseStatus(
"WebSocket error",
undefined,
new Error("WebSocket error")
)
);
});
await new Promise<void>((resolve, reject) => {
if (upstream.readyState === WebSocket.OPEN) {
resolve();
return;
}
upstream.addEventListener("open", () => resolve(), { once: true });
upstream.addEventListener("error", () => reject(new Error("WebSocket error")), {
once: true,
});
});
}
override async close(
status: CopilotWebSocketCloseStatus = CopilotWebSocketCloseStatus.normalClosure
): Promise<void> {
try {
if (
this.#upstream?.readyState === WebSocket.OPEN ||
this.#upstream?.readyState === WebSocket.CONNECTING
) {
this.#upstream?.close();
}
} catch {
// Best-effort; the socket may already be closed.
}
await super.close(status);
}
override async [Symbol.asyncDispose](): Promise<void> {
try {
await super[Symbol.asyncDispose]();
} finally {
try {
this.#upstream?.close();
} catch {
// Best-effort.
}
}
}
}
/**
* Base class for SDK consumers who want to observe or mutate the outbound
* model-layer requests the runtime issues (for both CAPI and BYOK providers).
* Subclass and override {@link sendRequest} or {@link openWebSocket}; an
* instance that overrides nothing is a transparent pass-through.
*
* @experimental
*/
export class CopilotRequestHandler {
protected sendRequest(request: Request, ctx: CopilotRequestContext): Promise<Response> {
return fetch(request, { signal: ctx.signal });
}
protected openWebSocket(ctx: CopilotRequestContext): Promise<CopilotWebSocketHandler> {
return Promise.resolve(new CopilotWebSocketForwarder(ctx));
}
/** @internal */
async [kHandle](exchange: CopilotRequestExchange): Promise<void> {
const bridge = new CopilotWebSocketResponseBridge(exchange);
const ctx: InternalContext = {
requestId: exchange.requestId,
sessionId: exchange.sessionId,
transport: exchange.transport,
url: exchange.url,
headers: exchange.headers,
signal: exchange.signal,
[kBridge]: bridge,
};
if (exchange.transport === "websocket") {
await this.#handleWebSocket(exchange, ctx);
} else {
await this.#handleHttp(exchange, ctx);
}
}
async #handleHttp(exchange: CopilotRequestExchange, ctx: CopilotRequestContext): Promise<void> {
const request = await buildFetchRequest(exchange);
const response = await this.sendRequest(request, ctx);
await streamResponse(response, exchange);
}
async #handleWebSocket(exchange: CopilotRequestExchange, ctx: InternalContext): Promise<void> {
const handler = await this.openWebSocket(ctx);
try {
await handler[kOpen]();
// 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 ctx[kBridge].start();
let cancelled: unknown;
const clientSettled = (async () => {
for await (const chunk of exchange.requestBody) {
await handler.sendRequestMessage(decodeFrame(chunk));
}
return "client-complete" as const;
})().catch((err) => {
cancelled = err;
return "client-error" as const;
});
const first = await Promise.race([
clientSettled,
handler[kCompletion].then(() => "server-done" as const),
]);
if (first === "client-error") {
handler[kSuppressCloseOnDispose] = true;
throw cancelled instanceof Error ? cancelled : new Error(String(cancelled));
}
if (first === "client-complete") {
await handler.close(CopilotWebSocketCloseStatus.normalClosure);
await handler[kCompletion];
return;
}
const status = await handler[kCompletion];
if (status.error) {
throw status.error;
}
} finally {
await handler[Symbol.asyncDispose]();
}
}
}
/**
* Adapt a {@link CopilotRequestHandler} into the generated
* {@link LlmInferenceHandler} shape consumed by the SDK's RPC dispatcher.
*
* Maintains a per-`requestId` table of {@link CopilotRequestExchange}: each
* `httpRequestStart` allocates one and fires the handler in the background,
* returning immediately so the runtime's RPC reply is not gated on the
* consumer's I/O. Subsequent `httpRequestChunk` frames are routed into the
* matching exchange's body stream.
*
* @internal
*/
export function createCopilotRequestAdapter(
handler: CopilotRequestHandler,
getServerRpc: () => ServerRpc | undefined
): LlmInferenceHandler {
const pending = new Map<string, CopilotRequestExchange>();
function getOrCreate(requestId: string): CopilotRequestExchange {
// The runtime dispatches httpRequestStart and httpRequestChunk frames
// independently. get-or-create keeps the adapter correct regardless of
// arrival order: a body chunk (including the terminal end frame) that
// races ahead of its start frame is buffered into the same exchange
// rather than dropped, which would otherwise hang the body drain.
let exchange = pending.get(requestId);
if (!exchange) {
exchange = new CopilotRequestExchange(requestId, getServerRpc);
pending.set(requestId, exchange);
}
return exchange;
}
async function run(exchange: CopilotRequestExchange): Promise<void> {
try {
await handler[kHandle](exchange);
if (!exchange.finished) {
await finalize(
exchange,
502,
"Copilot request handler returned without finalising the response (call responseBody.end() or .error())."
);
}
} catch (err) {
if (exchange.cancelled || exchange.signal.aborted) {
// The runtime already cancelled this request; the handler's
// throw is just the abort propagating out of its upstream call.
await finalize(exchange, 499, "Request cancelled by runtime", "cancelled");
return;
}
const message = err instanceof Error ? err.message : String(err);
await finalize(exchange, 502, message);
} finally {
pending.delete(exchange.requestId);
}
}
return {
async httpRequestStart(
params: LlmInferenceHttpRequestStartRequest
): Promise<LlmInferenceHttpRequestStartResult> {
// Adopt any exchange a racing chunk already created — with its
// buffered body — rather than dropping those frames.
const exchange = getOrCreate(params.requestId);
exchange.setContext(params);
void run(exchange);
return {};
},
async httpRequestChunk(
params: LlmInferenceHttpRequestChunkRequest
): Promise<LlmInferenceHttpRequestChunkResult> {
// May arrive before the matching start frame; get-or-create so the
// body is buffered, never lost.
routeChunk(getOrCreate(params.requestId), params);
return {};
},
};
}
async function finalize(
exchange: CopilotRequestExchange,
status: number,
message: string,
code?: string
): Promise<void> {
if (exchange.finished) {
return;
}
try {
if (!exchange.started) {
await exchange.startResponse({ status, headers: {} });
}
await exchange.errorResponse({ message, code });
} catch {
// Best-effort — the connection may already be dead.
}
}
function routeChunk(
exchange: CopilotRequestExchange,
params: LlmInferenceHttpRequestChunkRequest
): void {
if (params.cancel) {
exchange.pushCancel(params.cancelReason);
return;
}
if (params.data && params.data.length > 0) {
exchange.pushChunk(decodeChunkData(params.data, !!params.binary));
}
if (params.end) {
exchange.pushEnd();
}
}
/** Response head emitted to the runtime via {@link CopilotRequestExchange.startResponse}. */
interface ResponseInit {
status: number;
statusText?: string;
headers?: LlmInferenceHeaders;
}
interface BodyQueueItem {
chunk?: Uint8Array;
end?: boolean;
cancel?: { reason?: string };
}
/**
* One intercepted request in flight. Carries the request context plus the body
* byte stream the runtime feeds in via `httpRequestChunk` frames, and emits the
* handler's response straight back to the runtime through the generated
* `llmInference` server API. Replaces the former provider/sink/response-channel
* indirection with a single object the adapter owns and the handler drives.
*/
class CopilotRequestExchange {
readonly requestId: string;
sessionId?: string;
method = "GET";
url = "";
headers: LlmInferenceHeaders = {};
transport: "http" | "websocket" = "http";
readonly #getServerRpc: () => ServerRpc | undefined;
readonly #abort = new AbortController();
readonly #buffer: BodyQueueItem[] = [];
#waker: (() => void) | null = null;
#drained = false;
#started = false;
#finished = false;
#cancelled = false;
constructor(requestId: string, getServerRpc: () => ServerRpc | undefined) {
this.requestId = requestId;
this.#getServerRpc = getServerRpc;
}
/** Fill in the request context once the matching start frame arrives. */
setContext(params: LlmInferenceHttpRequestStartRequest): void {
this.sessionId = params.sessionId;
this.method = params.method;
this.url = params.url;
this.headers = params.headers;
this.transport = params.transport ?? "http";
}
get signal(): AbortSignal {
return this.#abort.signal;
}
get started(): boolean {
return this.#started;
}
get finished(): boolean {
return this.#finished;
}
get cancelled(): boolean {
return this.#cancelled;
}
// --- Request body feed (driven by the adapter as chunk frames arrive) ---
pushChunk(chunk: Uint8Array): void {
this.#push({ chunk });
}
pushEnd(): void {
this.#push({ end: true });
}
pushCancel(reason?: string): void {
this.#cancelled = true;
this.#abort.abort();
this.#push({ cancel: { reason } });
}
#push(item: BodyQueueItem): void {
this.#buffer.push(item);
const w = this.#waker;
this.#waker = null;
w?.();
}
/**
* Request body bytes, yielded as they arrive. A cancel frame surfaces as a
* thrown error so the handler's upstream call is torn down.
*/
get requestBody(): AsyncIterable<Uint8Array> {
return {
[Symbol.asyncIterator]: (): AsyncIterator<Uint8Array> => ({
next: async (): Promise<IteratorResult<Uint8Array>> => {
if (this.#drained) {
return { value: undefined, done: true };
}
while (this.#buffer.length === 0) {
await new Promise<void>((resolve) => {
this.#waker = resolve;
});
}
const item = this.#buffer.shift()!;
if (item.cancel) {
this.#drained = true;
throw new Error(
item.cancel.reason
? `Request cancelled by runtime: ${item.cancel.reason}`
: "Request cancelled by runtime"
);
}
if (item.end) {
this.#drained = true;
return { value: undefined, done: true };
}
return { value: item.chunk ?? new Uint8Array(), done: false };
},
}),
};
}
// --- Response emit (driven by the handler). Strict state machine: ---
// startResponse once -> 0..N writeResponse -> exactly one of
// endResponse / errorResponse.
async startResponse(init: ResponseInit): Promise<void> {
if (this.#started) {
throw new Error("Copilot request response start() called twice.");
}
if (this.#finished) {
throw new Error("Copilot request response already finished.");
}
this.#started = true;
await this.#rpc().llmInference.httpResponseStart({
requestId: this.requestId,
status: init.status,
statusText: init.statusText,
headers: init.headers ?? {},
});
}
async writeResponse(data: string | Uint8Array): Promise<void> {
if (this.#cancelled) {
throw new Error("Copilot request was cancelled by the runtime.");
}
if (!this.#started) {
throw new Error("Copilot request response write() called before start().");
}
if (this.#finished) {
throw new Error("Copilot request response write() called after end()/error().");
}
const isString = typeof data === "string";
await this.#rpc().llmInference.httpResponseChunk({
requestId: this.requestId,
data: isString ? data : Buffer.from(data).toString("base64"),
binary: !isString,
end: false,
});
}
async endResponse(): Promise<void> {
if (this.#finished) {
return;
}
this.#finished = true;
await this.#rpc().llmInference.httpResponseChunk({
requestId: this.requestId,
data: "",
end: true,
});
}
async errorResponse(error: { message: string; code?: string }): Promise<void> {
if (this.#finished) {
return;
}
this.#finished = true;
await this.#rpc().llmInference.httpResponseChunk({
requestId: this.requestId,
data: "",
end: true,
error: { message: error.message, code: error.code },
});
}
#rpc(): ServerRpc {
const r = this.#getServerRpc();
if (!r) {
throw new Error("Copilot request response used after RPC connection closed.");
}
return r;
}
}
const FORBIDDEN_REQUEST_HEADERS = new Set([
"host",
"connection",
"content-length",
"transfer-encoding",
"keep-alive",
"upgrade",
"proxy-connection",
"te",
"trailer",
]);
async function buildFetchRequest(exchange: CopilotRequestExchange): Promise<Request> {
const headers = new Headers();
for (const [name, values] of Object.entries(exchange.headers)) {
if (!values) {
continue;
}
if (FORBIDDEN_REQUEST_HEADERS.has(name.toLowerCase())) {
continue;
}
for (const value of values) {
headers.append(name, value);
}
}
const method = exchange.method.toUpperCase();
const hasBody = method !== "GET" && method !== "HEAD";
let body: Uint8Array | undefined;
if (hasBody) {
const buffered = await drainAsync(exchange.requestBody);
if (buffered.length > 0) {
body = buffered;
}
} else {
await drainAsync(exchange.requestBody);
}
return new Request(exchange.url, { method, headers, body });
}
async function drainAsync(stream: AsyncIterable<Uint8Array>): Promise<Uint8Array> {
const parts: Uint8Array[] = [];
let total = 0;
for await (const chunk of stream) {
parts.push(chunk);
total += chunk.byteLength;
}
if (parts.length === 0) {
return new Uint8Array(0);
}
if (parts.length === 1) {
return parts[0];
}
const out = new Uint8Array(total);
let off = 0;
for (const part of parts) {
out.set(part, off);
off += part.byteLength;
}
return out;
}
async function streamResponse(response: Response, exchange: CopilotRequestExchange): Promise<void> {
await exchange.startResponse({
status: response.status,
statusText: response.statusText || undefined,
headers: headersToMultiMap(response.headers),
});
const body = response.body;
if (!body) {
await exchange.endResponse();
return;
}
const reader = body.getReader();
try {
for (;;) {
const { value, done } = await reader.read();
if (done) {
break;
}
if (value && value.byteLength > 0) {
await exchange.writeResponse(value);
}
}
await exchange.endResponse();
} finally {
reader.releaseLock();
}
}
function headersToMultiMap(headers: Headers): LlmInferenceHeaders {
const out: Record<string, string[]> = {};
headers.forEach((value, name) => {
if (name.toLowerCase() === "set-cookie") {
return;
}
const list = out[name] ?? (out[name] = []);
list.push(value);
});
const setCookies = headers.getSetCookie();
if (setCookies.length > 0) {
out["set-cookie"] = setCookies;
}
return out;
}
function decodeChunkData(data: string, binary: boolean): Uint8Array {
if (binary) {
return new Uint8Array(Buffer.from(data, "base64"));
}
return sharedTextEncoder.encode(data);
}
function decodeFrame(chunk: Uint8Array): string {
return sharedTextDecoder.decode(chunk);
}
function normalizeWsData(data: unknown): string | Uint8Array {
if (typeof data === "string") {
return data;
}
if (data instanceof Uint8Array) {
return data;
}
if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
}
return new Uint8Array();
}
/**
* Forwards upstream WebSocket messages back to the owning
* {@link CopilotRequestExchange}. The 101 upgrade head is emitted eagerly via
* {@link start} (the runtime gates the connect on it); thereafter writes are
* serialised so the head always precedes any body or terminal frame.
*/
class CopilotWebSocketResponseBridge {
readonly #exchange: CopilotRequestExchange;
#started = false;
#completed = false;
#serial: Promise<void> = Promise.resolve();
constructor(exchange: CopilotRequestExchange) {
this.#exchange = exchange;
}
/** Emit the 101 upgrade head now, acknowledging the WebSocket connect. */
start(): Promise<void> {
return this.#run(false, () => Promise.resolve());
}
write(data: string | Uint8Array): Promise<void> {
return this.#run(false, () => this.#exchange.writeResponse(data));
}
end(): Promise<void> {
return this.#run(true, () => this.#exchange.endResponse());
}
error(error: { message: string; code?: string }): Promise<void> {
return this.#run(true, () => this.#exchange.errorResponse(error));
}
#run(terminal: boolean, action: () => Promise<void>): Promise<void> {
const task = this.#serial.then(async () => {
if (this.#completed) {
return;
}
if (!this.#started) {
this.#started = true;
await this.#exchange.startResponse({ status: 101, headers: {} });
}
if (terminal) {
this.#completed = true;
}
await action();
});
this.#serial = task.catch(() => {});
return task;
}
}