@ai-changeguard/replay 0.0.0-stage → 0.1.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.
@@ -0,0 +1,606 @@
1
+ class Skip extends Error {
2
+ }
3
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4
+ const str = (v) => (typeof v === "string" ? v : undefined);
5
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() && Number.isFinite(Number(v)) ? Number(v) : undefined;
6
+ /** Values that are JSON written as a string (Helicone bodies, Langfuse I/O, span attributes). */
7
+ function parsed(v) {
8
+ if (typeof v !== "string")
9
+ return v;
10
+ const t = v.trim();
11
+ if (!(t.startsWith("{") || t.startsWith("[")))
12
+ return v;
13
+ try {
14
+ return JSON.parse(t);
15
+ }
16
+ catch {
17
+ return v;
18
+ }
19
+ }
20
+ /** Gemini writes schema types in capitals ("OBJECT"); JSON Schema and the replay checks use lower case. */
21
+ function normalizeSchema(schema) {
22
+ if (Array.isArray(schema))
23
+ return schema.map(normalizeSchema);
24
+ if (!isObj(schema))
25
+ return schema;
26
+ const out = {};
27
+ for (const [k, v] of Object.entries(schema)) {
28
+ if (k === "type")
29
+ out[k] = typeof v === "string" ? v.toLowerCase() : Array.isArray(v) ? v.map((t) => (typeof t === "string" ? t.toLowerCase() : t)) : v;
30
+ else if (k === "properties" && isObj(v))
31
+ out[k] = Object.fromEntries(Object.entries(v).map(([pk, pv]) => [pk, normalizeSchema(pv)]));
32
+ else if (k === "items" || k === "anyOf" || k === "oneOf" || k === "allOf")
33
+ out[k] = normalizeSchema(v);
34
+ else
35
+ out[k] = v;
36
+ }
37
+ return out;
38
+ }
39
+ // ---------- reading the file ----------
40
+ function parseFile(text) {
41
+ const trimmed = text.trim();
42
+ if (!trimmed)
43
+ return { values: [], badLines: 0 };
44
+ try {
45
+ return { values: [JSON.parse(trimmed)], badLines: 0 };
46
+ }
47
+ catch {
48
+ // JSONL
49
+ }
50
+ const values = [];
51
+ let badLines = 0;
52
+ for (const line of trimmed.split(/\r?\n/)) {
53
+ const l = line.trim();
54
+ if (!l)
55
+ continue;
56
+ try {
57
+ values.push(JSON.parse(l));
58
+ }
59
+ catch {
60
+ badLines++;
61
+ }
62
+ }
63
+ return { values, badLines };
64
+ }
65
+ /** An OpenAI Evals output item: one recorded call, whose "results" are grader scores, not more records. */
66
+ function isEvalItem(value) {
67
+ return isObj(value.sample) && Array.isArray(value.sample.input);
68
+ }
69
+ const CONTAINERS = ["data", "observations", "spans", "requests", "items", "records", "results", "rows", "generations"];
70
+ /** Flattens wrappers (arrays, OTLP resourceSpans, {data:[...]}, a trace with observations) into records. */
71
+ function records(value, out = []) {
72
+ if (Array.isArray(value)) {
73
+ for (const v of value)
74
+ records(v, out);
75
+ return out;
76
+ }
77
+ if (!isObj(value))
78
+ return out;
79
+ if (Array.isArray(value.resourceSpans)) {
80
+ for (const rs of value.resourceSpans) {
81
+ for (const ss of isObj(rs) && Array.isArray(rs.scopeSpans) ? rs.scopeSpans : [])
82
+ records(isObj(ss) ? ss.spans : [], out);
83
+ }
84
+ return out;
85
+ }
86
+ const container = CONTAINERS.find((k) => Array.isArray(value[k]) && value[k].some(isObj));
87
+ if (container && !isEvalItem(value) && !Array.isArray(value.messages) && !Array.isArray(value.contents)) {
88
+ records(value[container], out);
89
+ return out;
90
+ }
91
+ out.push(value);
92
+ return out;
93
+ }
94
+ // ---------- OpenTelemetry GenAI ----------
95
+ function otelValue(v) {
96
+ if (!isObj(v))
97
+ return v;
98
+ if ("stringValue" in v)
99
+ return v.stringValue;
100
+ if ("intValue" in v)
101
+ return num(v.intValue);
102
+ if ("doubleValue" in v)
103
+ return v.doubleValue;
104
+ if ("boolValue" in v)
105
+ return v.boolValue;
106
+ if (isObj(v.arrayValue) && Array.isArray(v.arrayValue.values))
107
+ return v.arrayValue.values.map(otelValue);
108
+ return v;
109
+ }
110
+ /** Span attributes as a flat map, from OTLP JSON ([{key, value}]) or an already flat object. */
111
+ function spanAttributes(record) {
112
+ const raw = record.attributes ?? record.span_attributes ?? record.spanAttributes;
113
+ if (Array.isArray(raw)) {
114
+ const map = {};
115
+ for (const a of raw)
116
+ if (isObj(a) && typeof a.key === "string")
117
+ map[a.key] = otelValue(a.value);
118
+ return map;
119
+ }
120
+ return isObj(raw) ? raw : null;
121
+ }
122
+ function partsText(parts, onOther) {
123
+ if (!Array.isArray(parts))
124
+ return "";
125
+ const texts = [];
126
+ for (const p of parts) {
127
+ if (!isObj(p))
128
+ continue;
129
+ if (p.type === "text" && typeof p.content === "string")
130
+ texts.push(p.content);
131
+ else if (typeof p.type === "string")
132
+ onOther(p.type);
133
+ }
134
+ return texts.join("\n");
135
+ }
136
+ function fromOtel(attrs) {
137
+ const input = parsed(attrs["gen_ai.input.messages"]);
138
+ const messages = [];
139
+ let system = "";
140
+ const refuse = (type) => {
141
+ if (type === "tool_call" || type === "tool_call_response")
142
+ throw new Skip("tool-call conversation");
143
+ if (type !== "reasoning")
144
+ throw new Skip("non-text content (images, files or audio)");
145
+ };
146
+ if (Array.isArray(input)) {
147
+ for (const m of input) {
148
+ if (!isObj(m))
149
+ continue;
150
+ const text = partsText(m.parts, refuse);
151
+ if (m.role === "system")
152
+ system = [system, text].filter(Boolean).join("\n\n");
153
+ else if (m.role === "user" || m.role === "assistant")
154
+ messages.push({ role: m.role, content: text });
155
+ else if (m.role === "tool")
156
+ throw new Skip("tool-call conversation");
157
+ }
158
+ const extra = partsText(parsed(attrs["gen_ai.system_instructions"]), () => { });
159
+ if (extra)
160
+ system = [extra, system].filter(Boolean).join("\n\n");
161
+ }
162
+ else {
163
+ // Older instrumentations: gen_ai.prompt.0.role / gen_ai.prompt.0.content ...
164
+ for (let i = 0; attrs[`gen_ai.prompt.${i}.role`] !== undefined || attrs[`gen_ai.prompt.${i}.content`] !== undefined; i++) {
165
+ const role = str(attrs[`gen_ai.prompt.${i}.role`]);
166
+ const content = str(attrs[`gen_ai.prompt.${i}.content`]) ?? "";
167
+ if (role === "system")
168
+ system = [system, content].filter(Boolean).join("\n\n");
169
+ else if (role === "user" || role === "assistant")
170
+ messages.push({ role, content });
171
+ else if (role === "tool")
172
+ throw new Skip("tool-call conversation");
173
+ }
174
+ }
175
+ if (messages.length === 0)
176
+ return null;
177
+ const out = { messages };
178
+ if (system)
179
+ out.system = system;
180
+ const model = str(attrs["gen_ai.request.model"]) ?? str(attrs["gen_ai.response.model"]);
181
+ if (model)
182
+ out.model = model;
183
+ const maxTokens = num(attrs["gen_ai.request.max_tokens"]);
184
+ if (maxTokens !== undefined)
185
+ out.maxTokens = maxTokens;
186
+ const temperature = num(attrs["gen_ai.request.temperature"]);
187
+ if (temperature !== undefined)
188
+ out.temperature = temperature;
189
+ if (attrs["gen_ai.output.type"] === "json")
190
+ out.jsonMode = true;
191
+ return out;
192
+ }
193
+ function otelAnswer(attrs) {
194
+ const output = parsed(attrs["gen_ai.output.messages"]);
195
+ if (Array.isArray(output)) {
196
+ for (const m of output) {
197
+ if (!isObj(m) || !Array.isArray(m.parts))
198
+ continue;
199
+ const call = m.parts.find((p) => isObj(p) && p.type === "tool_call");
200
+ if (call && typeof call.name === "string")
201
+ return { tool: call.name };
202
+ const text = partsText(m.parts, () => { });
203
+ if (text)
204
+ return { text };
205
+ }
206
+ }
207
+ const legacy = str(attrs["gen_ai.completion.0.content"]);
208
+ return legacy ? { text: legacy } : null;
209
+ }
210
+ // ---------- request bodies ----------
211
+ /** Text of an OpenAI/Anthropic content value: a string or a list of text blocks. */
212
+ function contentText(content) {
213
+ if (typeof content === "string")
214
+ return content;
215
+ if (!Array.isArray(content))
216
+ throw new Skip("unreadable message content");
217
+ const texts = [];
218
+ for (const block of content) {
219
+ if (typeof block === "string")
220
+ texts.push(block);
221
+ else if (isObj(block)) {
222
+ const type = block.type;
223
+ if ((type === "text" || type === "input_text" || type === "output_text") && typeof block.text === "string")
224
+ texts.push(block.text);
225
+ else if (type === "tool_use" || type === "tool_result" || type === "function_call" || type === "function_call_output")
226
+ throw new Skip("tool-call conversation");
227
+ else if (type !== "thinking" && type !== "redacted_thinking")
228
+ throw new Skip("non-text content (images, files or audio)");
229
+ }
230
+ }
231
+ return texts.join("\n");
232
+ }
233
+ function chatMessages(list) {
234
+ let system = "";
235
+ const messages = [];
236
+ for (const m of list) {
237
+ if (!isObj(m))
238
+ continue;
239
+ const role = m.role ?? (m.type === "message" ? "user" : undefined);
240
+ if (role === "system" || role === "developer")
241
+ system = [system, contentText(m.content)].filter(Boolean).join("\n\n");
242
+ else if (role === "user" || role === "assistant") {
243
+ if (role === "assistant" && ((Array.isArray(m.tool_calls) && m.tool_calls.length > 0) || isObj(m.function_call)))
244
+ throw new Skip("tool-call conversation");
245
+ messages.push({ role, content: contentText(m.content) });
246
+ }
247
+ else if (role === "tool" || role === "function" || m.type === "function_call" || m.type === "function_call_output") {
248
+ throw new Skip("tool-call conversation");
249
+ }
250
+ }
251
+ return { system, messages };
252
+ }
253
+ function geminiContents(contents) {
254
+ return contents.flatMap((c) => {
255
+ if (!isObj(c) || !Array.isArray(c.parts))
256
+ return [];
257
+ const texts = [];
258
+ for (const p of c.parts) {
259
+ if (!isObj(p))
260
+ continue;
261
+ if (typeof p.text === "string")
262
+ texts.push(p.text);
263
+ else if ("functionCall" in p || "functionResponse" in p)
264
+ throw new Skip("tool-call conversation");
265
+ else
266
+ throw new Skip("non-text content (images, files or audio)");
267
+ }
268
+ return [{ role: c.role === "model" ? "assistant" : "user", content: texts.join("\n") }];
269
+ });
270
+ }
271
+ function toolDefs(body) {
272
+ if (!Array.isArray(body.tools))
273
+ return undefined;
274
+ const defs = [];
275
+ for (const t of body.tools) {
276
+ if (!isObj(t))
277
+ continue;
278
+ // Gemini: tools: [{functionDeclarations: [...]}]
279
+ if (Array.isArray(t.functionDeclarations)) {
280
+ for (const f of t.functionDeclarations) {
281
+ if (isObj(f) && typeof f.name === "string" && isObj(f.parameters)) {
282
+ defs.push({ name: f.name, parameters: f.parameters, ...(typeof f.description === "string" ? { description: f.description } : {}) });
283
+ }
284
+ }
285
+ continue;
286
+ }
287
+ const fn = isObj(t.function) ? t.function : t; // OpenAI chat nests under function; Responses and Anthropic do not
288
+ const name = str(fn.name);
289
+ const parameters = isObj(fn.parameters) ? fn.parameters : isObj(fn.input_schema) ? fn.input_schema : undefined;
290
+ if (!name || !parameters)
291
+ continue;
292
+ defs.push({ name, parameters, ...(typeof fn.description === "string" ? { description: fn.description } : {}) });
293
+ }
294
+ return defs.length ? defs : undefined;
295
+ }
296
+ function fromBody(body) {
297
+ let system = "";
298
+ let messages;
299
+ if (Array.isArray(body.messages)) {
300
+ const chat = chatMessages(body.messages);
301
+ messages = chat.messages;
302
+ system = chat.system;
303
+ // Anthropic: top-level system as a string or text blocks.
304
+ if (body.system !== undefined && body.system !== null)
305
+ system = [contentText(body.system), system].filter(Boolean).join("\n\n");
306
+ }
307
+ else if (Array.isArray(body.contents)) {
308
+ messages = geminiContents(body.contents);
309
+ const si = body.systemInstruction ?? body.system_instruction;
310
+ if (isObj(si) && Array.isArray(si.parts))
311
+ system = si.parts.flatMap((p) => (isObj(p) && typeof p.text === "string" ? [p.text] : [])).join("\n");
312
+ }
313
+ else if (typeof body.input === "string" && (body.model !== undefined || body.instructions !== undefined)) {
314
+ messages = [{ role: "user", content: body.input }]; // OpenAI Responses
315
+ }
316
+ else if (Array.isArray(body.input) && (body.model !== undefined || body.instructions !== undefined)) {
317
+ const chat = chatMessages(body.input);
318
+ messages = chat.messages;
319
+ system = chat.system;
320
+ }
321
+ else {
322
+ return null;
323
+ }
324
+ if (typeof body.instructions === "string")
325
+ system = [body.instructions, system].filter(Boolean).join("\n\n");
326
+ if (messages.length === 0)
327
+ return null;
328
+ const out = { messages };
329
+ if (system)
330
+ out.system = system;
331
+ if (typeof body.model === "string")
332
+ out.model = body.model;
333
+ const gen = isObj(body.generationConfig) ? body.generationConfig : isObj(body.generation_config) ? body.generation_config : {};
334
+ const maxTokens = num(body.max_tokens) ?? num(body.max_completion_tokens) ?? num(body.max_output_tokens) ?? num(gen.maxOutputTokens);
335
+ if (maxTokens !== undefined)
336
+ out.maxTokens = maxTokens;
337
+ const temperature = num(body.temperature) ?? num(gen.temperature);
338
+ if (temperature !== undefined)
339
+ out.temperature = temperature;
340
+ const defs = toolDefs(body);
341
+ if (defs)
342
+ out.tools = defs;
343
+ const choice = body.tool_choice;
344
+ if (choice === "required" || choice === "any" || (isObj(choice) && choice.type !== "auto" && choice.type !== "none"))
345
+ out.forcedTool = true;
346
+ if (isObj(body.toolConfig) && isObj(body.toolConfig.functionCallingConfig) && body.toolConfig.functionCallingConfig.mode === "ANY")
347
+ out.forcedTool = true;
348
+ const rf = isObj(body.response_format) ? body.response_format : isObj(body.text) && isObj(body.text.format) ? body.text.format : null;
349
+ if (rf?.type === "json_object")
350
+ out.jsonMode = true;
351
+ if (rf?.type === "json_schema") {
352
+ out.jsonMode = true;
353
+ const schema = isObj(rf.json_schema) ? rf.json_schema.schema : rf.schema;
354
+ if (isObj(schema))
355
+ out.schema = normalizeSchema(schema);
356
+ }
357
+ if (gen.responseMimeType === "application/json") {
358
+ out.jsonMode = true;
359
+ const schema = gen.responseSchema ?? gen.responseJsonSchema;
360
+ if (isObj(schema))
361
+ out.schema = normalizeSchema(schema);
362
+ }
363
+ return out;
364
+ }
365
+ // ---------- recorded answers ----------
366
+ function answerFrom(value) {
367
+ const v = parsed(value);
368
+ if (typeof v === "string")
369
+ return v.trim() ? { text: v } : null;
370
+ if (Array.isArray(v)) {
371
+ for (const item of v) {
372
+ const a = answerFrom(item);
373
+ if (a)
374
+ return a;
375
+ }
376
+ return null;
377
+ }
378
+ if (!isObj(v))
379
+ return null;
380
+ // OpenAI chat
381
+ if (Array.isArray(v.choices) && isObj(v.choices[0]))
382
+ return answerFrom(v.choices[0].message ?? v.choices[0].text);
383
+ if (Array.isArray(v.tool_calls) && isObj(v.tool_calls[0])) {
384
+ const fn = isObj(v.tool_calls[0].function) ? v.tool_calls[0].function : v.tool_calls[0];
385
+ if (typeof fn.name === "string")
386
+ return { tool: fn.name };
387
+ }
388
+ // Gemini
389
+ if (Array.isArray(v.candidates) && isObj(v.candidates[0]) && isObj(v.candidates[0].content)) {
390
+ const parts = v.candidates[0].content.parts;
391
+ if (Array.isArray(parts)) {
392
+ const call = parts.find((p) => isObj(p) && isObj(p.functionCall));
393
+ if (call && isObj(call.functionCall) && typeof call.functionCall.name === "string")
394
+ return { tool: call.functionCall.name };
395
+ const text = parts.flatMap((p) => (isObj(p) && typeof p.text === "string" ? [p.text] : [])).join("");
396
+ return text ? { text } : null;
397
+ }
398
+ }
399
+ // Anthropic content blocks, Responses output items
400
+ const blocks = Array.isArray(v.content) ? v.content : Array.isArray(v.output) ? v.output : null;
401
+ if (blocks) {
402
+ for (const b of blocks) {
403
+ if (isObj(b) && (b.type === "tool_use" || b.type === "function_call") && typeof b.name === "string")
404
+ return { tool: b.name };
405
+ }
406
+ const text = blocks
407
+ .flatMap((b) => isObj(b) && typeof b.text === "string"
408
+ ? [b.text]
409
+ : isObj(b) && Array.isArray(b.content)
410
+ ? b.content.flatMap((c) => (isObj(c) && typeof c.text === "string" ? [c.text] : []))
411
+ : [])
412
+ .join("");
413
+ if (text)
414
+ return { text };
415
+ }
416
+ if (typeof v.content === "string")
417
+ return { text: v.content };
418
+ if (typeof v.output_text === "string")
419
+ return { text: v.output_text };
420
+ if (typeof v.text === "string")
421
+ return { text: v.text };
422
+ return null;
423
+ }
424
+ function looksLikeJson(text) {
425
+ let t = text.trim();
426
+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(t);
427
+ if (fenced?.[1] !== undefined)
428
+ t = fenced[1];
429
+ if (!t.startsWith("{") && !t.startsWith("["))
430
+ return false;
431
+ try {
432
+ const v = JSON.parse(t);
433
+ return typeof v === "object" && v !== null;
434
+ }
435
+ catch {
436
+ return false;
437
+ }
438
+ }
439
+ // ---------- per record ----------
440
+ const BODY_KEYS = ["request_body", "requestBody", "request", "body", "input", "prompt"];
441
+ const ANSWER_KEYS = ["response_body", "responseBody", "response", "output", "completion", "result"];
442
+ const ID_KEYS = ["id", "request_id", "requestId", "spanId", "span_id"];
443
+ function extractRecord(record) {
444
+ const attrs = spanAttributes(record);
445
+ if (attrs && (attrs["gen_ai.input.messages"] !== undefined || attrs["gen_ai.prompt.0.content"] !== undefined || attrs["gen_ai.prompt.0.role"] !== undefined)) {
446
+ const call = fromOtel(attrs);
447
+ const id = str(record.spanId) ?? str(record.span_id);
448
+ return call ? { call, answer: otelAnswer(attrs), ...(id ? { id } : {}) } : null;
449
+ }
450
+ // OpenAI Evals output items (saved with evals-export): the exact messages sent, the model and its answer. The
451
+ // run's sampling_params (response format, tools), which the items don't repeat, come in as `sampling_params`.
452
+ if (isEvalItem(record)) {
453
+ const s = record.sample;
454
+ if (isObj(s.error) && (s.error.code || s.error.message))
455
+ throw new Skip("the eval's call failed");
456
+ const sp = isObj(record.sampling_params) ? record.sampling_params : {};
457
+ const max = num(s.max_completion_tokens) ?? num(sp.max_completion_tokens) ?? num(sp.max_output_tokens);
458
+ const evalCall = fromBody({
459
+ messages: s.input,
460
+ model: s.model,
461
+ ...(max && max > 0 ? { max_completion_tokens: max } : {}),
462
+ temperature: s.temperature ?? sp.temperature,
463
+ ...(sp.response_format !== undefined ? { response_format: sp.response_format } : {}),
464
+ ...(sp.text !== undefined ? { text: sp.text } : {}),
465
+ ...(sp.tools !== undefined ? { tools: sp.tools } : {}),
466
+ });
467
+ if (!evalCall)
468
+ return null;
469
+ const itemId = num(record.datasource_item_id);
470
+ const id = str(record.id) ?? (itemId !== undefined ? `item-${itemId}` : undefined);
471
+ return { call: evalCall, answer: answerFrom(s.output), ...(id ? { id } : {}) };
472
+ }
473
+ let call = null;
474
+ for (const key of BODY_KEYS) {
475
+ const v = parsed(record[key]);
476
+ if (isObj(v))
477
+ call = fromBody(v);
478
+ // Langfuse often stores a generation's input as the message list itself.
479
+ else if (Array.isArray(v) && v.some((m) => isObj(m) && typeof m.role === "string"))
480
+ call = fromBody({ messages: v });
481
+ if (call)
482
+ break;
483
+ }
484
+ call ??= fromBody(record);
485
+ if (!call)
486
+ return null;
487
+ if (!call.model && typeof record.model === "string")
488
+ call.model = record.model;
489
+ let answer = null;
490
+ for (const key of ANSWER_KEYS) {
491
+ if (record[key] === undefined)
492
+ continue;
493
+ answer = answerFrom(record[key]);
494
+ if (answer)
495
+ break;
496
+ }
497
+ const id = ID_KEYS.map((k) => record[k]).find((v) => typeof v === "string" || typeof v === "number");
498
+ return { call, answer, ...(id !== undefined ? { id: String(id) } : {}) };
499
+ }
500
+ function lastSegment(model) {
501
+ return (model.split("/").at(-1) ?? model).toLowerCase();
502
+ }
503
+ /** gpt-4o matches gpt-4o and its dated snapshots (gpt-4o-2024-08-06), never gpt-4o-mini. */
504
+ export function sameModel(logged, wanted) {
505
+ const a = lastSegment(logged);
506
+ const b = lastSegment(wanted);
507
+ if (a === b)
508
+ return true;
509
+ if (!a.startsWith(b))
510
+ return false;
511
+ return /^(?:-\d{4}-?\d{2}-?\d{2}|-\d{3,4}|@\d{8}|-latest|-v\d+(?::\d+)?)$/.test(a.slice(b.length));
512
+ }
513
+ /** Up to `limit` items spread evenly over the list, so one busy hour does not fill the set. */
514
+ function spread(list, limit) {
515
+ if (list.length <= limit)
516
+ return list;
517
+ const step = list.length / limit;
518
+ return Array.from({ length: limit }, (_, i) => list[Math.floor(i * step)]);
519
+ }
520
+ const UNSAFE_ID = /[^A-Za-z0-9._-]+/g;
521
+ export function importPrompts(text, options = {}) {
522
+ const { values, badLines } = parseFile(text);
523
+ return importValues(values, options, badLines);
524
+ }
525
+ /** Like importPrompts, for records already parsed (several files at once, or records given extra fields). */
526
+ export function importValues(values, options = {}, badLines = 0) {
527
+ const limit = options.limit ?? 50;
528
+ const wantModel = options.model;
529
+ const all = values.flatMap((v) => records(v));
530
+ const skipped = {};
531
+ const skip = (reason) => (skipped[reason] = (skipped[reason] ?? 0) + 1);
532
+ if (badLines > 0)
533
+ skipped["lines that are not JSON"] = badLines;
534
+ const seen = new Set();
535
+ const ids = new Set();
536
+ const models = {};
537
+ const found = [];
538
+ let unknownModel = 0;
539
+ for (const record of all) {
540
+ let got;
541
+ try {
542
+ got = extractRecord(record);
543
+ }
544
+ catch (error) {
545
+ if (!(error instanceof Skip))
546
+ throw error;
547
+ skip(error.message);
548
+ continue;
549
+ }
550
+ if (!got) {
551
+ skip("no prompt found in the record");
552
+ continue;
553
+ }
554
+ const { call, answer } = got;
555
+ // A logged conversation can end with the model's own reply; the prompt is everything before it.
556
+ while (call.messages.at(-1)?.role === "assistant")
557
+ call.messages.pop();
558
+ if (call.messages.length === 0 || !call.messages.at(-1).content.trim()) {
559
+ skip("empty prompt");
560
+ continue;
561
+ }
562
+ if (wantModel && call.model && !sameModel(call.model, wantModel)) {
563
+ skip("a different model");
564
+ continue;
565
+ }
566
+ if (wantModel && !call.model)
567
+ unknownModel++;
568
+ const key = JSON.stringify([call.system ?? "", call.messages, call.tools?.map((t) => t.name) ?? [], call.jsonMode ?? false, call.schema ?? null]);
569
+ if (seen.has(key)) {
570
+ skip("duplicate of an earlier prompt");
571
+ continue;
572
+ }
573
+ seen.add(key);
574
+ if (call.model)
575
+ models[call.model] = (models[call.model] ?? 0) + 1;
576
+ const fallback = `log-${found.length + 1}`;
577
+ const base = (got.id ?? fallback).replace(UNSAFE_ID, "-").slice(0, 60) || fallback;
578
+ let id = base;
579
+ for (let n = 2; ids.has(id); n++)
580
+ id = `${base}-${n}`;
581
+ ids.add(id);
582
+ const item = { id, messages: call.messages };
583
+ if (call.system)
584
+ item.system = call.system;
585
+ if (call.tools)
586
+ item.tools = call.tools;
587
+ if (call.maxTokens !== undefined)
588
+ item.maxTokens = call.maxTokens;
589
+ if (call.temperature !== undefined)
590
+ item.temperature = call.temperature;
591
+ if (call.jsonMode)
592
+ item.jsonMode = true;
593
+ const expect = {};
594
+ if (call.schema)
595
+ expect.schema = call.schema;
596
+ else if (call.jsonMode || (answer?.text !== undefined && looksLikeJson(answer.text)))
597
+ expect.json = true;
598
+ // A forced tool_choice is not replayed, so the model may answer in text; no tool check then.
599
+ if (answer?.tool && !call.forcedTool && call.tools?.some((t) => t.name === answer.tool))
600
+ expect.tool = answer.tool;
601
+ if (Object.keys(expect).length > 0)
602
+ item.expect = expect;
603
+ found.push(item);
604
+ }
605
+ return { items: spread(found, limit), records: all.length, found: found.length, skipped, models, unknownModel };
606
+ }
@@ -0,0 +1,31 @@
1
+ export { loadGoldenSet, parseGoldenSet, GoldenSetError } from "./golden.js";
2
+ export type { GoldenItem, GoldenExpect } from "./golden.js";
3
+ export { validateSchema, extractJson } from "./schema.js";
4
+ export type { JsonSchema } from "./schema.js";
5
+ export { similarity } from "./similarity.js";
6
+ export { runReplay, plannedCalls, SpendCapError } from "./run.js";
7
+ export type { RunRecord, ReplayOptions, Side } from "./run.js";
8
+ export { judgeItem } from "./verdict.js";
9
+ export type { ItemResult, Reason, ReasonCode, SideStats, Verdict } from "./verdict.js";
10
+ export { buildReplayReport, costLine, costOfCall, formatReplayMarkdown, formatReplayText, isReroute, platformForRef } from "./report.js";
11
+ export type { ReplayReport, Reroute } from "./report.js";
12
+ export { applyRepair, formatInstruction, formatRepairMarkdown, formatRepairText, goldenLine, plannedRepairCalls, repairable, runRepair } from "./repair.js";
13
+ export type { RepairAttempt, RepairKind, RepairPatch, RepairReport, RepairResult } from "./repair.js";
14
+ export { importPrompts, importValues, sameModel } from "./importer.js";
15
+ export type { ImportOptions, ImportResult } from "./importer.js";
16
+ export { generateStarterSet, parseStarterAnswer, starterRequest } from "./starter.js";
17
+ export type { StarterOptions, StarterResult, StarterSource } from "./starter.js";
18
+ export { runReplayJob } from "./job.js";
19
+ export type { ReplayJob, ReplayJobResult } from "./job.js";
20
+ export { ReplayCancelledError } from "./run.js";
21
+ export { BASELINE_VERSION, createBaseline, formatWatchMarkdown, formatWatchText, itemHash, parseBaseline, postSlack, runWatch, slackMessage, WATCH_SHARE } from "./watch.js";
22
+ export type { Baseline, BaselineOptions, WatchOptions, WatchReport } from "./watch.js";
23
+ export type { JudgeOptions } from "./verdict.js";
24
+ export { cleanCandidates, litellmConfig, openrouterConfig, plannedFallbackCalls, testFallbacks } from "./fallback.js";
25
+ export type { CandidateResult, FallbackOptions, FallbackResult } from "./fallback.js";
26
+ export { candidateProblem, cheaperCandidates, findSavings, formatSavingsMarkdown, formatSavingsText, MAX_CHANGED_SHARE, steadyCost } from "./savings.js";
27
+ export type { Candidate, SavingsCandidate, SavingsOptions, SavingsResult } from "./savings.js";
28
+ export { formatSlimMarkdown, formatSlimText, MIN_SLIM_ITEMS, parseSlimAnswer, placeholders, plannedSlimCalls, rewriteProblem, SLIM_STYLES, slimPrompts, slimRequest, slimTargets } from "./slim.js";
29
+ export type { SlimOptions, SlimPrompt, SlimResult, SlimStyle, SlimVariant } from "./slim.js";
30
+ export { EvalsExportError, exportOpenAiEvals, runFileIds, runSamplingParams, safeId } from "./openai-evals.js";
31
+ export type { EvalsExportOptions, EvalsExportResult } from "./openai-evals.js";
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ export { loadGoldenSet, parseGoldenSet, GoldenSetError } from "./golden.js";
2
+ export { validateSchema, extractJson } from "./schema.js";
3
+ export { similarity } from "./similarity.js";
4
+ export { runReplay, plannedCalls, SpendCapError } from "./run.js";
5
+ export { judgeItem } from "./verdict.js";
6
+ export { buildReplayReport, costLine, costOfCall, formatReplayMarkdown, formatReplayText, isReroute, platformForRef } from "./report.js";
7
+ export { applyRepair, formatInstruction, formatRepairMarkdown, formatRepairText, goldenLine, plannedRepairCalls, repairable, runRepair } from "./repair.js";
8
+ export { importPrompts, importValues, sameModel } from "./importer.js";
9
+ export { generateStarterSet, parseStarterAnswer, starterRequest } from "./starter.js";
10
+ export { runReplayJob } from "./job.js";
11
+ export { ReplayCancelledError } from "./run.js";
12
+ export { BASELINE_VERSION, createBaseline, formatWatchMarkdown, formatWatchText, itemHash, parseBaseline, postSlack, runWatch, slackMessage, WATCH_SHARE } from "./watch.js";
13
+ export { cleanCandidates, litellmConfig, openrouterConfig, plannedFallbackCalls, testFallbacks } from "./fallback.js";
14
+ export { candidateProblem, cheaperCandidates, findSavings, formatSavingsMarkdown, formatSavingsText, MAX_CHANGED_SHARE, steadyCost } from "./savings.js";
15
+ export { formatSlimMarkdown, formatSlimText, MIN_SLIM_ITEMS, parseSlimAnswer, placeholders, plannedSlimCalls, rewriteProblem, SLIM_STYLES, slimPrompts, slimRequest, slimTargets } from "./slim.js";
16
+ export { EvalsExportError, exportOpenAiEvals, runFileIds, runSamplingParams, safeId } from "./openai-evals.js";
package/dist/job.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { LlmClient } from "@ai-changeguard/llm";
2
+ import type { GoldenItem } from "./golden.js";
3
+ import { type RepairReport } from "./repair.js";
4
+ import { type ReplayReport } from "./report.js";
5
+ import { type RunRecord } from "./run.js";
6
+ /**
7
+ * One replay, optionally followed by Prompt Repair, under a single call budget. Shared by the
8
+ * CLI, the GitHub Action and the MCP server so the spend rules live in one place: the replay
9
+ * refuses to start above maxCalls, and repair only uses what the replay left.
10
+ */
11
+ export interface ReplayJob {
12
+ items: GoldenItem[];
13
+ oldModel: string;
14
+ newModel: string;
15
+ runs: number;
16
+ maxCalls: number;
17
+ concurrency: number;
18
+ client: LlmClient;
19
+ repair?: boolean;
20
+ signal?: AbortSignal;
21
+ onProgress?: (done: number, total: number) => void;
22
+ }
23
+ export interface ReplayJobResult {
24
+ report: ReplayReport;
25
+ records: RunRecord[];
26
+ repair?: RepairReport;
27
+ /** Why repair did not run although broken formats were found. */
28
+ repairSkipped?: string;
29
+ }
30
+ export declare function runReplayJob(job: ReplayJob): Promise<ReplayJobResult>;