@microsoft/copilot-sdk 0.0.0-stage → 2.0.0-preview.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +2531 -2
  2. package/dist/canvas.d.ts +135 -0
  3. package/dist/canvas.js +51 -0
  4. package/dist/cjs/canvas.js +77 -0
  5. package/dist/cjs/cliVersion.js +31 -0
  6. package/dist/cjs/client.js +3941 -0
  7. package/dist/cjs/copilotRequestHandler.js +815 -0
  8. package/dist/cjs/decisions.js +139 -0
  9. package/dist/cjs/entra.js +83 -0
  10. package/dist/cjs/extension.js +79 -0
  11. package/dist/cjs/ffiRuntimeHost.js +400 -0
  12. package/dist/cjs/generated/lifecycle-diagnostics.js +16 -0
  13. package/dist/cjs/generated/rpc.js +5883 -0
  14. package/dist/cjs/generated/session-events.js +16 -0
  15. package/dist/cjs/host.js +83 -0
  16. package/dist/cjs/index.js +100 -0
  17. package/dist/cjs/installationConfirmation.js +98 -0
  18. package/dist/cjs/jsonrpcTypes.js +41 -0
  19. package/dist/cjs/localModelJson.js +103 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/cjs/providerConfiguration.js +39 -0
  22. package/dist/cjs/rpcCancellation.js +49 -0
  23. package/dist/cjs/runtimeArtifacts.js +255 -0
  24. package/dist/cjs/schema.js +40 -0
  25. package/dist/cjs/sdkProtocolVersion.js +33 -0
  26. package/dist/cjs/session.js +2764 -0
  27. package/dist/cjs/sessionFsProvider.js +283 -0
  28. package/dist/cjs/taskAnalyticsJson.js +47 -0
  29. package/dist/cjs/telemetry.js +35 -0
  30. package/dist/cjs/toolSet.js +107 -0
  31. package/dist/cjs/types.js +204 -0
  32. package/dist/cjs/workflow.js +278 -0
  33. package/dist/cliVersion.d.ts +2 -0
  34. package/dist/cliVersion.js +6 -0
  35. package/dist/client.d.ts +576 -0
  36. package/dist/client.js +3924 -0
  37. package/dist/copilotRequestHandler.d.ts +91 -0
  38. package/dist/copilotRequestHandler.js +787 -0
  39. package/dist/decisions.d.ts +65 -0
  40. package/dist/decisions.js +113 -0
  41. package/dist/entra.d.ts +3 -0
  42. package/dist/entra.js +59 -0
  43. package/dist/extension.d.ts +69 -0
  44. package/dist/extension.js +59 -0
  45. package/dist/ffiRuntimeHost.d.ts +44 -0
  46. package/dist/ffiRuntimeHost.js +366 -0
  47. package/dist/generated/lifecycle-diagnostics.d.ts +232 -0
  48. package/dist/generated/lifecycle-diagnostics.js +0 -0
  49. package/dist/generated/rpc.d.ts +47706 -0
  50. package/dist/generated/rpc.js +5854 -0
  51. package/dist/generated/session-events.d.ts +17349 -0
  52. package/dist/generated/session-events.js +0 -0
  53. package/dist/host.d.ts +143 -0
  54. package/dist/host.js +59 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.js +74 -0
  57. package/dist/installationConfirmation.d.ts +19 -0
  58. package/dist/installationConfirmation.js +74 -0
  59. package/dist/jsonrpcTypes.d.ts +16 -0
  60. package/dist/jsonrpcTypes.js +17 -0
  61. package/dist/localModelJson.d.ts +1 -0
  62. package/dist/localModelJson.js +69 -0
  63. package/dist/providerConfiguration.d.ts +3 -0
  64. package/dist/providerConfiguration.js +15 -0
  65. package/dist/rpcCancellation.d.ts +3 -0
  66. package/dist/rpcCancellation.js +25 -0
  67. package/dist/runtimeArtifacts.d.ts +18 -0
  68. package/dist/runtimeArtifacts.js +233 -0
  69. package/dist/schema.d.ts +4 -0
  70. package/dist/schema.js +14 -0
  71. package/dist/sdkProtocolVersion.d.ts +10 -0
  72. package/dist/sdkProtocolVersion.js +8 -0
  73. package/dist/session.d.ts +524 -0
  74. package/dist/session.js +2751 -0
  75. package/dist/sessionFsProvider.d.ts +130 -0
  76. package/dist/sessionFsProvider.js +257 -0
  77. package/dist/taskAnalyticsJson.d.ts +8 -0
  78. package/dist/taskAnalyticsJson.js +12 -0
  79. package/dist/telemetry.d.ts +14 -0
  80. package/dist/telemetry.js +11 -0
  81. package/dist/toolSet.d.ts +75 -0
  82. package/dist/toolSet.js +82 -0
  83. package/dist/types.d.ts +3864 -0
  84. package/dist/types.js +169 -0
  85. package/dist/workflow.d.ts +413 -0
  86. package/dist/workflow.js +248 -0
  87. package/docs/agent-author.md +372 -0
  88. package/docs/examples.md +747 -0
  89. package/docs/extensions.md +121 -0
  90. package/docs/workflows.md +303 -0
  91. package/package.json +135 -5
@@ -0,0 +1,787 @@
1
+ const sharedTextDecoder = new TextDecoder("utf-8", { fatal: false });
2
+ const sharedTextEncoder = new TextEncoder();
3
+ const HTTP_RESPONSE_READ_AHEAD_BYTES = 32 * 1024;
4
+ const kBridge = /* @__PURE__ */ Symbol("copilotWebSocketResponseBridge");
5
+ const kCompletion = /* @__PURE__ */ Symbol("copilotWebSocketCompletion");
6
+ const kOpen = /* @__PURE__ */ Symbol("copilotWebSocketOpen");
7
+ const kSuppressCloseOnDispose = /* @__PURE__ */ Symbol("copilotWebSocketSuppressCloseOnDispose");
8
+ const kHandle = /* @__PURE__ */ Symbol("copilotRequestHandle");
9
+ class CopilotWebSocketCloseStatus {
10
+ constructor(description, errorCode, error) {
11
+ this.description = description;
12
+ this.errorCode = errorCode;
13
+ this.error = error;
14
+ }
15
+ description;
16
+ errorCode;
17
+ error;
18
+ static normalClosure = new CopilotWebSocketCloseStatus();
19
+ }
20
+ class CopilotWebSocketHandler {
21
+ #response;
22
+ #completion;
23
+ #resolveCompletion;
24
+ #closed = false;
25
+ [kSuppressCloseOnDispose] = false;
26
+ context;
27
+ constructor(context) {
28
+ this.context = context;
29
+ const bridge = context[kBridge];
30
+ if (!bridge) {
31
+ throw new Error("WebSocket response bridge is not attached");
32
+ }
33
+ this.#response = bridge;
34
+ this.#completion = new Promise((resolve) => {
35
+ this.#resolveCompletion = resolve;
36
+ });
37
+ }
38
+ async sendResponseMessage(data) {
39
+ await this.#response.write(data);
40
+ }
41
+ async close(status = CopilotWebSocketCloseStatus.normalClosure) {
42
+ if (this.#closed) {
43
+ return;
44
+ }
45
+ this.#closed = true;
46
+ if (status.error) {
47
+ await this.#response.error({
48
+ message: status.description ?? status.error.message,
49
+ code: status.errorCode
50
+ });
51
+ } else {
52
+ await this.#response.end();
53
+ }
54
+ this.#resolveCompletion(status);
55
+ }
56
+ async [Symbol.asyncDispose]() {
57
+ if (!this[kSuppressCloseOnDispose] && !this.#closed) {
58
+ await this.close(CopilotWebSocketCloseStatus.normalClosure);
59
+ }
60
+ }
61
+ /** @internal */
62
+ get [kCompletion]() {
63
+ return this.#completion;
64
+ }
65
+ /** @internal */
66
+ async [kOpen]() {
67
+ }
68
+ }
69
+ class CopilotWebSocketForwarder extends CopilotWebSocketHandler {
70
+ #upstream = null;
71
+ constructor(context) {
72
+ super(context);
73
+ }
74
+ sendRequestMessage(data, _ctx) {
75
+ if (this.#upstream?.readyState !== WebSocket.OPEN) {
76
+ return;
77
+ }
78
+ this.#upstream.send(data);
79
+ }
80
+ /** @internal */
81
+ async [kOpen]() {
82
+ if (this.#upstream) {
83
+ return;
84
+ }
85
+ const upstream = new WebSocket(this.context.url, {
86
+ headers: forwardedRequestHeaders(this.context.headers)
87
+ });
88
+ upstream.binaryType = "arraybuffer";
89
+ this.#upstream = upstream;
90
+ upstream.addEventListener("message", (event) => {
91
+ void this.sendResponseMessage(normalizeWsData(event.data)).catch(
92
+ async (err) => {
93
+ await this.close(
94
+ new CopilotWebSocketCloseStatus(
95
+ err instanceof Error ? err.message : String(err),
96
+ void 0,
97
+ err instanceof Error ? err : new Error(String(err))
98
+ )
99
+ );
100
+ }
101
+ );
102
+ });
103
+ upstream.addEventListener("close", () => {
104
+ void this.close(CopilotWebSocketCloseStatus.normalClosure);
105
+ });
106
+ upstream.addEventListener("error", () => {
107
+ void this.close(
108
+ new CopilotWebSocketCloseStatus(
109
+ "WebSocket error",
110
+ void 0,
111
+ new Error("WebSocket error")
112
+ )
113
+ );
114
+ });
115
+ await new Promise((resolve, reject) => {
116
+ if (upstream.readyState === WebSocket.OPEN) {
117
+ resolve();
118
+ return;
119
+ }
120
+ upstream.addEventListener("open", () => resolve(), { once: true });
121
+ upstream.addEventListener("error", () => reject(new Error("WebSocket error")), {
122
+ once: true
123
+ });
124
+ });
125
+ }
126
+ async close(status = CopilotWebSocketCloseStatus.normalClosure) {
127
+ const upstream = this.#upstream;
128
+ this.#upstream = null;
129
+ const completion = super.close(status);
130
+ try {
131
+ if (upstream?.readyState === WebSocket.OPEN || upstream?.readyState === WebSocket.CONNECTING) {
132
+ upstream.close();
133
+ }
134
+ } catch {
135
+ }
136
+ await completion;
137
+ }
138
+ async [Symbol.asyncDispose]() {
139
+ try {
140
+ await super[Symbol.asyncDispose]();
141
+ } finally {
142
+ try {
143
+ this.#upstream?.close();
144
+ } catch {
145
+ }
146
+ }
147
+ }
148
+ }
149
+ class CopilotRequestHandler {
150
+ sendRequest(request, ctx) {
151
+ return fetch(request, { signal: ctx.signal });
152
+ }
153
+ openWebSocket(ctx) {
154
+ return Promise.resolve(new CopilotWebSocketForwarder(ctx));
155
+ }
156
+ /** @internal */
157
+ async [kHandle](exchange) {
158
+ const bridge = new CopilotWebSocketResponseBridge(exchange);
159
+ const ctx = {
160
+ requestId: exchange.requestId,
161
+ sessionId: exchange.sessionId,
162
+ agentId: exchange.agentId,
163
+ agentInvocationId: exchange.agentInvocationId,
164
+ parentAgentId: exchange.parentAgentId,
165
+ interactionType: exchange.interactionType,
166
+ transport: exchange.transport,
167
+ url: exchange.url,
168
+ headers: exchange.headers,
169
+ signal: exchange.signal,
170
+ [kBridge]: bridge
171
+ };
172
+ if (exchange.transport === "websocket") {
173
+ await this.#handleWebSocket(exchange, ctx);
174
+ } else {
175
+ await this.#handleHttp(exchange, ctx);
176
+ }
177
+ }
178
+ async #handleHttp(exchange, ctx) {
179
+ const request = await buildFetchRequest(exchange);
180
+ const response = await this.sendRequest(request, ctx);
181
+ await streamResponse(response, exchange);
182
+ }
183
+ async #handleWebSocket(exchange, ctx) {
184
+ const handler = await this.openWebSocket(ctx);
185
+ try {
186
+ await handler[kOpen]();
187
+ await ctx[kBridge].start();
188
+ let cancelled;
189
+ const clientSettled = (async () => {
190
+ for await (const chunk of exchange.requestBody) {
191
+ await handler.sendRequestMessage(decodeFrame(chunk.chunk ?? new Uint8Array()), {
192
+ ...ctx,
193
+ agentInvocationId: chunk.agentInvocationId
194
+ });
195
+ }
196
+ return "client-complete";
197
+ })().catch((err) => {
198
+ cancelled = err;
199
+ return "client-error";
200
+ });
201
+ const first = await Promise.race([
202
+ clientSettled,
203
+ handler[kCompletion].then(() => "server-done")
204
+ ]);
205
+ if (first === "client-error") {
206
+ handler[kSuppressCloseOnDispose] = true;
207
+ throw cancelled instanceof Error ? cancelled : new Error(String(cancelled));
208
+ }
209
+ if (first === "client-complete") {
210
+ await handler.close(CopilotWebSocketCloseStatus.normalClosure);
211
+ await handler[kCompletion];
212
+ return;
213
+ }
214
+ const status = await handler[kCompletion];
215
+ if (status.error) {
216
+ throw status.error;
217
+ }
218
+ } finally {
219
+ await handler[Symbol.asyncDispose]();
220
+ }
221
+ }
222
+ }
223
+ const MAX_FINISHED_REQUEST_IDS = 256;
224
+ function createCopilotRequestAdapter(handler, getServerRpc) {
225
+ const pending = /* @__PURE__ */ new Map();
226
+ const finished = /* @__PURE__ */ new Set();
227
+ function rememberFinished(requestId) {
228
+ if (finished.has(requestId)) {
229
+ return;
230
+ }
231
+ finished.add(requestId);
232
+ if (finished.size > MAX_FINISHED_REQUEST_IDS) {
233
+ finished.delete(finished.values().next().value);
234
+ }
235
+ }
236
+ function getOrCreate(requestId) {
237
+ let exchange = pending.get(requestId);
238
+ if (!exchange) {
239
+ if (finished.has(requestId)) {
240
+ return void 0;
241
+ }
242
+ exchange = new CopilotRequestExchange(requestId, getServerRpc);
243
+ pending.set(requestId, exchange);
244
+ }
245
+ return exchange;
246
+ }
247
+ async function run(exchange) {
248
+ try {
249
+ await handler[kHandle](exchange);
250
+ if (!exchange.finished) {
251
+ await finalize(
252
+ exchange,
253
+ 502,
254
+ "Copilot request handler returned without finalising the response (call responseBody.end() or .error())."
255
+ );
256
+ }
257
+ } catch (err) {
258
+ if (exchange.cancelled || exchange.signal.aborted) {
259
+ await finalize(exchange, 499, "Request cancelled by runtime", "cancelled");
260
+ return;
261
+ }
262
+ const message = err instanceof Error ? err.message : String(err);
263
+ await finalize(exchange, 502, message);
264
+ } finally {
265
+ if (pending.get(exchange.requestId) === exchange) {
266
+ pending.delete(exchange.requestId);
267
+ }
268
+ rememberFinished(exchange.requestId);
269
+ }
270
+ }
271
+ return {
272
+ async httpRequestStart(params) {
273
+ const exchange = getOrCreate(params.requestId);
274
+ if (!exchange) {
275
+ throw new Error(
276
+ `llmInference.httpRequestStart for request "${params.requestId}", which already finished`
277
+ );
278
+ }
279
+ exchange.setContext(params);
280
+ void run(exchange);
281
+ return {};
282
+ },
283
+ async httpRequestChunk(params) {
284
+ const exchange = getOrCreate(params.requestId);
285
+ if (exchange) {
286
+ routeChunk(exchange, params);
287
+ }
288
+ return {};
289
+ },
290
+ cancelPending() {
291
+ const exchanges = [...pending.values()];
292
+ pending.clear();
293
+ for (const exchange of exchanges) {
294
+ exchange.pushCancel("RPC connection closed");
295
+ }
296
+ }
297
+ };
298
+ }
299
+ async function finalize(exchange, status, message, code) {
300
+ if (exchange.finished) {
301
+ return;
302
+ }
303
+ try {
304
+ if (!exchange.started) {
305
+ await exchange.startResponse({ status, headers: {} });
306
+ }
307
+ await exchange.errorResponse({ message, code });
308
+ } catch {
309
+ }
310
+ }
311
+ function routeChunk(exchange, params) {
312
+ if (params.cancel) {
313
+ exchange.pushCancel(params.cancelReason);
314
+ return;
315
+ }
316
+ if (params.data && params.data.length > 0) {
317
+ exchange.pushChunk(decodeChunkData(params.data, !!params.binary), params.agentInvocationId);
318
+ }
319
+ if (params.end) {
320
+ exchange.pushEnd();
321
+ }
322
+ }
323
+ class CopilotRequestExchange {
324
+ requestId;
325
+ sessionId;
326
+ agentId;
327
+ agentInvocationId;
328
+ parentAgentId;
329
+ interactionType;
330
+ method = "GET";
331
+ url = "";
332
+ headers = {};
333
+ transport = "http";
334
+ #getServerRpc;
335
+ #abort = new AbortController();
336
+ #buffer = [];
337
+ #waker = null;
338
+ #drained = false;
339
+ #started = false;
340
+ #finished = false;
341
+ #cancelled = false;
342
+ constructor(requestId, getServerRpc) {
343
+ this.requestId = requestId;
344
+ this.#getServerRpc = getServerRpc;
345
+ }
346
+ /** Fill in the request context once the matching start frame arrives. */
347
+ setContext(params) {
348
+ this.sessionId = params.sessionId;
349
+ this.agentId = params.agentId;
350
+ this.agentInvocationId = params.agentInvocationId;
351
+ this.parentAgentId = params.parentAgentId;
352
+ this.interactionType = params.interactionType;
353
+ this.method = params.method;
354
+ this.url = params.url;
355
+ this.headers = params.headers;
356
+ this.transport = params.transport ?? "http";
357
+ }
358
+ get signal() {
359
+ return this.#abort.signal;
360
+ }
361
+ get started() {
362
+ return this.#started;
363
+ }
364
+ get finished() {
365
+ return this.#finished;
366
+ }
367
+ get cancelled() {
368
+ return this.#cancelled;
369
+ }
370
+ // --- Request body feed (driven by the adapter as chunk frames arrive) ---
371
+ pushChunk(chunk, agentInvocationId) {
372
+ this.#push({ chunk, agentInvocationId });
373
+ }
374
+ pushEnd() {
375
+ this.#push({ end: true });
376
+ }
377
+ pushCancel(reason) {
378
+ this.#cancelled = true;
379
+ this.#abort.abort();
380
+ this.#push({ cancel: { reason } });
381
+ }
382
+ #push(item) {
383
+ this.#buffer.push(item);
384
+ const w = this.#waker;
385
+ this.#waker = null;
386
+ w?.();
387
+ }
388
+ /**
389
+ * Request body bytes, yielded as they arrive. A cancel frame surfaces as a
390
+ * thrown error so the handler's upstream call is torn down.
391
+ */
392
+ get requestBody() {
393
+ return {
394
+ [Symbol.asyncIterator]: () => ({
395
+ next: async () => {
396
+ if (this.#drained) {
397
+ return { value: void 0, done: true };
398
+ }
399
+ while (this.#buffer.length === 0) {
400
+ await new Promise((resolve) => {
401
+ this.#waker = resolve;
402
+ });
403
+ }
404
+ const item = this.#buffer.shift();
405
+ if (item.cancel) {
406
+ this.#drained = true;
407
+ throw new Error(
408
+ item.cancel.reason ? `Request cancelled by runtime: ${item.cancel.reason}` : "Request cancelled by runtime"
409
+ );
410
+ }
411
+ if (item.end) {
412
+ this.#drained = true;
413
+ return { value: void 0, done: true };
414
+ }
415
+ return { value: item, done: false };
416
+ }
417
+ })
418
+ };
419
+ }
420
+ // --- Response emit (driven by the handler). Strict state machine: ---
421
+ // startResponse once -> 0..N writeResponse -> exactly one of
422
+ // endResponse / errorResponse.
423
+ async startResponse(init) {
424
+ if (this.#started) {
425
+ throw new Error("Copilot request response start() called twice.");
426
+ }
427
+ if (this.#finished) {
428
+ throw new Error("Copilot request response already finished.");
429
+ }
430
+ this.#started = true;
431
+ await this.#rpc().llmInference.httpResponseStart({
432
+ requestId: this.requestId,
433
+ status: init.status,
434
+ statusText: init.statusText,
435
+ headers: init.headers ?? {}
436
+ });
437
+ }
438
+ async writeResponse(data) {
439
+ if (this.#cancelled) {
440
+ throw new Error("Copilot request was cancelled by the runtime.");
441
+ }
442
+ if (!this.#started) {
443
+ throw new Error("Copilot request response write() called before start().");
444
+ }
445
+ if (this.#finished) {
446
+ throw new Error("Copilot request response write() called after end()/error().");
447
+ }
448
+ const isString = typeof data === "string";
449
+ await this.#rpc().llmInference.httpResponseChunk({
450
+ requestId: this.requestId,
451
+ data: isString ? data : Buffer.from(data).toString("base64"),
452
+ binary: !isString,
453
+ end: false
454
+ });
455
+ }
456
+ async endResponse() {
457
+ if (this.#finished) {
458
+ return;
459
+ }
460
+ this.#finished = true;
461
+ await this.#rpc().llmInference.httpResponseChunk({
462
+ requestId: this.requestId,
463
+ data: "",
464
+ end: true
465
+ });
466
+ }
467
+ async errorResponse(error) {
468
+ if (this.#finished) {
469
+ return;
470
+ }
471
+ this.#finished = true;
472
+ await this.#rpc().llmInference.httpResponseChunk({
473
+ requestId: this.requestId,
474
+ data: "",
475
+ end: true,
476
+ error: { message: error.message, code: error.code }
477
+ });
478
+ }
479
+ #rpc() {
480
+ const r = this.#getServerRpc();
481
+ if (!r) {
482
+ throw new Error("Copilot request response used after RPC connection closed.");
483
+ }
484
+ return r;
485
+ }
486
+ }
487
+ const FORBIDDEN_REQUEST_HEADERS = /* @__PURE__ */ new Set([
488
+ "host",
489
+ "connection",
490
+ "content-length",
491
+ "transfer-encoding",
492
+ "keep-alive",
493
+ "upgrade",
494
+ "proxy-connection",
495
+ "te",
496
+ "trailer"
497
+ ]);
498
+ function forwardedRequestHeaders(source) {
499
+ const headers = new Headers();
500
+ for (const [name, values] of Object.entries(source)) {
501
+ if (!values) {
502
+ continue;
503
+ }
504
+ const lower = name.toLowerCase();
505
+ if (FORBIDDEN_REQUEST_HEADERS.has(lower) || lower.startsWith("sec-websocket-")) {
506
+ continue;
507
+ }
508
+ for (const value of values) {
509
+ headers.append(name, value);
510
+ }
511
+ }
512
+ return headers;
513
+ }
514
+ async function buildFetchRequest(exchange) {
515
+ const headers = forwardedRequestHeaders(exchange.headers);
516
+ const method = exchange.method.toUpperCase();
517
+ const hasBody = method !== "GET" && method !== "HEAD";
518
+ let body;
519
+ if (hasBody) {
520
+ const buffered = await drainAsync(exchange.requestBody);
521
+ if (buffered.length > 0) {
522
+ body = buffered;
523
+ }
524
+ } else {
525
+ await drainAsync(exchange.requestBody);
526
+ }
527
+ return new Request(exchange.url, { method, headers, body });
528
+ }
529
+ async function drainAsync(stream) {
530
+ const parts = [];
531
+ let total = 0;
532
+ for await (const item of stream) {
533
+ if (item.chunk) {
534
+ parts.push(item.chunk);
535
+ total += item.chunk.byteLength;
536
+ }
537
+ }
538
+ if (parts.length === 0) {
539
+ return new Uint8Array(0);
540
+ }
541
+ if (parts.length === 1) {
542
+ return parts[0];
543
+ }
544
+ const out = new Uint8Array(total);
545
+ let off = 0;
546
+ for (const part of parts) {
547
+ out.set(part, off);
548
+ off += part.byteLength;
549
+ }
550
+ return out;
551
+ }
552
+ async function streamResponse(response, exchange) {
553
+ const reader = response.body ? new HttpResponseReader(response.body, exchange.signal) : void 0;
554
+ try {
555
+ await exchange.startResponse({
556
+ status: response.status,
557
+ statusText: response.statusText || void 0,
558
+ headers: headersToMultiMap(response.headers)
559
+ });
560
+ if (reader) {
561
+ for (; ; ) {
562
+ const chunk = await reader.nextChunk();
563
+ if (!chunk) {
564
+ break;
565
+ }
566
+ await exchange.writeResponse(chunk);
567
+ }
568
+ }
569
+ await exchange.endResponse();
570
+ } finally {
571
+ await reader?.dispose();
572
+ }
573
+ }
574
+ class HttpResponseReader {
575
+ #reader;
576
+ #signal;
577
+ #frames = [];
578
+ #pump;
579
+ #onAbort;
580
+ #queued = 0;
581
+ #done = false;
582
+ #cancelled = false;
583
+ #hasError = false;
584
+ #error;
585
+ #dataWaker;
586
+ #spaceWaker;
587
+ #cancelPromise;
588
+ constructor(body, signal) {
589
+ this.#reader = body.getReader();
590
+ this.#signal = signal;
591
+ this.#onAbort = () => {
592
+ void this.cancel(signal.reason);
593
+ };
594
+ signal.addEventListener("abort", this.#onAbort, { once: true });
595
+ this.#pump = this.#pumpSource();
596
+ if (signal.aborted) {
597
+ this.#onAbort();
598
+ }
599
+ }
600
+ async nextChunk() {
601
+ while (this.#frames.length === 0 && !this.#done && !this.#hasError) {
602
+ await new Promise((resolve) => {
603
+ this.#dataWaker = resolve;
604
+ });
605
+ }
606
+ if (this.#frames.length > 0) {
607
+ const chunk = this.#takeQueued();
608
+ this.#wakeSpace();
609
+ return chunk;
610
+ }
611
+ if (this.#hasError) {
612
+ this.#hasError = false;
613
+ throw this.#error;
614
+ }
615
+ return void 0;
616
+ }
617
+ #takeQueued() {
618
+ const frames = this.#frames;
619
+ const total = this.#queued;
620
+ this.#queued = 0;
621
+ if (frames.length === 1) {
622
+ return frames.pop();
623
+ }
624
+ const chunk = new Uint8Array(total);
625
+ let offset = 0;
626
+ for (const frame of frames) {
627
+ chunk.set(frame, offset);
628
+ offset += frame.byteLength;
629
+ }
630
+ frames.length = 0;
631
+ return chunk;
632
+ }
633
+ async dispose() {
634
+ this.#signal.removeEventListener("abort", this.#onAbort);
635
+ if (!this.#done) {
636
+ await this.cancel();
637
+ } else if (this.#cancelPromise) {
638
+ await this.#cancelPromise;
639
+ }
640
+ await this.#pump;
641
+ }
642
+ cancel(reason) {
643
+ if (this.#done) {
644
+ return Promise.resolve();
645
+ }
646
+ if (!this.#cancelPromise) {
647
+ this.#cancelled = true;
648
+ this.#done = true;
649
+ this.#hasError = true;
650
+ this.#error = reason instanceof Error ? reason : new Error("HTTP response body cancelled.");
651
+ this.#frames.length = 0;
652
+ this.#queued = 0;
653
+ this.#wakeData();
654
+ this.#wakeSpace();
655
+ this.#cancelPromise = this.#reader.cancel(reason).catch(() => void 0);
656
+ }
657
+ return this.#cancelPromise;
658
+ }
659
+ async #pumpSource() {
660
+ try {
661
+ while (!this.#cancelled) {
662
+ while (this.#queued >= HTTP_RESPONSE_READ_AHEAD_BYTES && !this.#cancelled) {
663
+ await new Promise((resolve) => {
664
+ this.#spaceWaker = resolve;
665
+ });
666
+ }
667
+ if (this.#cancelled) {
668
+ return;
669
+ }
670
+ const { value, done } = await this.#reader.read();
671
+ if (done) {
672
+ return;
673
+ }
674
+ if (value.byteLength > 0) {
675
+ this.#frames.push(value);
676
+ this.#queued += value.byteLength;
677
+ this.#wakeData();
678
+ continue;
679
+ }
680
+ await new Promise((resolve) => setImmediate(resolve));
681
+ }
682
+ } catch (error) {
683
+ if (!this.#cancelled) {
684
+ this.#hasError = true;
685
+ this.#error = error;
686
+ }
687
+ } finally {
688
+ this.#done = true;
689
+ this.#wakeData();
690
+ this.#wakeSpace();
691
+ this.#reader.releaseLock();
692
+ }
693
+ }
694
+ #wakeData() {
695
+ const waker = this.#dataWaker;
696
+ this.#dataWaker = void 0;
697
+ waker?.();
698
+ }
699
+ #wakeSpace() {
700
+ const waker = this.#spaceWaker;
701
+ this.#spaceWaker = void 0;
702
+ waker?.();
703
+ }
704
+ }
705
+ function headersToMultiMap(headers) {
706
+ const out = {};
707
+ headers.forEach((value, name) => {
708
+ if (name.toLowerCase() === "set-cookie") {
709
+ return;
710
+ }
711
+ const list = out[name] ?? (out[name] = []);
712
+ list.push(value);
713
+ });
714
+ const setCookies = headers.getSetCookie();
715
+ if (setCookies.length > 0) {
716
+ out["set-cookie"] = setCookies;
717
+ }
718
+ return out;
719
+ }
720
+ function decodeChunkData(data, binary) {
721
+ if (binary) {
722
+ return new Uint8Array(Buffer.from(data, "base64"));
723
+ }
724
+ return sharedTextEncoder.encode(data);
725
+ }
726
+ function decodeFrame(chunk) {
727
+ return sharedTextDecoder.decode(chunk);
728
+ }
729
+ function normalizeWsData(data) {
730
+ if (typeof data === "string") {
731
+ return data;
732
+ }
733
+ if (data instanceof Uint8Array) {
734
+ return data;
735
+ }
736
+ if (data instanceof ArrayBuffer) {
737
+ return new Uint8Array(data);
738
+ }
739
+ return new Uint8Array();
740
+ }
741
+ class CopilotWebSocketResponseBridge {
742
+ #exchange;
743
+ #started = false;
744
+ #completed = false;
745
+ #serial = Promise.resolve();
746
+ constructor(exchange) {
747
+ this.#exchange = exchange;
748
+ }
749
+ /** Emit the 101 upgrade head now, acknowledging the WebSocket connect. */
750
+ start() {
751
+ return this.#run(false, () => Promise.resolve());
752
+ }
753
+ write(data) {
754
+ return this.#run(false, () => this.#exchange.writeResponse(data));
755
+ }
756
+ end() {
757
+ return this.#run(true, () => this.#exchange.endResponse());
758
+ }
759
+ error(error) {
760
+ return this.#run(true, () => this.#exchange.errorResponse(error));
761
+ }
762
+ #run(terminal, action) {
763
+ const task = this.#serial.then(async () => {
764
+ if (this.#completed) {
765
+ return;
766
+ }
767
+ if (!this.#started) {
768
+ this.#started = true;
769
+ await this.#exchange.startResponse({ status: 101, headers: {} });
770
+ }
771
+ if (terminal) {
772
+ this.#completed = true;
773
+ }
774
+ await action();
775
+ });
776
+ this.#serial = task.catch(() => {
777
+ });
778
+ return task;
779
+ }
780
+ }
781
+ export {
782
+ CopilotRequestHandler,
783
+ CopilotWebSocketCloseStatus,
784
+ CopilotWebSocketForwarder,
785
+ CopilotWebSocketHandler,
786
+ createCopilotRequestAdapter
787
+ };