-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathreplayingCapiProxy.ts
More file actions
1603 lines (1463 loc) · 53.8 KB
/
Copy pathreplayingCapiProxy.ts
File metadata and controls
1603 lines (1463 loc) · 53.8 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.
*--------------------------------------------------------------------------------------------*/
import { existsSync, appendFileSync } from "fs";
import { mkdir, readFile, writeFile } from "fs/promises";
import type {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsBase,
ChatCompletionMessageFunctionToolCall,
ChatCompletionMessageParam,
} from "openai/resources/chat/completions";
import { ChatCompletionStream } from "openai/resources/chat/completions";
import path from "path";
import yaml from "yaml";
import {
CapturedExchange,
CapturingHttpProxy,
PerformRequestOptions,
} from "./capturingHttpProxy";
import { iife, ShellConfig, sleep } from "./util";
export const workingDirPlaceholder = "${workdir}";
const chatCompletionEndpoint = "/chat/completions";
const shellConfig =
process.platform === "win32" ? ShellConfig.powerShell : ShellConfig.bash;
const normalizedToolNames: Record<string, string> = {
[shellConfig.shellToolName]: "${shell}",
[shellConfig.readShellToolName]: "${read_shell}",
[shellConfig.writeShellToolName]: "${write_shell}",
};
/**
* Default model to use when no stored data is available for a given test.
* This enables responding to /models without needing to have a capture file.
*/
const defaultModel = "claude-sonnet-4.5";
/**
* An HTTP proxy that not only captures HTTP exchanges, but also stores them in a file on disk and
* replays the stored responses on subsequent runs.
*
* This only stores and matches CAPI-provided OpenAI chat completions, not arbitrary HTTP traffic, since
* the core idea is to store and compare in a normalized form that (1) ignores irrelevant differences (like
* timestamps, or references to your working directory path) and (2) writes data files in a simple,
* human-readable format where it's easy to reason about diffs when things change.
*
* To avoid leaving stale files around as tests are modified, it stores things on a one-file-per-test basis,
* which is overwritten on each test run. So for as long as a test exists, its data will be kept up-to-date.
*/
export class ReplayingCapiProxy extends CapturingHttpProxy {
private state: ReplayingCapiProxyState | null = null;
private startPromise: Promise<string> | null = null;
private defaultToolResultNormalizers: ToolResultNormalizer[] = [
{ toolName: "*", normalizer: normalizeLargeOutputFilepaths },
{ toolName: "${shell}", normalizer: normalizeShellExitMarkers },
{ toolName: "*", normalizer: normalizeGhAuthMessages },
{ toolName: "*", normalizer: normalizeAvailableToolNames },
{ toolName: "read_agent", normalizer: normalizeReadAgentTimings },
];
/**
* Per-token responses for `/copilot_internal/user` endpoint.
* Key is the Bearer token (without "Bearer " prefix), value is the response body.
* When a request arrives with `Authorization: Bearer <token>`, the matching response is returned.
* If no match is found, a 401 Unauthorized response is returned.
*/
private copilotUserByToken = new Map<string, CopilotUserResponse>();
/**
* If true, cached responses are played back slowly (~ 2KiB/sec). Otherwise streaming responses are sent as fast as possible.
*/
slowStreaming = false;
onStopRequested?: (skipWritingCache: boolean) => Promise<void> | void;
constructor(
targetUrl: string,
filePath?: string,
workDir?: string,
testInfo?: { file: string; line?: number },
) {
super(targetUrl);
// If the instantiator wants to supply config up front as ctor params, we can
// skip the need to do a /config POST before other requests. This only makes
// sense if the config will be static for the lifetime of the proxy.
if (filePath && workDir) {
this.state = {
filePath,
workDir,
testInfo,
toolResultNormalizers: [...this.defaultToolResultNormalizers],
};
}
}
async start(): Promise<string> {
return (this.startPromise ??= (async () => {
await this.loadStoredData();
return super.start();
})());
}
async updateConfig(config: Partial<ReplayingCapiProxyState>): Promise<void> {
if (!config.filePath || !config.workDir) {
throw new Error("filePath and workDir must be provided in config");
}
// Since we're about to switch to a new file, write out any captured exchanges
// Note that the final call to stop() will also write out any remaining exchanges.
// In CI mode (GITHUB_ACTIONS=true) we never write — the snapshots are read-only.
// Otherwise tests that exercise only a subset of a multi-conversation snapshot
// would silently overwrite the file with that subset, breaking subsequent runs.
if (this.state && process.env.GITHUB_ACTIONS !== "true") {
await writeCapturesToDisk(this.exchanges, this.state);
}
this.state = {
filePath: config.filePath,
workDir: config.workDir,
testInfo: config.testInfo,
toolResultNormalizers: [...this.defaultToolResultNormalizers],
};
this.clearExchanges();
await this.loadStoredData();
}
private async loadStoredData(): Promise<void> {
if (this.state && existsSync(this.state.filePath)) {
const content = await readFile(this.state.filePath, "utf-8");
this.state.storedData = yaml.parse(content) as NormalizedData;
normalizeToolResultOrder(this.state.storedData.conversations);
normalizeStoredUserMessages(this.state.storedData.conversations);
}
}
async stop(skipWritingCache?: boolean): Promise<void> {
await super.stop();
// In CI mode we never write — the snapshots are read-only.
if (
this.state &&
!skipWritingCache &&
process.env.GITHUB_ACTIONS !== "true"
) {
await writeCapturesToDisk(this.exchanges, this.state);
}
}
addToolResultNormalizer(
toolName: string,
normalizer: (result: string) => string,
) {
if (!this.state) {
throw new Error(
"ReplayingCapiProxy not yet initialized. Cannot add tool result normalizer.",
);
}
this.state.toolResultNormalizers.push({ toolName, normalizer });
}
/**
* Register a per-token response for the `/copilot_internal/user` endpoint.
* When a request with `Authorization: Bearer <token>` arrives, the matching response is returned.
*/
setCopilotUserByToken(token: string, response: CopilotUserResponse): void {
this.copilotUserByToken.set(token, response);
}
override performRequest(options: PerformRequestOptions): void {
void iife(async () => {
const commonResponseHeaders = {
"x-github-request-id": "some-request-id",
};
try {
// Handle /copilot-user-config endpoint for configuring per-token user responses
if (
options.requestOptions.path === "/copilot-user-config" &&
options.requestOptions.method === "POST"
) {
const config = JSON.parse(options.body!) as {
token: string;
response: CopilotUserResponse;
};
this.copilotUserByToken.set(config.token, config.response);
options.onResponseStart(200, {});
options.onResponseEnd();
return;
}
// Handle /config endpoint for updating proxy configuration
if (
options.requestOptions.path === "/config" &&
options.requestOptions.method === "POST"
) {
await this.updateConfig(JSON.parse(options.body!));
options.onResponseStart(200, {});
options.onResponseEnd();
return;
}
// Handle /stop endpoint for stopping the proxy
if (
options.requestOptions.path?.startsWith("/stop") &&
options.requestOptions.method === "POST"
) {
const skipWritingCache = options.requestOptions.path.includes(
"skipWritingCache=true",
);
options.onResponseStart(200, {});
options.onResponseEnd();
await this.onStopRequested?.(skipWritingCache);
await this.stop(skipWritingCache);
process.exit(0);
}
// Handle /exchanges endpoint for retrieving captured exchanges
if (
options.requestOptions.path === "/exchanges" &&
options.requestOptions.method === "GET"
) {
const chatCompletionExchanges = this.exchanges.filter(
(e) => e.request.url === chatCompletionEndpoint,
);
const parsedExchanges = await Promise.all(
chatCompletionExchanges.map((e) =>
parseHttpExchange(
e.request.body,
e.response?.body,
e.request.headers,
),
),
);
options.onResponseStart(200, {});
options.onData(Buffer.from(JSON.stringify(parsedExchanges)));
options.onResponseEnd();
return;
}
// Handle /copilot_internal/user endpoint for per-session auth.
// This must run before the state guard below: the CLI authenticates and
// calls /copilot_internal/user at startup, which can race ahead of the
// per-test POST /config (e.g. the Go harness spawns the CLI before the
// first ConfigureForTest). The response only depends on the token map,
// which is populated independently of `state`.
if (options.requestOptions.path === "/copilot_internal/user") {
const headers = options.requestOptions.headers;
const headerMap = headers as
| Record<string, string | string[] | number | undefined>
| undefined;
const rawAuthHeader = Array.isArray(headers)
? undefined
: (headerMap?.authorization ?? headerMap?.Authorization);
const authHeader = Array.isArray(rawAuthHeader)
? rawAuthHeader[0]
: typeof rawAuthHeader === "string"
? rawAuthHeader
: undefined;
const token = authHeader?.replace("Bearer ", "");
const registered = token
? this.copilotUserByToken.get(token)
: undefined;
// The CLI gates third-party MCP servers behind the copilot user's
// `is_mcp_enabled` flag (a null/missing value disables them). Default
// it to true so e2e MCP servers are enabled unless a test opts out.
const userResponse = registered
? ({ is_mcp_enabled: true, ...registered } as CopilotUserResponse)
: undefined;
if (userResponse) {
const headers = {
"content-type": "application/json",
...commonResponseHeaders,
};
options.onResponseStart(200, headers);
options.onData(Buffer.from(JSON.stringify(userResponse)));
options.onResponseEnd();
} else {
options.onResponseStart(401, commonResponseHeaders);
options.onData(
Buffer.from(JSON.stringify({ message: "Bad credentials" })),
);
options.onResponseEnd();
}
return;
}
const state = this.state;
if (!state) {
throw new Error(
"ReplayingCapiProxy not yet initialized. Either pass filePath and workDir to the constructor, " +
"or post configuration to /config before making other HTTP requests.",
);
}
// Handle /models endpoint
// Use stored models if available, otherwise use default model
if (options.requestOptions.path === "/models") {
const models =
state.storedData?.models && state.storedData.models.length > 0
? state.storedData.models
: [defaultModel];
const modelsResponse = createGetModelsResponse(models);
const body = JSON.stringify(modelsResponse);
const headers = {
"content-type": "application/json",
...commonResponseHeaders,
};
options.onResponseStart(200, headers);
options.onData(Buffer.from(body));
options.onResponseEnd();
return;
}
// Handle memory endpoints - return stub responses in tests
// Matches: /agents/*/memory/*/enabled, /agents/*/memory/*/recent, etc.
if (options.requestOptions.path?.match(/\/agents\/.*\/memory\//)) {
let body: string;
if (options.requestOptions.path.includes("/enabled")) {
body = JSON.stringify({ enabled: false });
} else if (options.requestOptions.path.includes("/recent")) {
body = JSON.stringify({ memories: [] });
} else {
body = JSON.stringify({});
}
const headers = {
"content-type": "application/json",
...commonResponseHeaders,
};
options.onResponseStart(200, headers);
options.onData(Buffer.from(body));
options.onResponseEnd();
return;
}
// Handle /chat/completions endpoint
if (
state.storedData &&
options.requestOptions.path === chatCompletionEndpoint &&
options.body
) {
const savedError = await findSavedChatCompletionError(
state.storedData,
options.body,
state.workDir,
state.toolResultNormalizers,
);
if (savedError) {
const headers = {
"content-type": "application/json",
...commonResponseHeaders,
...(savedError.retryAfterSeconds !== undefined
? { "retry-after": String(savedError.retryAfterSeconds) }
: {}),
};
options.onResponseStart(savedError.status, headers);
options.onData(
Buffer.from(
JSON.stringify({
error: {
message:
savedError.message ?? "Rate limited by test snapshot",
type: savedError.code ?? "rate_limited",
code: savedError.code ?? "rate_limited",
},
}),
),
);
options.onResponseEnd();
return;
}
const savedResponse = await findSavedChatCompletionResponse(
state.storedData,
options.body,
state.workDir,
state.toolResultNormalizers,
);
if (savedResponse) {
const streamingIsRequested =
options.body &&
(JSON.parse(options.body) as { stream?: boolean }).stream ===
true;
if (streamingIsRequested) {
const headers = {
"content-type": "text/event-stream",
...commonResponseHeaders,
};
options.onResponseStart(200, headers);
for (const chunk of convertToStreamingResponseChunks(
savedResponse,
)) {
options.onData(
Buffer.from(`data: ${JSON.stringify(chunk)}\n\n`),
);
if (this.slowStreaming) {
await sleep(100);
}
}
options.onData(Buffer.from("data: [DONE]\n\n"));
options.onResponseEnd();
} else {
const body = JSON.stringify(savedResponse);
const headers = {
"content-type": "application/json",
...commonResponseHeaders,
};
options.onResponseStart(200, headers);
options.onData(Buffer.from(body));
options.onResponseEnd();
}
return;
}
// Check if this request matches a snapshot with no response (e.g., timeout tests).
// If so, hang forever so the client-side timeout can trigger.
if (
await isRequestOnlySnapshot(
state.storedData,
options.body,
state.workDir,
state.toolResultNormalizers,
)
) {
const streamingIsRequested =
options.body &&
(JSON.parse(options.body) as { stream?: boolean }).stream ===
true;
const headers = {
"content-type": streamingIsRequested
? "text/event-stream"
: "application/json",
...commonResponseHeaders,
};
options.onResponseStart(200, headers);
// Never call onResponseEnd - hang indefinitely for timeout tests.
// Returning here keeps the HTTP response open without leaking a pending Promise.
return;
}
}
// Beyond this point, we're only going to be able to supply responses in CI if we have a snapshot,
// and we only store snapshots for chat completion. For anything else (e.g., custom-agents fetches),
// return 404 so the CLI treats them as unavailable instead of erroring.
if (options.requestOptions.path !== chatCompletionEndpoint) {
const headers = {
"content-type": "application/json",
"x-github-request-id": "proxy-not-found",
};
options.onResponseStart(404, headers);
options.onData(
Buffer.from(JSON.stringify({ error: "Not found by test proxy" })),
);
options.onResponseEnd();
return;
}
// Fallback to normal proxying if no cached response found
// This implicitly captures the new exchange too
const isCI = process.env.GITHUB_ACTIONS === "true";
if (isCI) {
await exitWithNoMatchingRequestError(
options,
state.testInfo,
state.workDir,
state.toolResultNormalizers,
state.storedData,
);
return;
}
super.performRequest(options);
} catch (err) {
options.onError(err as Error | string);
}
});
}
}
async function writeCapturesToDisk(
exchanges: readonly CapturedExchange[],
state: ReplayingCapiProxyState,
) {
const data = await transformHttpExchanges(
exchanges,
state.workDir,
state.toolResultNormalizers,
);
const preservedErrors = state.storedData?.errors;
if (preservedErrors && preservedErrors.length > 0) {
data.errors = preservedErrors;
data.models = [
...new Set([
...(state.storedData?.models ?? []),
...data.models,
...preservedErrors
.map((error) => error.model)
.filter((model): model is string => model !== undefined),
]),
];
}
if (data.conversations.length > 0) {
let yamlText = yaml.stringify(data, { lineWidth: 120 });
// We have to normalize line endings explicitly, because yaml.stringify uses Unix-style even on Windows,
// and Git will restore the files with CRLF on Windows so they will appear to be changed
if (process.platform === "win32") {
yamlText = yamlText.replace(/\r?\n/g, "\r\n");
}
await mkdir(path.dirname(state.filePath), { recursive: true });
await writeFileIfDifferent(state.filePath, yamlText);
}
}
/**
* Produces a human-readable explanation of why no stored conversation matched
* a given request. For each stored conversation it reports the first reason
* matching failed, mirroring the logic in {@link findAssistantIndexAfterPrefix}.
*/
function diagnoseMatchFailure(
requestMessages: NormalizedMessage[],
rawMessages: unknown[],
storedData: NormalizedData | undefined,
): string {
const lines: string[] = [];
lines.push(
`Request has ${requestMessages.length} normalized messages (${rawMessages.length} raw).`,
);
if (!storedData || storedData.conversations.length === 0) {
lines.push("No stored conversations to match against.");
return lines.join("\n");
}
for (let c = 0; c < storedData.conversations.length; c++) {
const saved = storedData.conversations[c].messages;
// Same check as findAssistantIndexAfterPrefix: request must be a strict prefix
if (requestMessages.length >= saved.length) {
lines.push(
`Conversation ${c} (${saved.length} messages): ` +
`skipped — request has ${requestMessages.length} messages, need fewer than ${saved.length}.`,
);
continue;
}
// Find the first message that doesn't match
let mismatchIndex = -1;
for (let i = 0; i < requestMessages.length; i++) {
if (JSON.stringify(requestMessages[i]) !== JSON.stringify(saved[i])) {
mismatchIndex = i;
break;
}
}
if (mismatchIndex >= 0) {
const raw =
mismatchIndex < rawMessages.length
? JSON.stringify(rawMessages[mismatchIndex]).slice(0, 300)
: "(no raw message)";
lines.push(
`Conversation ${c} (${saved.length} messages): mismatch at message ${mismatchIndex}:`,
` request: ${JSON.stringify(requestMessages[mismatchIndex]).slice(0, 200)}`,
` saved: ${JSON.stringify(saved[mismatchIndex]).slice(0, 200)}`,
` raw (pre-normalization): ${raw}`,
);
} else {
// Prefix matched, but the next saved message isn't an assistant turn
const nextRole =
saved[requestMessages.length]?.role ?? "(end of conversation)";
lines.push(
`Conversation ${c} (${saved.length} messages): ` +
`prefix matched, but next saved message is "${nextRole}" (need "assistant").`,
);
}
}
return lines.join("\n");
}
async function exitWithNoMatchingRequestError(
options: PerformRequestOptions,
testInfo: { file: string; line?: number } | undefined,
workDir: string,
toolResultNormalizers: ToolResultNormalizer[],
storedData?: NormalizedData,
) {
let diagnostics: string;
try {
const normalized = await parseAndNormalizeRequest(
options.body,
workDir,
toolResultNormalizers,
);
const requestMessages = normalized.conversations[0]?.messages ?? [];
let rawMessages: unknown[] = [];
try {
rawMessages =
(JSON.parse(options.body ?? "{}") as { messages?: unknown[] })
.messages ?? [];
} catch {
/* non-JSON body */
}
diagnostics = diagnoseMatchFailure(
requestMessages,
rawMessages,
storedData,
);
} catch (e) {
diagnostics = `(unable to parse request for diagnostics: ${e})`;
}
const errorMessage = `No cached response found for ${options.requestOptions.method} ${options.requestOptions.path}.\n${diagnostics}`;
// Format as GitHub Actions annotation when test location is available
const annotation = [
testInfo?.file ? `file=${testInfo.file}` : "",
typeof testInfo?.line === "number" ? `line=${testInfo.line}` : "",
]
.filter(Boolean)
.join(",");
process.stderr.write(
`::error${annotation ? ` ${annotation}` : ""}::${errorMessage}\n`,
);
options.onError(new Error(errorMessage));
}
async function findSavedChatCompletionResponse(
storedData: NormalizedData,
requestBody: string | undefined,
workDir: string,
toolResultNormalizers: ToolResultNormalizer[],
): Promise<ChatCompletion | undefined> {
// Normalize the incoming request the same way we normalize for caching
const normalized = await parseAndNormalizeRequest(
requestBody,
workDir,
toolResultNormalizers,
);
const requestMessages = normalized.conversations[0]?.messages ?? [];
const requestModel = normalized.models[0];
if (!requestModel) {
throw new Error("Unable to determine model from request");
}
// Now find a matching cached conversation (i.e., one for which this request is a prefix)
for (const conversation of storedData.conversations) {
const replyIndex = findAssistantIndexAfterPrefix(
requestMessages,
conversation.messages,
);
if (replyIndex !== undefined) {
return createOpenAIResponse(
requestModel,
conversation.messages,
replyIndex,
workDir,
);
}
}
return undefined;
}
async function findSavedChatCompletionError(
storedData: NormalizedData,
requestBody: string | undefined,
workDir: string,
toolResultNormalizers: ToolResultNormalizer[],
): Promise<NormalizedErrorResponse | undefined> {
const normalized = await parseAndNormalizeRequest(
requestBody,
workDir,
toolResultNormalizers,
);
const requestMessages = normalized.conversations[0]?.messages ?? [];
const requestModel = normalized.models[0];
for (const error of storedData.errors ?? []) {
if (error.model && error.model !== requestModel) {
continue;
}
if (
requestMessages.length === error.messages.length &&
requestMessages.every(
(msg, i) => JSON.stringify(msg) === JSON.stringify(error.messages[i]),
)
) {
return error;
}
}
return undefined;
}
// Checks if the request matches a snapshot that has no assistant response.
// This handles timeout test scenarios where the snapshot only records the request.
async function isRequestOnlySnapshot(
storedData: NormalizedData,
requestBody: string | undefined,
workDir: string,
toolResultNormalizers: ToolResultNormalizer[],
): Promise<boolean> {
const normalized = await parseAndNormalizeRequest(
requestBody,
workDir,
toolResultNormalizers,
);
const requestMessages = normalized.conversations[0]?.messages ?? [];
for (const conversation of storedData.conversations) {
if (
requestMessages.length === conversation.messages.length &&
requestMessages.every(
(msg, i) =>
JSON.stringify(msg) === JSON.stringify(conversation.messages[i]),
)
) {
return true;
}
}
return false;
}
async function parseAndNormalizeRequest(
requestBody: string | undefined,
workDir: string,
toolResultNormalizers: ToolResultNormalizer[],
) {
const fakeRequest = {
request: { url: chatCompletionEndpoint, body: requestBody },
} as CapturedExchange;
return await transformHttpExchanges(
[fakeRequest],
workDir,
toolResultNormalizers,
);
}
// Takes raw HTTP traffic and turns it into the normalized form that we store on disk
async function transformHttpExchanges(
httpExchanges: readonly CapturedExchange[],
workDir: string,
toolResultNormalizers: ToolResultNormalizer[],
): Promise<NormalizedData> {
const chatCompletionExchanges = httpExchanges
.filter((e) => e.request.url === chatCompletionEndpoint)
.filter(excludeFailedResponses);
const allTurns = await Promise.all(
chatCompletionExchanges.map((e) =>
transformHttpExchange(e.request.body, e.response?.body),
),
);
const dedupedExchanges = removePrefixConversations(
allTurns.map((t) => t.conversation),
);
const dedupedModels = new Set(
allTurns.map((t) => t.model ?? "").filter((m) => !!m),
);
normalizeToolCalls(dedupedExchanges, toolResultNormalizers);
normalizeToolResultOrder(dedupedExchanges);
normalizeFilenames(dedupedExchanges, workDir);
return { models: Array.from(dedupedModels), conversations: dedupedExchanges };
}
function normalizeFilenames(
conversations: NormalizedConversation[],
workDir: string,
): void {
// Replace occurrences of the workDir path with workingDirPlaceholder to avoid diffs due to different test run locations
// We do so case-insensitively and with both / and \ to cover different OSes
// We also normalize any slashes in the rest of the path (e.g., C:\my\workdir\path\to\file.txt -> ${workdir}/path/to/file.txt)
workDir = workDir.replace(/\\/g, "/").replace(/\/+$/, "");
const escaped = workDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const workDirPattern = new RegExp(
escaped.replace(/\//g, "[\\\\/]+") + "([\\\\/]+[^\\s\"'`,]*)?",
"gi",
);
const workDirReplacer = (_: string, rest?: string) =>
workingDirPlaceholder + (rest?.replace(/[\\/]+/g, "/") ?? "");
// Match non-rooted Windows paths like abc\def\something.ext and flip slashes to /
// We don't need to match absolute paths because the only legit ones should be inside workdir which
// is handled above. Plus there's nothing we could do to normalize them since we don't know their base.
const windowsFnPattern =
/(?<![a-zA-Z0-9_\\])([a-zA-Z0-9_.-]+(?:\\[a-zA-Z0-9_.-]+)+)/g;
const windowsFnReplacer = (_: string, path: string) =>
path.replace(/\\/g, "/");
for (const conv of conversations) {
for (const msg of conv.messages) {
if (msg.content) {
msg.content = msg.content.replace(workDirPattern, workDirReplacer);
msg.content = msg.content.replace(windowsFnPattern, windowsFnReplacer);
}
for (const tc of msg.tool_calls ?? []) {
if (tc.function?.arguments) {
tc.function.arguments = tc.function.arguments.replace(
workDirPattern,
workDirReplacer,
);
tc.function.arguments = tc.function.arguments.replace(
windowsFnPattern,
windowsFnReplacer,
);
}
}
}
}
}
function normalizeToolCalls(
conversations: NormalizedConversation[],
resultNormalizers: ToolResultNormalizer[],
) {
// We normalize:
// - Tool call IDs (mapping from tooluse_rjaaFdJRRhqAZevU_1aBSA etc to toolcall_0, toolcall_1, etc)
// - Tool names (e.g., bash/powershell -> ${shell})
// - Tool call results that may vary between execution environments
// This is so that we're not storing random or environment-specific data in snapshots, and so we can
// still match cached responses even if these details change.
for (const conv of conversations) {
const idMap = new Map<string, string>();
const precedingMessages: NormalizedMessage[] = [];
let counter = 0;
for (const msg of conv.messages) {
for (const tc of msg.tool_calls ?? []) {
// Normalize ID in tool calls
idMap.set(tc.id, (tc.id = idMap.get(tc.id) ?? `toolcall_${counter++}`));
// Normalize name
const originalToolName = tc.function?.name;
const normalizedToolName =
originalToolName && normalizedToolNames[originalToolName];
if (normalizedToolName) {
tc.function!.name = normalizedToolName;
}
}
if (msg.role === "tool" && msg.tool_call_id) {
// Normalize ID in tool results
msg.tool_call_id = idMap.get(msg.tool_call_id) ?? msg.tool_call_id;
// Normalize result
if (msg.content) {
const precedingToolCall = precedingMessages
.flatMap((m) => m.tool_calls ?? [])
.find((tc) => tc.id === msg.tool_call_id);
if (precedingToolCall) {
for (const normalizer of resultNormalizers) {
if (
precedingToolCall.function?.name === normalizer.toolName ||
normalizer.toolName === "*"
) {
msg.content = normalizer.normalizer(msg.content);
}
}
}
}
}
precedingMessages.push(msg);
}
}
}
function normalizeToolResultOrder(conversations: NormalizedConversation[]) {
for (const conv of conversations) {
for (let start = 0; start < conv.messages.length; ) {
if (conv.messages[start].role !== "tool") {
start++;
continue;
}
let end = start + 1;
while (end < conv.messages.length && conv.messages[end].role === "tool") {
end++;
}
conv.messages
.slice(start, end)
.sort(compareToolResultMessages)
.forEach((message, index) => {
conv.messages[start + index] = message;
});
start = end;
}
}
}
function compareToolResultMessages(
left: NormalizedMessage,
right: NormalizedMessage,
) {
return compareToolCallIds(left.tool_call_id, right.tool_call_id);
}
function compareToolCallIds(left?: string, right?: string) {
const leftNumber = parseNormalizedToolCallId(left);
const rightNumber = parseNormalizedToolCallId(right);
if (leftNumber !== undefined && rightNumber !== undefined) {
return leftNumber - rightNumber;
}
return (left ?? "").localeCompare(right ?? "");
}
function parseNormalizedToolCallId(id?: string) {
const match = id?.match(/^toolcall_(\d+)$/);
return match ? Number(match[1]) : undefined;
}
// As we capture LLM calls, we see:
// - Request A, response AB
// - Request ABC, response ABCD
// - Request ABCDE, response ABCDEF
// Among these, it's only necessary to keep the longest conversation (ABCDEF) since this contains all
// information from the shorter ones. Avoiding duplication makes it reasonable for humans to reason
// about diffs in the stored conversations when things change.
function removePrefixConversations(
conversations: NormalizedConversation[],
): NormalizedConversation[] {
const result = [...conversations];
for (let i = result.length - 1; i >= 0; i--) {
for (let j = i - 1; j >= 0; j--) {
if (isPrefix(result[j].messages, result[i].messages)) {
result.splice(j, 1);
i--; // adjust index since we removed an element before current position
}
}
}
return result;
}
function isPrefix(
shorter: NormalizedMessage[],
longer: NormalizedMessage[],
): boolean {
if (shorter.length >= longer.length) {
return false;
}
return shorter.every(
(msg, idx) => JSON.stringify(msg) === JSON.stringify(longer[idx]),
);
}
async function parseHttpExchange(
requestBody: string,
responseBody: string | undefined,
requestHeaders?: Record<string, string | string[] | undefined>,
): Promise<ParsedHttpExchange> {
const request = JSON.parse(requestBody) as ChatCompletionCreateParamsBase;
const response = await parseOpenAIResponse(responseBody);
return { request, response, requestHeaders };
}
// Converts a single HTTP exchange (request + response) into a normalized conversation
async function transformHttpExchange(
requestBody: string,
responseBody: string | undefined,
): Promise<{ conversation: NormalizedConversation; model?: string }> {
const { request, response } = await parseHttpExchange(
requestBody,
responseBody,
);
const messages = request.messages.map(transformOpenAIRequestMessage);
if (response?.choices?.length) {
messages.push(...transformOpenAIResponseChoice(response.choices));
}
return { conversation: { messages }, model: request.model };
}
// Transforms a single OpenAI-style outbound request message into normalized form
// We use this to look up whether we already have a cached response for it
function transformOpenAIRequestMessage(
m: ChatCompletionMessageParam,
): NormalizedMessage {
let content: string | undefined;
if (m.role === "system") {
// System message changes too often to include in snapshots - just store placeholder
content = "${system}";
} else if (m.role === "user" && typeof m.content === "string") {
content = normalizeUserMessage(m.content);
} else if (m.role === "user" && Array.isArray(m.content)) {
// Multimodal user messages have array content with text and image_url parts.
// Extract and normalize text parts; represent image_url parts as a stable marker.
const parts: string[] = [];
for (const part of m.content) {