@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.
package/dist/report.js ADDED
@@ -0,0 +1,165 @@
1
+ import { billedPriceOn, callCost, defaultPlatform, formatUsd, localToday } from "@ai-changeguard/catalog";
2
+ import { judgeItem } from "./verdict.js";
3
+ const VERDICT_ORDER = { broken: 0, changed: 1, error: 2, same: 3 };
4
+ const average = (values) => (values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0);
5
+ /** The model part of a provider:model reference. */
6
+ export function modelName(ref) {
7
+ return ref.slice(ref.indexOf(":") + 1);
8
+ }
9
+ function lastSegment(name) {
10
+ return (name.split("/").at(-1) ?? name).toLowerCase();
11
+ }
12
+ export function isReroute(requested, served) {
13
+ const a = lastSegment(requested);
14
+ const b = lastSegment(served);
15
+ return !b.startsWith(a) && !a.startsWith(b);
16
+ }
17
+ /**
18
+ * The catalog platform a provider:model reference is priced on. Undefined for gateways (groq, openrouter,
19
+ * ollama), which bill their own prices: the catalog only knows the providers' own APIs.
20
+ */
21
+ export function platformForRef(ref) {
22
+ const provider = ref.slice(0, ref.indexOf(":"));
23
+ return Object.hasOwn(defaultPlatform, provider) ? defaultPlatform[provider] : undefined;
24
+ }
25
+ /** List-price cost of one call for a provider:model reference, or undefined when the catalog has no price. */
26
+ export function costOfCall(ref, usage, today) {
27
+ const platform = platformForRef(ref);
28
+ const price = platform ? billedPriceOn(modelName(ref), platform, today) : undefined;
29
+ return price ? callCost(price, usage.input, usage.output) : undefined;
30
+ }
31
+ export function buildReplayReport(items, records, options) {
32
+ const results = items.map((item) => judgeItem(item, records, options.judge)).sort((a, b) => VERDICT_ORDER[a.verdict] - VERDICT_ORDER[b.verdict]);
33
+ const totals = { same: 0, changed: 0, broken: 0, error: 0 };
34
+ for (const r of results)
35
+ totals[r.verdict]++;
36
+ const ok = (side) => records.flatMap((r) => (r.side === side && r.response ? [r.response] : []));
37
+ // Compare only prompts both models answered, so a failed call doesn't skew the averages.
38
+ const paired = results.filter((r) => r.old.runs > r.old.errors && r.new.runs > r.new.errors);
39
+ const usage = (side) => ({
40
+ input: average(paired.map((r) => r[side].avgInputTokens)),
41
+ output: average(paired.map((r) => r[side].avgOutputTokens)),
42
+ });
43
+ const reroutes = [];
44
+ for (const side of ["old", "new"]) {
45
+ const requested = modelName(side === "old" ? options.oldModel : options.newModel);
46
+ const served = new Set(ok(side).flatMap((r) => (r.servedModel ? [r.servedModel] : [])));
47
+ for (const s of served)
48
+ if (isReroute(requested, s))
49
+ reroutes.push({ side, requested, served: s });
50
+ }
51
+ const today = options.today ?? localToday();
52
+ const avgTokens = { old: usage("old"), new: usage("new") };
53
+ const oldCost = paired.length ? costOfCall(options.oldModel, avgTokens.old, today) : undefined;
54
+ const newCost = paired.length ? costOfCall(options.newModel, avgTokens.new, today) : undefined;
55
+ return {
56
+ oldModel: options.oldModel,
57
+ newModel: options.newModel,
58
+ runs: options.runs,
59
+ calls: records.length,
60
+ failedCalls: records.filter((r) => r.error).length,
61
+ totals,
62
+ avgTokens,
63
+ avgLatencyMs: { old: average(paired.map((r) => r.old.avgLatencyMs)), new: average(paired.map((r) => r.new.avgLatencyMs)) },
64
+ ...(oldCost !== undefined || newCost !== undefined ? { costPerCall: { ...(oldCost !== undefined ? { old: oldCost } : {}), ...(newCost !== undefined ? { new: newCost } : {}) } } : {}),
65
+ comparedPrompts: paired.length,
66
+ rateLimited: records.some((r) => r.error?.startsWith("HTTP 429")),
67
+ reroutes,
68
+ items: results,
69
+ };
70
+ }
71
+ function change(before, after) {
72
+ if (before === 0)
73
+ return "";
74
+ const pct = Math.round(((after - before) / before) * 100);
75
+ return ` (${pct > 0 ? "+" : ""}${pct}%)`;
76
+ }
77
+ /** "Cost per call at list price: $0.0012 → $0.0015 (+25%)", or "" when neither side has a price. */
78
+ export function costLine(report) {
79
+ const c = report.costPerCall;
80
+ if (!c)
81
+ return "";
82
+ const side = (v) => (v === undefined ? "no list price known" : formatUsd(v));
83
+ const pct = c.old !== undefined && c.new !== undefined ? change(c.old, c.new) : "";
84
+ return `Cost per call at list price: ${side(c.old)} → ${side(c.new)}${pct}`;
85
+ }
86
+ function seconds(ms) {
87
+ return `${(ms / 1000).toFixed(1)} s`;
88
+ }
89
+ const LABEL = { broken: "BROKEN ", changed: "CHANGED", error: "ERROR ", same: "SAME " };
90
+ export function formatReplayText(report) {
91
+ const t = report.totals;
92
+ const out = [];
93
+ out.push(`Replay: ${report.oldModel} → ${report.newModel} · ${report.items.length} prompt${report.items.length === 1 ? "" : "s"} × ${report.runs} run${report.runs === 1 ? "" : "s"} · ${report.calls} calls (${report.failedCalls} failed)`);
94
+ out.push(`Verdict: ${t.same} same · ${t.changed} changed · ${t.broken} broken · ${t.error} could not compare`);
95
+ const o = report.avgTokens.old;
96
+ const n = report.avgTokens.new;
97
+ out.push(`Per call, over the ${report.comparedPrompts} prompts both models answered: input tokens ${Math.round(o.input)} → ${Math.round(n.input)}${change(o.input, n.input)} · ` +
98
+ `output tokens ${Math.round(o.output)} → ${Math.round(n.output)}${change(o.output, n.output)} · ` +
99
+ `latency ${seconds(report.avgLatencyMs.old)} → ${seconds(report.avgLatencyMs.new)}`);
100
+ const cost = costLine(report);
101
+ if (cost)
102
+ out.push(cost);
103
+ if (report.rateLimited) {
104
+ out.push("TIP: some calls hit the provider's rate limit. Re-run with --concurrency 1, or use a key with a higher quota.");
105
+ }
106
+ for (const r of report.reroutes) {
107
+ out.push(`NOTE: ${r.side} model "${r.requested}" was answered by "${r.served}", a different model than requested.`);
108
+ }
109
+ out.push("");
110
+ for (const item of report.items) {
111
+ if (item.verdict === "same" || item.verdict === "error")
112
+ continue;
113
+ out.push(`${LABEL[item.verdict]} ${item.id}`);
114
+ for (const reason of item.reasons)
115
+ out.push(` ${reason.code}: ${reason.detail}`);
116
+ }
117
+ const errorsByMessage = new Map();
118
+ for (const item of report.items) {
119
+ if (item.verdict !== "error")
120
+ continue;
121
+ const message = item.error ?? "Unknown error";
122
+ errorsByMessage.set(message, [...(errorsByMessage.get(message) ?? []), item.id]);
123
+ }
124
+ for (const [message, ids] of errorsByMessage) {
125
+ const shown = ids.length > 3 ? `${ids.slice(0, 3).join(", ")} and ${ids.length - 3} more` : ids.join(", ");
126
+ out.push(`${LABEL.error} ${ids.length === 1 ? ids[0] : `${ids.length} prompts (${shown})`}`);
127
+ out.push(` ${message}`);
128
+ }
129
+ if (t.same > 0)
130
+ out.push(`${t.same} ${t.same === 1 ? "prompt behaves" : "prompts behave"} the same.`);
131
+ return out.join("\n");
132
+ }
133
+ export function formatReplayMarkdown(report) {
134
+ const t = report.totals;
135
+ const o = report.avgTokens.old;
136
+ const n = report.avgTokens.new;
137
+ const out = [
138
+ `## Model switch check: \`${report.oldModel}\` → \`${report.newModel}\``,
139
+ "",
140
+ `${report.items.length} real prompt${report.items.length === 1 ? "" : "s"}, ${report.runs} run${report.runs === 1 ? "" : "s"} each on both models.`,
141
+ "",
142
+ "| Same | Changed | Broken | Could not compare |",
143
+ "| --- | --- | --- | --- |",
144
+ `| ${t.same} | ${t.changed} | ${t.broken} | ${t.error} |`,
145
+ "",
146
+ `Per call: input tokens ${Math.round(o.input)} → ${Math.round(n.input)}${change(o.input, n.input)}, output tokens ${Math.round(o.output)} → ${Math.round(n.output)}${change(o.output, n.output)}, latency ${seconds(report.avgLatencyMs.old)} → ${seconds(report.avgLatencyMs.new)}.`,
147
+ ];
148
+ const cost = costLine(report);
149
+ if (cost)
150
+ out.push("", `${cost}.`);
151
+ for (const r of report.reroutes)
152
+ out.push("", `> **Note:** the ${r.side} model \`${r.requested}\` was answered by \`${r.served}\`.`);
153
+ const flagged = report.items.filter((i) => i.verdict !== "same");
154
+ if (flagged.length > 0) {
155
+ out.push("", "### What changed");
156
+ for (const item of flagged) {
157
+ out.push("", `**${item.verdict.toUpperCase()}: ${item.id}**`);
158
+ if (item.error)
159
+ out.push(`- ${item.error}`);
160
+ for (const reason of item.reasons)
161
+ out.push(`- ${reason.detail}`);
162
+ }
163
+ }
164
+ return out.join("\n");
165
+ }
package/dist/run.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { LlmClient, LlmResponse } from "@ai-changeguard/llm";
2
+ import type { GoldenItem } from "./golden.js";
3
+ export type Side = "old" | "new";
4
+ export interface RunRecord {
5
+ itemId: string;
6
+ side: Side;
7
+ run: number;
8
+ response?: LlmResponse;
9
+ error?: string;
10
+ }
11
+ export interface ReplayOptions {
12
+ items: GoldenItem[];
13
+ oldModel: string;
14
+ newModel: string;
15
+ client: LlmClient;
16
+ runs?: number;
17
+ concurrency?: number;
18
+ maxCalls?: number;
19
+ defaultMaxTokens?: number;
20
+ /**
21
+ * Prompts sent on the new side in place of `items`, matched by id: the same prompts with a different system
22
+ * prompt, for example (Verified Prompt Slimming). Default: `items` on both sides.
23
+ */
24
+ newItems?: GoldenItem[];
25
+ /** Which models to call; a repair re-test calls only the new one. Default: both. */
26
+ sides?: Side[];
27
+ /** Stops starting new calls once aborted; the replay then rejects with a ReplayCancelledError. */
28
+ signal?: AbortSignal;
29
+ onProgress?: (done: number, total: number) => void;
30
+ }
31
+ export declare class SpendCapError extends Error {
32
+ }
33
+ export declare class ReplayCancelledError extends Error {
34
+ }
35
+ export declare function plannedCalls(items: number, runs: number, sides?: number): number;
36
+ export declare function runReplay(options: ReplayOptions): Promise<RunRecord[]>;
package/dist/run.js ADDED
@@ -0,0 +1,62 @@
1
+ export class SpendCapError extends Error {
2
+ }
3
+ export class ReplayCancelledError extends Error {
4
+ }
5
+ export function plannedCalls(items, runs, sides = 2) {
6
+ return items * runs * sides;
7
+ }
8
+ function requestFor(item, model, defaultMaxTokens) {
9
+ const request = { model, messages: item.messages, maxTokens: item.maxTokens ?? defaultMaxTokens };
10
+ if (item.system)
11
+ request.system = item.system;
12
+ if (item.tools)
13
+ request.tools = item.tools;
14
+ if (item.temperature !== undefined)
15
+ request.temperature = item.temperature;
16
+ if (item.jsonMode)
17
+ request.jsonMode = true;
18
+ return request;
19
+ }
20
+ export async function runReplay(options) {
21
+ const runs = options.runs ?? 5;
22
+ const concurrency = Math.max(1, options.concurrency ?? 5);
23
+ const maxCalls = options.maxCalls ?? 500;
24
+ const sides = options.sides ?? ["old", "new"];
25
+ const total = plannedCalls(options.items.length, runs, sides.length);
26
+ if (total > maxCalls) {
27
+ throw new SpendCapError(`This replay needs ${total} AI calls, above the limit of ${maxCalls}. Lower --runs, use fewer prompts, or raise --max-calls.`);
28
+ }
29
+ const newById = new Map((options.newItems ?? []).map((i) => [i.id, i]));
30
+ const tasks = [];
31
+ for (const item of options.items) {
32
+ for (let run = 0; run < runs; run++) {
33
+ for (const side of sides) {
34
+ const sent = side === "new" ? (newById.get(item.id) ?? item) : item;
35
+ const request = requestFor(sent, side === "old" ? options.oldModel : options.newModel, options.defaultMaxTokens ?? 1024);
36
+ tasks.push(async () => {
37
+ try {
38
+ return { itemId: item.id, side, run, response: await options.client(request) };
39
+ }
40
+ catch (error) {
41
+ return { itemId: item.id, side, run, error: error instanceof Error ? error.message : String(error) };
42
+ }
43
+ });
44
+ }
45
+ }
46
+ }
47
+ const results = new Array(tasks.length);
48
+ let next = 0;
49
+ let done = 0;
50
+ const worker = async () => {
51
+ while (next < tasks.length && !options.signal?.aborted) {
52
+ const index = next++;
53
+ results[index] = await tasks[index]();
54
+ done++;
55
+ options.onProgress?.(done, total);
56
+ }
57
+ };
58
+ await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, worker));
59
+ if (options.signal?.aborted)
60
+ throw new ReplayCancelledError(`Replay cancelled after ${done} of ${total} calls.`);
61
+ return results;
62
+ }
@@ -0,0 +1,85 @@
1
+ import { type LlmClient } from "@ai-changeguard/llm";
2
+ import type { GoldenItem } from "./golden.js";
3
+ import { type ReplayReport } from "./report.js";
4
+ /** At most this share of prompts may change for a cheaper model to count as a safe switch. */
5
+ export declare const MAX_CHANGED_SHARE = 0.02;
6
+ export interface Candidate {
7
+ ref: string;
8
+ /** Estimated cost per call, at the token mix given (tokenizer difference included). */
9
+ costPerCall: number;
10
+ }
11
+ /**
12
+ * Cheaper models on the same provider (so the same API key works), closest in price first: those are the
13
+ * likeliest to answer the same way. Skips previews, dated snapshot IDs (the alias is suggested instead),
14
+ * models retiring soon, and models whose price in two months is unknown.
15
+ */
16
+ /**
17
+ * Why a model is not offered as a cheaper switch, or undefined when it may be: a preview, a dated snapshot
18
+ * ID, a model that retires or reroutes within 90 days, or one whose price two months out is unknown.
19
+ */
20
+ export declare function candidateProblem(ref: string, today: string): string | undefined;
21
+ /** Cost of a call at the steady price (the higher of today's and the price in two months). */
22
+ export declare function steadyCost(ref: string, tokens: {
23
+ input: number;
24
+ output: number;
25
+ }, today: string): number | undefined;
26
+ export declare function cheaperCandidates(primary: string, today: string, options?: {
27
+ tokens?: {
28
+ input: number;
29
+ output: number;
30
+ };
31
+ count?: number;
32
+ }): Candidate[];
33
+ export interface SavingsCandidate {
34
+ model: string;
35
+ qualifies: boolean;
36
+ reason?: string;
37
+ report: ReplayReport;
38
+ /** Share of compared prompts whose answers changed. */
39
+ changedShare: number;
40
+ /** US dollars per call at list price, from the replay's measured tokens. */
41
+ costPerCall?: {
42
+ current: number;
43
+ candidate: number;
44
+ };
45
+ /** Share of the per-call cost saved (0.7 = 70% cheaper). */
46
+ savingShare?: number;
47
+ /** Dollars a month saved at the call volume given. */
48
+ monthlySaving?: number;
49
+ }
50
+ export interface SavingsResult {
51
+ primary: string;
52
+ runs: number;
53
+ calls: number;
54
+ callsPerMonth?: number;
55
+ candidates: SavingsCandidate[];
56
+ /** Candidates not tested, and why (no calls spent on them). */
57
+ excluded: {
58
+ model: string;
59
+ reason: string;
60
+ }[];
61
+ /** Prompts the current model did not answer, so they could not be compared. */
62
+ skippedPrompts: string[];
63
+ /** The qualifying candidate that saves the most per call. */
64
+ best?: SavingsCandidate;
65
+ }
66
+ export interface SavingsOptions {
67
+ items: GoldenItem[];
68
+ primary: string;
69
+ client: LlmClient;
70
+ /** provider:model candidates; picked from the catalog when left out. */
71
+ candidates?: string[];
72
+ callsPerMonth?: number;
73
+ runs?: number;
74
+ concurrency?: number;
75
+ maxCalls?: number;
76
+ today?: string;
77
+ signal?: AbortSignal;
78
+ }
79
+ export declare function findSavings(options: SavingsOptions): Promise<SavingsResult>;
80
+ /** Text report. Pass volumeHint: false when a volume was asked for (e.g. a log) but none was found. */
81
+ export declare function formatSavingsText(result: SavingsResult, options?: {
82
+ volumeHint?: boolean;
83
+ }): string;
84
+ /** The savings card: Markdown for a pull request or the Action's Summary. */
85
+ export declare function formatSavingsMarkdown(result: SavingsResult): string;
@@ -0,0 +1,220 @@
1
+ // Money-Finder (plan 8.9): cheaper models that answer your real prompts the same way. Picks cheaper candidates
2
+ // on the same provider from the catalog, replays the golden set on them against your model, and keeps a
3
+ // candidate only with nothing broken and at most 2% of answers changed. Savings use the tokens measured in
4
+ // the replay (so a tokenizer that uses more tokens counts) and, when given, your monthly call volume.
5
+ import { billedPriceOn, callCost, formatUsd, localToday, lookupModel, prices, tokenRatio } from "@ai-changeguard/catalog";
6
+ import { parseModelRef } from "@ai-changeguard/llm";
7
+ import { testFallbacks } from "./fallback.js";
8
+ import { modelName, platformForRef } from "./report.js";
9
+ /** At most this share of prompts may change for a cheaper model to count as a safe switch. */
10
+ export const MAX_CHANGED_SHARE = 0.02;
11
+ /** A candidate must be at least this much cheaper per call to be worth a switch. */
12
+ const MIN_SAVING = 0.05;
13
+ /** Prices are judged at the worse of today and this many days ahead, so an introductory price ending soon can't win. */
14
+ const PRICE_HORIZON_DAYS = 60;
15
+ /** Models that retire or reroute within this many days are not suggested. */
16
+ const RETIREMENT_DAYS = 90;
17
+ /** Token mix used to rank candidates before the replay has measured anything. */
18
+ const DEFAULT_TOKENS = { input: 1000, output: 250 };
19
+ function addDays(date, days) {
20
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10);
21
+ }
22
+ /** The higher of the price billed today and the price in PRICE_HORIZON_DAYS, or undefined if either is unknown. */
23
+ function steadyPrice(id, platform, today) {
24
+ const now = billedPriceOn(id, platform, today);
25
+ const later = billedPriceOn(id, platform, addDays(today, PRICE_HORIZON_DAYS));
26
+ if (!now || !later)
27
+ return undefined;
28
+ return { input: Math.max(now.input, later.input), output: Math.max(now.output, later.output) };
29
+ }
30
+ /**
31
+ * Cheaper models on the same provider (so the same API key works), closest in price first: those are the
32
+ * likeliest to answer the same way. Skips previews, dated snapshot IDs (the alias is suggested instead),
33
+ * models retiring soon, and models whose price in two months is unknown.
34
+ */
35
+ /**
36
+ * Why a model is not offered as a cheaper switch, or undefined when it may be: a preview, a dated snapshot
37
+ * ID, a model that retires or reroutes within 90 days, or one whose price two months out is unknown.
38
+ */
39
+ export function candidateProblem(ref, today) {
40
+ const platform = platformForRef(ref);
41
+ const id = modelName(ref);
42
+ if (!platform)
43
+ return "not priced in the catalog (a gateway or unknown provider)";
44
+ if (/preview/.test(id))
45
+ return "a preview model";
46
+ if (/-\d{8}$|-\d{4}-\d{2}-\d{2}$/.test(id))
47
+ return "a dated snapshot ID; test its alias instead";
48
+ const retiring = lookupModel(id).find((m) => m.platform === platform && m.retiresOn <= addDays(today, RETIREMENT_DAYS));
49
+ if (retiring)
50
+ return `${retiring.reroutesTo ? "reroutes" : "retires"} on ${retiring.retiresOn}`;
51
+ if (!steadyPrice(id, platform, today))
52
+ return "its price two months from now is not known";
53
+ return undefined;
54
+ }
55
+ /** Cost of a call at the steady price (the higher of today's and the price in two months). */
56
+ export function steadyCost(ref, tokens, today) {
57
+ const platform = platformForRef(ref);
58
+ const price = platform ? steadyPrice(modelName(ref), platform, today) : undefined;
59
+ return price ? callCost(price, tokens.input, tokens.output) : undefined;
60
+ }
61
+ export function cheaperCandidates(primary, today, options = {}) {
62
+ const { provider } = parseModelRef(primary);
63
+ const platform = platformForRef(primary);
64
+ if (!platform)
65
+ return [];
66
+ const id = modelName(primary);
67
+ const tokens = options.tokens ?? DEFAULT_TOKENS;
68
+ const current = steadyPrice(id, platform, today) ?? billedPriceOn(id, platform, today);
69
+ if (!current)
70
+ return [];
71
+ const currentCost = callCost(current, tokens.input, tokens.output);
72
+ const out = [];
73
+ for (const p of prices) {
74
+ if (p.platform !== platform || p.id === id)
75
+ continue;
76
+ // Closed to new API users: most accounts would get a 404. Name it with --candidates if yours has access.
77
+ if (p.availability === "existing-users")
78
+ continue;
79
+ if (candidateProblem(`${provider}:${p.id}`, today))
80
+ continue;
81
+ const price = steadyPrice(p.id, platform, today);
82
+ const ratio = tokenRatio({ id, platform }, { id: p.id, platform });
83
+ const cost = callCost(price, tokens.input * ratio, tokens.output * ratio);
84
+ if (cost <= currentCost * (1 - MIN_SAVING))
85
+ out.push({ ref: `${provider}:${p.id}`, costPerCall: cost });
86
+ }
87
+ return out.sort((a, b) => b.costPerCall - a.costPerCall).slice(0, options.count ?? 2);
88
+ }
89
+ export async function findSavings(options) {
90
+ const today = options.today ?? localToday();
91
+ const runs = options.runs ?? 3;
92
+ const asked = options.candidates ?? cheaperCandidates(options.primary, today).map((c) => c.ref);
93
+ // Given candidates get the same checks as picked ones, before any call is spent.
94
+ const excluded = asked.flatMap((model) => {
95
+ const reason = candidateProblem(model, today);
96
+ return reason ? [{ model, reason }] : [];
97
+ });
98
+ const candidates = asked.filter((m) => !excluded.some((e) => e.model === m));
99
+ const base = { primary: options.primary, runs, excluded, ...(options.callsPerMonth !== undefined ? { callsPerMonth: options.callsPerMonth } : {}) };
100
+ if (candidates.length === 0)
101
+ return { ...base, calls: 0, candidates: [], skippedPrompts: [] };
102
+ const tested = await testFallbacks({
103
+ items: options.items,
104
+ primary: options.primary,
105
+ candidates,
106
+ client: options.client,
107
+ runs,
108
+ ...(options.concurrency ? { concurrency: options.concurrency } : {}),
109
+ ...(options.maxCalls ? { maxCalls: options.maxCalls } : {}),
110
+ ...(options.signal ? { signal: options.signal } : {}),
111
+ today,
112
+ });
113
+ const results = tested.candidates.map((c) => {
114
+ const compared = c.report.items.length || 1;
115
+ const changedShare = c.report.totals.changed / compared;
116
+ // Priced at the steady price on the tokens each model really used, so a promotion ending soon can't win.
117
+ const current = steadyCost(options.primary, c.report.avgTokens.old, today) ?? c.report.costPerCall?.old;
118
+ const candidate = steadyCost(c.model, c.report.avgTokens.new, today);
119
+ const priced = current !== undefined && candidate !== undefined && c.report.comparedPrompts > 0 ? { current, candidate } : undefined;
120
+ const savingShare = priced && priced.current > 0 ? 1 - priced.candidate / priced.current : undefined;
121
+ // Say which prompt broke and how, so a skip can be checked by hand.
122
+ const firstBroken = c.report.items.find((i) => i.verdict === "broken");
123
+ const brokenDetail = firstBroken ? ` (first: ${firstBroken.id}, ${(firstBroken.reasons[0]?.detail ?? firstBroken.error ?? "").slice(0, 120)})` : "";
124
+ const reason = (c.reason ? `${c.reason}${c.report.totals.broken > 0 ? brokenDetail : ""}` : undefined) ??
125
+ (changedShare > MAX_CHANGED_SHARE
126
+ ? `${c.report.totals.changed} of ${compared} prompts answered differently (more than ${Math.round(MAX_CHANGED_SHARE * 100)}%)`
127
+ : !priced || savingShare === undefined
128
+ ? "no list price known for one of the two models"
129
+ : savingShare < 0
130
+ ? `costs more on your prompts (+${Math.round(-savingShare * 100)}% per call)`
131
+ : savingShare < MIN_SAVING
132
+ ? `only ${Math.round(savingShare * 100)}% cheaper on your prompts`
133
+ : undefined);
134
+ return {
135
+ model: c.model,
136
+ qualifies: !reason,
137
+ ...(reason ? { reason } : {}),
138
+ report: c.report,
139
+ changedShare,
140
+ ...(priced ? { costPerCall: priced } : {}),
141
+ ...(savingShare !== undefined ? { savingShare } : {}),
142
+ ...(priced && options.callsPerMonth !== undefined ? { monthlySaving: (priced.current - priced.candidate) * options.callsPerMonth } : {}),
143
+ };
144
+ });
145
+ const best = results.filter((r) => r.qualifies).sort((a, b) => (b.savingShare ?? 0) - (a.savingShare ?? 0))[0];
146
+ return { ...base, calls: tested.calls, candidates: results, skippedPrompts: tested.skippedPrompts, ...(best ? { best } : {}) };
147
+ }
148
+ function usd(amount) {
149
+ return amount >= 100 ? `$${Math.round(amount).toLocaleString("en-US")}` : formatUsd(amount);
150
+ }
151
+ function verdictLine(c) {
152
+ const t = c.report.totals;
153
+ return `${t.same} same · ${t.changed} changed · ${t.broken} broken on ${c.report.items.length} prompts`;
154
+ }
155
+ function savingText(c) {
156
+ if (!c.costPerCall || c.savingShare === undefined)
157
+ return "";
158
+ const pct = Math.round(c.savingShare * 100);
159
+ const month = c.monthlySaving !== undefined ? `, about ${usd(c.monthlySaving)} a month` : "";
160
+ return `${pct}% cheaper per call (${usd(c.costPerCall.current)} → ${usd(c.costPerCall.candidate)})${month}`;
161
+ }
162
+ function skippedNote(result) {
163
+ const n = result.skippedPrompts.length;
164
+ return n ? `${result.primary} did not answer ${n} prompt${n === 1 ? "" : "s"} (${result.skippedPrompts.slice(0, 5).join(", ")}${n > 5 ? ", ..." : ""}), so ${n === 1 ? "it was" : "they were"} not compared.` : undefined;
165
+ }
166
+ /** Text report. Pass volumeHint: false when a volume was asked for (e.g. a log) but none was found. */
167
+ export function formatSavingsText(result, options = {}) {
168
+ const out = [`Money-Finder: cheaper models for ${result.primary}`];
169
+ for (const e of result.excluded)
170
+ out.push(` NOT TESTED ${e.model}: ${e.reason}`);
171
+ if (result.candidates.length === 0) {
172
+ out.push(result.excluded.length ? "No candidate left to test." : "No cheaper model on the same provider to test (or no list price known for yours).");
173
+ return out.join("\n");
174
+ }
175
+ if (result.best) {
176
+ out.push(`SAVE ${result.primary} → ${result.best.model}: ${savingText(result.best)}`);
177
+ out.push(` ${verdictLine(result.best)} (${result.runs} run${result.runs === 1 ? "" : "s"} each)`);
178
+ out.push(` Switch: ai-change-guard switch . --from ${modelName(result.primary)} --to ${modelName(result.best.model)} --write`);
179
+ }
180
+ else {
181
+ out.push("No cheaper model answered your prompts the same way. Keep the model you have.");
182
+ }
183
+ for (const c of result.candidates) {
184
+ if (c === result.best)
185
+ continue;
186
+ out.push(` ${c.qualifies ? "ALSO" : "SKIP"} ${c.model}: ${c.qualifies ? savingText(c) : c.reason}`);
187
+ }
188
+ const skipped = skippedNote(result);
189
+ if (skipped)
190
+ out.push(`WARNING: ${skipped}`);
191
+ if (result.callsPerMonth === undefined && result.best && options.volumeHint !== false)
192
+ out.push("Add --calls-per-month or --log ai-calls.jsonl to see the monthly saving.");
193
+ out.push(`${result.calls} calls used. Costs use list prices, at the higher of today's and the price two months out (no batch, cache or volume discounts).`);
194
+ return out.join("\n");
195
+ }
196
+ /** The savings card: Markdown for a pull request or the Action's Summary. */
197
+ export function formatSavingsMarkdown(result) {
198
+ const out = [`## Money-Finder: \`${result.primary}\``, ""];
199
+ if (result.candidates.length === 0) {
200
+ return [...out, "No cheaper model on the same provider to test.", ...result.excluded.map((e) => `- Not tested: \`${e.model}\`: ${e.reason}`)].join("\n");
201
+ }
202
+ if (result.best) {
203
+ out.push(`**Switch to \`${result.best.model}\`: ${savingText(result.best)}.**`, "", `On your real prompts: ${verdictLine(result.best)}, ${result.runs} runs each.`);
204
+ }
205
+ else {
206
+ out.push("**No cheaper model answered your prompts the same way.** Keep the model you have.");
207
+ }
208
+ out.push("", "| Candidate | Result | Cost per call |", "| --- | --- | --- |");
209
+ for (const c of result.candidates) {
210
+ const cost = c.costPerCall ? `${usd(c.costPerCall.current)} → ${usd(c.costPerCall.candidate)}` : "unknown";
211
+ out.push(`| \`${c.model}\` | ${c.qualifies ? `Passes: ${verdictLine(c)}` : `Skipped: ${c.reason}`} | ${cost} |`);
212
+ }
213
+ for (const e of result.excluded)
214
+ out.push(`| \`${e.model}\` | Not tested: ${e.reason} | |`);
215
+ const skipped = skippedNote(result);
216
+ if (skipped)
217
+ out.push("", `> **Warning:** ${skipped}`);
218
+ out.push("", "List prices at the higher of today's and the price two months out; no batch, cache or volume discounts.");
219
+ return out.join("\n");
220
+ }
@@ -0,0 +1,21 @@
1
+ export interface JsonSchema {
2
+ type?: string | string[];
3
+ properties?: Record<string, JsonSchema>;
4
+ required?: string[];
5
+ additionalProperties?: boolean;
6
+ items?: JsonSchema;
7
+ enum?: unknown[];
8
+ minItems?: number;
9
+ maxItems?: number;
10
+ minLength?: number;
11
+ maxLength?: number;
12
+ minimum?: number;
13
+ maximum?: number;
14
+ }
15
+ export declare function validateSchema(value: unknown, schema: JsonSchema, path?: string): string[];
16
+ export declare function extractJson(text: string): {
17
+ ok: true;
18
+ value: unknown;
19
+ } | {
20
+ ok: false;
21
+ };
package/dist/schema.js ADDED
@@ -0,0 +1,73 @@
1
+ function typeOf(value) {
2
+ if (value === null)
3
+ return "null";
4
+ if (Array.isArray(value))
5
+ return "array";
6
+ if (typeof value === "number")
7
+ return Number.isInteger(value) ? "integer" : "number";
8
+ return typeof value;
9
+ }
10
+ function matchesType(value, type) {
11
+ const actual = typeOf(value);
12
+ return actual === type || (type === "number" && actual === "integer");
13
+ }
14
+ export function validateSchema(value, schema, path = "$") {
15
+ if (schema.type) {
16
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
17
+ if (!types.some((t) => matchesType(value, t)))
18
+ return [`${path}: expected ${types.join(" or ")}, got ${typeOf(value)}`];
19
+ }
20
+ const errors = [];
21
+ if (schema.enum && !schema.enum.some((e) => JSON.stringify(e) === JSON.stringify(value))) {
22
+ errors.push(`${path}: not one of the allowed values`);
23
+ }
24
+ if (typeof value === "string") {
25
+ if (schema.minLength !== undefined && value.length < schema.minLength)
26
+ errors.push(`${path}: shorter than ${schema.minLength}`);
27
+ if (schema.maxLength !== undefined && value.length > schema.maxLength)
28
+ errors.push(`${path}: longer than ${schema.maxLength}`);
29
+ }
30
+ if (typeof value === "number") {
31
+ if (schema.minimum !== undefined && value < schema.minimum)
32
+ errors.push(`${path}: below ${schema.minimum}`);
33
+ if (schema.maximum !== undefined && value > schema.maximum)
34
+ errors.push(`${path}: above ${schema.maximum}`);
35
+ }
36
+ if (Array.isArray(value)) {
37
+ if (schema.minItems !== undefined && value.length < schema.minItems)
38
+ errors.push(`${path}: fewer than ${schema.minItems} items`);
39
+ if (schema.maxItems !== undefined && value.length > schema.maxItems)
40
+ errors.push(`${path}: more than ${schema.maxItems} items`);
41
+ if (schema.items)
42
+ value.forEach((v, i) => errors.push(...validateSchema(v, schema.items, `${path}[${i}]`)));
43
+ }
44
+ if (typeOf(value) === "object") {
45
+ const obj = value;
46
+ for (const key of schema.required ?? [])
47
+ if (!(key in obj))
48
+ errors.push(`${path}: missing "${key}"`);
49
+ for (const [key, sub] of Object.entries(schema.properties ?? {})) {
50
+ if (key in obj)
51
+ errors.push(...validateSchema(obj[key], sub, `${path}.${key}`));
52
+ }
53
+ if (schema.additionalProperties === false) {
54
+ for (const key of Object.keys(obj)) {
55
+ if (!schema.properties || !(key in schema.properties))
56
+ errors.push(`${path}: unexpected "${key}"`);
57
+ }
58
+ }
59
+ }
60
+ return errors;
61
+ }
62
+ export function extractJson(text) {
63
+ let candidate = text.trim();
64
+ const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(candidate);
65
+ if (fenced?.[1] !== undefined)
66
+ candidate = fenced[1];
67
+ try {
68
+ return { ok: true, value: JSON.parse(candidate) };
69
+ }
70
+ catch {
71
+ return { ok: false };
72
+ }
73
+ }
@@ -0,0 +1 @@
1
+ export declare function similarity(a: string, b: string): number;