// Record and replay (lab 11). // // RecordingModel wraps a real model client and appends every request and response to a JSON // Lines file. ReplayModel reads that file and returns the same responses, in order, with no // network and no cost. Together they turn one real conversation into a repeatable test fixture: // // STEWARD_RECORD=fixtures/quiz.jsonl pnpm steward chat # record once, with the real API // new ReplayModel(await loadRecording('fixtures/quiz.jsonl')) # replay in tests, forever // // Replay checks that the conversation did not drift: if your code now sends a different number // of messages than when the fixture was recorded, it fails loudly instead of returning answers // to questions that were never asked. import { appendFile, mkdir, readFile } from 'node:fs/promises'; import path from 'node:path'; import type { BetaMessage, ModelCallOptions, ModelClient, ModelRequest } from './model.ts'; export interface RecordedCall { request: ModelRequest; response: BetaMessage; } export class RecordingModel implements ModelClient { readonly model: string; private readonly inner: ModelClient; private readonly file: string; constructor(inner: ModelClient, file: string) { this.inner = inner; this.file = file; this.model = inner.model; } async complete(request: ModelRequest, options?: ModelCallOptions): Promise { const response = await this.inner.complete(request, options); await mkdir(path.dirname(path.resolve(this.file)), { recursive: true }); const call: RecordedCall = { request, response }; await appendFile(this.file, JSON.stringify(call) + '\n', 'utf8'); return response; } } export async function loadRecording(file: string): Promise { const text = await readFile(file, 'utf8'); return text .split('\n') .filter((line) => line.trim()) .map((line) => JSON.parse(line) as RecordedCall); } export class ReplayModel implements ModelClient { readonly model: string; private readonly calls: RecordedCall[]; private index = 0; constructor(calls: RecordedCall[]) { this.calls = calls; this.model = calls[0]?.response.model ?? 'replay'; } async complete(request: ModelRequest, options: ModelCallOptions = {}): Promise { const call = this.calls[this.index]; if (!call) throw new Error(`replay: no recorded response for call ${this.index + 1}`); if (call.request.messages.length !== request.messages.length) { throw new Error( `replay diverged at call ${this.index + 1}: recorded ${call.request.messages.length} ` + `messages, now ${request.messages.length}`, ); } this.index++; for (const block of call.response.content) { if (block.type === 'text') options.onText?.(block.text); } return call.response; } get remaining(): number { return this.calls.length - this.index; } }