forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvcr.ts
More file actions
406 lines (376 loc) · 11.9 KB
/
vcr.ts
File metadata and controls
406 lines (376 loc) · 11.9 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
import type { BetaContentBlock } from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs'
import { createHash, randomUUID, type UUID } from 'crypto'
import { mkdir, readFile, writeFile } from 'fs/promises'
import isPlainObject from 'lodash-es/isPlainObject.js'
import mapValues from 'lodash-es/mapValues.js'
import { dirname, join } from 'path'
import { addToTotalSessionCost } from 'src/cost-tracker.js'
import { calculateUSDCost } from 'src/utils/modelCost.js'
import type {
AssistantMessage,
Message,
StreamEvent,
SystemAPIErrorMessage,
UserMessage,
} from '../types/message.js'
import { getCwd } from '../utils/cwd.js'
import { env } from '../utils/env.js'
import { getClaudeConfigHomeDir, isEnvTruthy } from '../utils/envUtils.js'
import { getErrnoCode } from '../utils/errors.js'
import { normalizeMessagesForAPI } from '../utils/messages.js'
import { jsonParse, jsonStringify } from '../utils/slowOperations.js'
function shouldUseVCR(): boolean {
if (process.env.NODE_ENV === 'test') {
return true
}
if (process.env.USER_TYPE === 'ant' && isEnvTruthy(process.env.FORCE_VCR)) {
return true
}
return false
}
/**
* Generic fixture management helper
* Handles caching, reading, writing fixtures for any data type
*/
async function withFixture<T>(
input: unknown,
fixtureName: string,
f: () => Promise<T>,
): Promise<T> {
if (!shouldUseVCR()) {
return await f()
}
// Create hash of input for fixture filename
const hash = createHash('sha1')
.update(jsonStringify(input))
.digest('hex')
.slice(0, 12)
const filename = join(
process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT ?? getCwd(),
`fixtures/${fixtureName}-${hash}.json`,
)
// Fetch cached fixture
try {
const cached = jsonParse(
await readFile(filename, { encoding: 'utf8' }),
) as T
return cached
} catch (e: unknown) {
const code = getErrnoCode(e)
if (code !== 'ENOENT') {
throw e
}
}
if ((env.isCI || process.env.CI) && !isEnvTruthy(process.env.VCR_RECORD)) {
throw new Error(
`Fixture missing: ${filename}. Re-run tests with VCR_RECORD=1, then commit the result.`,
)
}
// Create & write new fixture
const result = await f()
await mkdir(dirname(filename), { recursive: true })
await writeFile(filename, jsonStringify(result, null, 2), {
encoding: 'utf8',
})
return result
}
export async function withVCR(
messages: Message[],
f: () => Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]>,
): Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]> {
if (!shouldUseVCR()) {
return await f()
}
const messagesForAPI = normalizeMessagesForAPI(
messages.filter(_ => {
if (_.type !== 'user') {
return true
}
if (_.isMeta) {
return false
}
return true
}),
)
const dehydratedInput = mapMessages(
messagesForAPI.map(_ => _.message.content),
dehydrateValue,
)
const filename = join(
process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT ?? getCwd(),
`fixtures/${dehydratedInput.map(_ => createHash('sha1').update(jsonStringify(_)).digest('hex').slice(0, 6)).join('-')}.json`,
)
// Fetch cached fixture
try {
const cached = jsonParse(
await readFile(filename, { encoding: 'utf8' }),
) as { output: (AssistantMessage | StreamEvent)[] }
cached.output.forEach(addCachedCostToTotalSessionCost)
return cached.output.map((message, index) =>
mapMessage(message, hydrateValue, index, randomUUID()),
)
} catch (e: unknown) {
const code = getErrnoCode(e)
if (code !== 'ENOENT') {
throw e
}
}
if (env.isCI && !isEnvTruthy(process.env.VCR_RECORD)) {
throw new Error(
`Anthropic API fixture missing: ${filename}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:\n${jsonStringify(dehydratedInput, null, 2)}`,
)
}
// Create & write new fixture
const results = await f()
if (env.isCI && !isEnvTruthy(process.env.VCR_RECORD)) {
return results
}
await mkdir(dirname(filename), { recursive: true })
await writeFile(
filename,
jsonStringify(
{
input: dehydratedInput,
output: results.map((message, index) =>
mapMessage(message, dehydrateValue, index),
),
},
null,
2,
),
{ encoding: 'utf8' },
)
return results
}
function addCachedCostToTotalSessionCost(
message: AssistantMessage | StreamEvent,
): void {
if (message.type === 'stream_event') {
return
}
const model = message.message.model
const usage = message.message.usage
const costUSD = calculateUSDCost(model, usage)
addToTotalSessionCost(costUSD, usage, model)
}
function mapMessages(
messages: (UserMessage | AssistantMessage)['message']['content'][],
f: (s: unknown) => unknown,
): (UserMessage | AssistantMessage)['message']['content'][] {
return messages.map(_ => {
if (typeof _ === 'string') {
return f(_)
}
return _.map(_ => {
switch (_.type) {
case 'tool_result':
if (typeof _.content === 'string') {
return { ..._, content: f(_.content) }
}
if (Array.isArray(_.content)) {
return {
..._,
content: _.content.map(_ => {
switch (_.type) {
case 'text':
return { ..._, text: f(_.text) }
case 'image':
return _
default:
return undefined
}
}),
}
}
return _
case 'text':
return { ..._, text: f(_.text) }
case 'tool_use':
return {
..._,
input: mapValuesDeep(_.input as Record<string, unknown>, f),
}
case 'image':
return _
default:
return undefined
}
})
}) as (UserMessage | AssistantMessage)['message']['content'][]
}
function mapValuesDeep(
obj: {
[x: string]: unknown
},
f: (val: unknown, key: string, obj: Record<string, unknown>) => unknown,
): Record<string, unknown> {
return mapValues(obj, (val, key) => {
if (Array.isArray(val)) {
return val.map(_ => mapValuesDeep(_, f))
}
if (isPlainObject(val)) {
return mapValuesDeep(val as Record<string, unknown>, f)
}
return f(val, key, obj)
})
}
function mapAssistantMessage(
message: AssistantMessage,
f: (s: unknown) => unknown,
index: number,
uuid?: UUID,
): AssistantMessage {
return {
// Use provided UUID if given (hydrate path uses randomUUID for globally unique IDs),
// otherwise fall back to deterministic index-based UUID (dehydrate/fixture path).
// sessionStorage.ts deduplicates messages by UUID, so without unique UUIDs across
// VCR calls, resumed sessions would treat different responses as duplicates.
uuid: uuid ?? (`UUID-${index}` as unknown as UUID),
requestId: 'REQUEST_ID',
timestamp: message.timestamp,
message: {
...message.message,
content: message.message.content
.map(_ => {
switch (_.type) {
case 'text':
return {
..._,
text: f(_.text) as string,
citations: _.citations || [],
} // Ensure citations
case 'tool_use':
return {
..._,
input: mapValuesDeep(_.input as Record<string, unknown>, f),
}
default:
return _ // Handle other block types unchanged
}
})
.filter(Boolean) as BetaContentBlock[],
},
type: 'assistant',
}
}
function mapMessage(
message: AssistantMessage | SystemAPIErrorMessage | StreamEvent,
f: (s: unknown) => unknown,
index: number,
uuid?: UUID,
): AssistantMessage | SystemAPIErrorMessage | StreamEvent {
if (message.type === 'assistant') {
return mapAssistantMessage(message, f, index, uuid)
} else {
return message
}
}
function dehydrateValue(s: unknown): unknown {
if (typeof s !== 'string') {
return s
}
const cwd = getCwd()
const configHome = getClaudeConfigHomeDir()
let s1 = s
.replace(/num_files="\d+"/g, 'num_files="[NUM]"')
.replace(/duration_ms="\d+"/g, 'duration_ms="[DURATION]"')
.replace(/cost_usd="\d+"/g, 'cost_usd="[COST]"')
// Note: We intentionally don't replace all forward slashes with path.sep here.
// That would corrupt XML-like tags (e.g., </system-reminder> -> <\system-reminder>).
// The [CONFIG_HOME] and [CWD] replacements below handle path normalization.
.replaceAll(configHome, '[CONFIG_HOME]')
.replaceAll(cwd, '[CWD]')
.replace(/Available commands:.+/, 'Available commands: [COMMANDS]')
// On Windows, paths may appear in multiple forms:
// 1. Forward-slash variants (Git, some Node APIs)
// 2. JSON-escaped variants (backslashes doubled in serialized JSON within messages)
if (process.platform === 'win32') {
const cwdFwd = cwd.replaceAll('\\', '/')
const configHomeFwd = configHome.replaceAll('\\', '/')
// jsonStringify escapes \ to \\ - match paths embedded in JSON strings
const cwdJsonEscaped = jsonStringify(cwd).slice(1, -1)
const configHomeJsonEscaped = jsonStringify(configHome).slice(1, -1)
s1 = s1
.replaceAll(cwdJsonEscaped, '[CWD]')
.replaceAll(configHomeJsonEscaped, '[CONFIG_HOME]')
.replaceAll(cwdFwd, '[CWD]')
.replaceAll(configHomeFwd, '[CONFIG_HOME]')
}
// Normalize backslash path separators after placeholders so VCR fixture
// hashes match across platforms (e.g., [CWD]\foo\bar -> [CWD]/foo/bar)
// Handle both single backslashes and JSON-escaped double backslashes (\\)
s1 = s1
.replace(/\[CWD\][^\s"'<>]*/g, match =>
match.replaceAll('\\\\', '/').replaceAll('\\', '/'),
)
.replace(/\[CONFIG_HOME\][^\s"'<>]*/g, match =>
match.replaceAll('\\\\', '/').replaceAll('\\', '/'),
)
if (s1.includes('Files modified by user:')) {
return 'Files modified by user: [FILES]'
}
return s1
}
function hydrateValue(s: unknown): unknown {
if (typeof s !== 'string') {
return s
}
return s
.replaceAll('[NUM]', '1')
.replaceAll('[DURATION]', '100')
.replaceAll('[CONFIG_HOME]', getClaudeConfigHomeDir())
.replaceAll('[CWD]', getCwd())
}
export async function* withStreamingVCR(
messages: Message[],
f: () => AsyncGenerator<
StreamEvent | AssistantMessage | SystemAPIErrorMessage,
void
>,
): AsyncGenerator<
StreamEvent | AssistantMessage | SystemAPIErrorMessage,
void
> {
if (!shouldUseVCR()) {
return yield* f()
}
// Compute and yield messages
const buffer: (StreamEvent | AssistantMessage | SystemAPIErrorMessage)[] = []
// Record messages (or fetch from cache)
const cachedBuffer = await withVCR(messages, async () => {
for await (const message of f()) {
buffer.push(message)
}
return buffer
})
if (cachedBuffer.length > 0) {
yield* cachedBuffer
return
}
yield* buffer
}
export async function withTokenCountVCR(
messages: unknown[],
tools: unknown[],
f: () => Promise<number | null>,
): Promise<number | null> {
// Dehydrate before hashing so fixture keys survive cwd/config-home/tempdir
// variation and message UUID/timestamp churn. System prompts embed the
// working directory (both raw and as a slash→dash project slug in the
// auto-memory path) and messages carry fresh UUIDs per run; without this,
// every test run produces a new hash and fixtures never hit in CI.
const cwdSlug = getCwd().replace(/[^a-zA-Z0-9]/g, '-')
const dehydrated = (
dehydrateValue(jsonStringify({ messages, tools })) as string
)
.replaceAll(cwdSlug, '[CWD_SLUG]')
.replace(
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
'[UUID]',
)
.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z?/g, '[TIMESTAMP]')
const result = await withFixture(dehydrated, 'token-count', async () => ({
tokenCount: await f(),
}))
return result.tokenCount
}