sprag-cli 3.99.1 → 3.101.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/bin/cli.js CHANGED
@@ -934,10 +934,17 @@ async function main() {
934
934
  : await parseAllSessions({ days: Math.max(1, Math.ceil(daysNeeded)), projectFilter, sinceMs: since });
935
935
  // 월 경계에 걸친 세션은 월초 이후 요청만 남긴다. 그러지 않으면 1일 자정을
936
936
  // 넘긴 세션의 전월분이 이번 달 지출에 그대로 들어온다.
937
- monthSpendInfo = monthSpend(await sessionsSince(monthSessions, since));
937
+ monthSpendInfo = monthSpend(await sessionsSince(monthSessions, since), new Date(), { ledger: !projectFilter });
938
938
  } catch (e) {
939
939
  debug('month-spend', e);
940
940
  }
941
+ // 사용량 장부: Claude Code 가 transcript 를 지운 뒤에도 월 지출이 줄지 않도록
942
+ // 토큰을 일자별로 남긴다(#15). 실패해도 통계선은 그대로 그린다.
943
+ try {
944
+ if (monthSessions) (await import('../src/usage-ledger.js')).recordUsage(monthSessions);
945
+ } catch (e) {
946
+ debug('usage-ledger', e);
947
+ }
941
948
  }
942
949
 
943
950
  // 모델별 사용 비중: `sprag saved` 와 같은 기간(라우팅 초기화 기록, 없으면 월초)의
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.99.1",
3
+ "version": "3.101.0",
4
4
  "description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,16 +10,54 @@ import { estimateCost, estimateCostAcross } from './cost.js';
10
10
  import { gatewayPriceFor } from './litellm-models.js';
11
11
  import { gatewayBase } from './gateway-auth.js';
12
12
 
13
- export function sessionCost(totals, model, { env = process.env, now } = {}) {
14
- if (!gatewayBase(env)) return estimateCost(totals, model);
15
- const price = gatewayPriceFor(model, env, now);
13
+ // `at` is when the tokens were spent; list prices and gateway prices (from the
14
+ // gateway's dated price history) are looked up for that time.
15
+ export function sessionCost(totals, model, { env = process.env, now, at } = {}) {
16
+ if (!gatewayBase(env)) return estimateCost(totals, model, { at });
17
+ const price = gatewayPriceFor(model, env, now, at);
16
18
  return price ? estimateCost(totals, model, { price }) : null;
17
19
  }
18
20
 
19
- /** One priced part per model that spent tokens, or the whole at its one model. */
21
+ /**
22
+ * Several totals folded into one, `long` included. Returns the entry itself
23
+ * for a list of one.
24
+ */
25
+ export function sumTotals(list) {
26
+ if (list.length === 1) return list[0];
27
+ const out = {};
28
+ for (const t of list) {
29
+ for (const [k, v] of Object.entries(t)) {
30
+ if (k === 'long') {
31
+ out.long = out.long || {};
32
+ for (const [lk, lv] of Object.entries(v)) out.long[lk] = (out.long[lk] || 0) + lv;
33
+ } else out[k] = (out[k] || 0) + v;
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /**
40
+ * One priced part per model that spent tokens, or the whole at its one model.
41
+ * `at` is when the tokens were spent (the start of the session or run) and
42
+ * `byDay` holds that model's totals per UTC day, present only when the
43
+ * session or run crossed a UTC midnight. Price rows change at UTC midnight,
44
+ * so partCost prices each day at its own row instead of one row for all (#15).
45
+ */
20
46
  function partsByModel(x) {
21
- if (!x.modelTotals) return [{ totals: x.totals, model: x.model }];
22
- return Object.entries(x.modelTotals).map(([model, totals]) => ({ totals, model }));
47
+ const t = x.startTime || x.endTime;
48
+ const at = t ? new Date(t).getTime() : undefined;
49
+ const dayTotals = x.dayTotals;
50
+ const dayParts = (model, only) => {
51
+ if (!dayTotals) return {};
52
+ const byDay = {};
53
+ for (const [day, models] of Object.entries(dayTotals)) {
54
+ const hit = only ? models[model] : sumTotals(Object.values(models));
55
+ if (hit) byDay[day] = hit;
56
+ }
57
+ return Object.keys(byDay).length ? { byDay } : {};
58
+ };
59
+ if (!x.modelTotals) return [{ totals: x.totals, model: x.model, at, ...dayParts(x.model, false) }];
60
+ return Object.entries(x.modelTotals).map(([model, totals]) => ({ totals, model, at, ...dayParts(model, true) }));
23
61
  }
24
62
 
25
63
  /**
@@ -37,11 +75,30 @@ export function pricedParts(session) {
37
75
  ];
38
76
  }
39
77
 
78
+ /**
79
+ * Cost of one priced part. A part that crossed UTC midnights is priced day by
80
+ * day, each day at the price row in effect then; the figures are summed. One
81
+ * unpriced day makes the whole part unpriced (null), as for a single price.
82
+ * Without `byDay` the part is priced at its start time.
83
+ */
84
+ export function partCost(part, { env = process.env, now } = {}) {
85
+ if (!part.byDay) return sessionCost(part.totals, part.model, { env, now, at: part.at });
86
+ const acc = { actual: 0, noCacheCost: 0, savings: 0, scenario5mCost: 0, extraCostIf5m: 0, extraCostIf5mApplicable: false, tier: null };
87
+ for (const day of Object.keys(part.byDay).sort()) {
88
+ const c = sessionCost(part.byDay[day], part.model, { env, now, at: `${day}T12:00:00Z` });
89
+ if (!c) return null;
90
+ for (const k of ['actual', 'noCacheCost', 'savings', 'scenario5mCost', 'extraCostIf5m']) acc[k] += c[k];
91
+ acc.extraCostIf5mApplicable = acc.extraCostIf5mApplicable || c.extraCostIf5mApplicable;
92
+ acc.tier = c.tier;
93
+ }
94
+ return { ...acc, savingsRate: acc.noCacheCost > 0 ? acc.savings / acc.noCacheCost : 0 };
95
+ }
96
+
40
97
  /** Like estimateCostAcross, plus how many priced parts (a session, a subagent run, or one model's share of either) had no price and were left out. */
41
98
  export function sessionCostAcross(sessions, opts = {}) {
42
99
  let unpriced = 0;
43
- const total = estimateCostAcross((sessions || []).flatMap(pricedParts), (totals, model) => {
44
- const c = sessionCost(totals, model, opts);
100
+ const total = estimateCostAcross((sessions || []).flatMap(pricedParts), (totals, model, part) => {
101
+ const c = partCost(part, opts);
45
102
  if (!c) unpriced++;
46
103
  return c;
47
104
  });
package/src/cost.js CHANGED
@@ -16,125 +16,239 @@ import { priceForPrompt } from './gateway-prices.js';
16
16
  // `totals.long` (see parser.js) rather than relying on session-wide sums.
17
17
  export const LONG_PROMPT_THRESHOLD = 100_000;
18
18
 
19
- const PRICING = {
19
+ // Each tier lists its rate cards oldest first, with the date each took effect
20
+ // (`from`, a UTC YYYY-MM-DD; null = since the model launched). A price change
21
+ // or a correction is a new row, never an edit of an old one, so a run is
22
+ // always priced at the rate that applied when it happened (#15).
23
+ const PRICE_HISTORY = {
20
24
  // Fable 5.1 / Mythos 5.1 — same prices as Fable 5 except cache reads, which
21
25
  // drop to $0.25.
22
- 'claude-fable-5-1': {
26
+ 'claude-fable-5-1': [{
27
+ from: null,
23
28
  input: 10.0,
24
29
  cacheWrite5m: 12.5,
25
30
  cacheWrite1h: 20.0,
26
31
  cacheRead: 0.25,
27
32
  output: 50.0,
28
- },
33
+ }],
29
34
  // Fable 5 / Mythos 5 — premium tier above Opus ($10/$50). Cache write
30
35
  // rates follow the standard multipliers (1.25x input for 5m, 2x for 1h),
31
36
  // cache read is 0.1x input.
32
- 'claude-fable-5': {
37
+ 'claude-fable-5': [{
38
+ from: null,
33
39
  input: 10.0,
34
40
  cacheWrite5m: 12.5,
35
41
  cacheWrite1h: 20.0,
36
42
  cacheRead: 1.0,
37
43
  output: 50.0,
38
- },
44
+ }],
39
45
  // Opus 5.5 — cheaper than the Opus 4.5-5 tier below.
40
- 'claude-opus-5-5': {
46
+ 'claude-opus-5-5': [{
47
+ from: null,
41
48
  input: 4.0,
42
49
  cacheWrite5m: 5.0,
43
50
  cacheWrite1h: 8.0,
44
51
  cacheRead: 0.2,
45
52
  output: 20.0,
46
- },
53
+ }],
47
54
  // Opus 4.5+ (new pricing tier — includes 4.5, 4.6, 4.7, 4.8, and future)
48
- 'claude-opus-new': {
55
+ 'claude-opus-new': [{
56
+ from: null,
49
57
  input: 5.0,
50
58
  cacheWrite5m: 6.25,
51
59
  cacheWrite1h: 10.0,
52
60
  cacheRead: 0.5,
53
61
  output: 25.0,
54
- },
62
+ }],
55
63
  // Opus 4 / 4.1 / Opus 3 (legacy premium pricing)
56
- 'claude-opus-legacy': {
64
+ 'claude-opus-legacy': [{
65
+ from: null,
57
66
  input: 15.0,
58
67
  cacheWrite5m: 18.75,
59
68
  cacheWrite1h: 30.0,
60
69
  cacheRead: 1.5,
61
70
  output: 75.0,
62
- },
71
+ }],
63
72
  // Sonnet 5 — standard price is $2/$10. The rise to $3/$15 planned for
64
73
  // 2026-09-01 was cancelled, so this is not an introductory rate.
65
- 'claude-sonnet-5': {
74
+ 'claude-sonnet-5': [{
75
+ from: null,
66
76
  input: 2.0,
67
77
  cacheWrite5m: 2.5,
68
78
  cacheWrite1h: 4.0,
69
79
  cacheRead: 0.2,
70
80
  output: 10.0,
71
- },
72
- // Sonnet 5.5 — same as Sonnet 5 except cache reads at $0.10.
73
- 'claude-sonnet-5-5': {
81
+ }],
82
+ // Sonnet 5.5 — launched 2026-09-28 with Sonnet 5's prices. Cache reads were
83
+ // cut from $0.20 to $0.10 on 2026-10-07 ("We've lowered the price of prompt
84
+ // cache reads on Claude Sonnet 5.5 from $0.20 USD to $0.10 USD", platform
85
+ // release notes); every other rate is unchanged.
86
+ 'claude-sonnet-5-5': [{
87
+ from: null,
88
+ input: 2.0,
89
+ cacheWrite5m: 2.5,
90
+ cacheWrite1h: 4.0,
91
+ cacheRead: 0.2,
92
+ output: 10.0,
93
+ }, {
94
+ from: '2026-10-07',
74
95
  input: 2.0,
75
96
  cacheWrite5m: 2.5,
76
97
  cacheWrite1h: 4.0,
77
98
  cacheRead: 0.1,
78
99
  output: 10.0,
79
- },
100
+ }],
80
101
  // Sonnet 4 / 4.5 / 4.6 / 3.7
81
- 'claude-sonnet': {
102
+ 'claude-sonnet': [{
103
+ from: null,
82
104
  input: 3.0,
83
105
  cacheWrite5m: 3.75,
84
106
  cacheWrite1h: 6.0,
85
107
  cacheRead: 0.3,
86
108
  output: 15.0,
87
- },
109
+ }],
88
110
  // Haiku 5.5, prompt <= LONG_PROMPT_THRESHOLD tokens.
89
- 'claude-haiku-5-5': {
111
+ 'claude-haiku-5-5': [{
112
+ from: null,
90
113
  input: 0.1,
91
114
  cacheWrite5m: 0.125,
92
115
  cacheWrite1h: 0.2,
93
116
  cacheRead: 0.01,
94
117
  output: 0.5,
95
- },
118
+ }],
96
119
  // Haiku 5.5, prompt > LONG_PROMPT_THRESHOLD tokens. Not returned by
97
120
  // detectPricingTier: estimateCost applies it to `totals.long` only.
98
- 'claude-haiku-5-5-long': {
121
+ 'claude-haiku-5-5-long': [{
122
+ from: null,
99
123
  input: 0.5,
100
124
  cacheWrite5m: 0.625,
101
125
  cacheWrite1h: 1.0,
102
126
  cacheRead: 0.05,
103
127
  output: 2.5,
104
- },
128
+ }],
105
129
  // Haiku 4.5
106
- 'claude-haiku-4-5': {
130
+ 'claude-haiku-4-5': [{
131
+ from: null,
107
132
  input: 1.0,
108
133
  cacheWrite5m: 1.25,
109
134
  cacheWrite1h: 2.0,
110
135
  cacheRead: 0.1,
111
136
  output: 5.0,
112
- },
137
+ }],
113
138
  // Haiku 3.5
114
- 'claude-haiku-3-5': {
139
+ 'claude-haiku-3-5': [{
140
+ from: null,
115
141
  input: 0.8,
116
142
  cacheWrite5m: 1.0,
117
143
  cacheWrite1h: 1.6,
118
144
  cacheRead: 0.08,
119
145
  output: 4.0,
120
- },
146
+ }],
121
147
  // Haiku 3 (deprecated)
122
- 'claude-haiku-3': {
148
+ 'claude-haiku-3': [{
149
+ from: null,
123
150
  input: 0.25,
124
151
  cacheWrite5m: 0.3,
125
152
  cacheWrite1h: 0.5,
126
153
  cacheRead: 0.03,
127
154
  output: 1.25,
128
- },
155
+ }],
156
+ };
157
+
158
+ /** Milliseconds for a `from` date, or -Infinity for "since launch". */
159
+ const fromMs = (from) => (from ? Date.parse(`${from}T00:00:00Z`) : -Infinity);
160
+
161
+ const toMs = (at) => {
162
+ if (at === undefined || at === null) return Date.now();
163
+ const n = typeof at === 'number' ? at : Date.parse(at);
164
+ return Number.isFinite(n) ? n : Date.now();
165
+ };
166
+
167
+ /**
168
+ * The rate card of a tier in effect at `at` (ms or a date string; default
169
+ * now): the newest row whose `from` is not after it. A time before the first
170
+ * dated row gets the first row, since that is the earliest price known.
171
+ */
172
+ export function ratesAt(tier, at) {
173
+ const rows = PRICE_HISTORY[tier];
174
+ if (!rows) return null;
175
+ const t = toMs(at);
176
+ let pick = rows[0];
177
+ for (const r of rows) if (fromMs(r.from) <= t) pick = r;
178
+ return pick;
179
+ }
180
+
181
+ /** Every dated row of a tier, oldest first (for audits and the upstream watch). */
182
+ export function priceHistory(tier) {
183
+ return (PRICE_HISTORY[tier] || []).map((r) => ({ ...r }));
184
+ }
185
+
186
+ // What a bare alias meant over time: the model Claude Code sent for it from
187
+ // each date on, oldest first. An alias moves to a new model on launch day, so
188
+ // a run recorded as `opus` is priced as the Opus that was current then, not
189
+ // the oldest Opus in the table (#13).
190
+ // Dates are the launch days in the platform release notes
191
+ // (https://platform.claude.com/docs/en/release-notes/overview); Claude Code
192
+ // moved its aliases on or shortly after them. A time before the first row
193
+ // resolves to the first row.
194
+ const ALIAS_HISTORY = {
195
+ opus: [
196
+ { from: '2025-05-22', model: 'claude-opus-4-20250514' },
197
+ { from: '2025-08-05', model: 'claude-opus-4-1-20250805' },
198
+ { from: '2025-11-24', model: 'claude-opus-4-5-20251101' },
199
+ { from: '2026-02-05', model: 'claude-opus-4-6' },
200
+ { from: '2026-04-16', model: 'claude-opus-4-7' },
201
+ { from: '2026-05-28', model: 'claude-opus-4-8' },
202
+ { from: '2026-07-24', model: 'claude-opus-5' },
203
+ { from: '2026-09-22', model: 'claude-opus-5-5' },
204
+ ],
205
+ sonnet: [
206
+ { from: '2025-05-22', model: 'claude-sonnet-4-20250514' },
207
+ { from: '2025-09-29', model: 'claude-sonnet-4-5-20250929' },
208
+ { from: '2026-02-17', model: 'claude-sonnet-4-6' },
209
+ { from: '2026-06-30', model: 'claude-sonnet-5' },
210
+ { from: '2026-09-28', model: 'claude-sonnet-5-5' },
211
+ ],
212
+ haiku: [
213
+ { from: null, model: 'claude-3-5-haiku-20241022' },
214
+ { from: '2025-10-15', model: 'claude-haiku-4-5-20251001' },
215
+ { from: '2026-10-07', model: 'claude-haiku-5-5' },
216
+ ],
217
+ fable: [
218
+ { from: '2026-06-09', model: 'claude-fable-5' },
219
+ { from: '2026-09-01', model: 'claude-fable-5-1' },
220
+ ],
129
221
  };
130
222
 
223
+ // Spellings that name an alias rather than a model: the bare family, its
224
+ // `[1m]` form, and the Claude Code shorthands that resolve to a family.
225
+ const ALIAS_OF = { opus: 'opus', opusplan: 'opus', sonnet: 'sonnet', haiku: 'haiku', fable: 'fable', best: 'fable' };
226
+
227
+ /**
228
+ * The model a bare alias stood for at `at`, or null when `model` is not an
229
+ * alias (a full id passes through untouched at the call site).
230
+ */
231
+ export function resolveAlias(model, at) {
232
+ if (typeof model !== 'string') return null;
233
+ const key = ALIAS_OF[model.trim().toLowerCase().replace(/\[1m\]$/, '')];
234
+ const rows = key && ALIAS_HISTORY[key];
235
+ if (!rows || rows.length === 0) return null;
236
+ const t = toMs(at);
237
+ let pick = null;
238
+ for (const r of rows) if (fromMs(r.from) <= t) pick = r;
239
+ return (pick || rows[0]).model;
240
+ }
241
+
131
242
  /**
132
243
  * Detect pricing tier from Claude model identifier.
133
244
  * Examples: 'claude-opus-4-7', 'claude-sonnet-4-5', 'claude-haiku-4-5'.
245
+ * A bare alias (`opus`, `sonnet[1m]`) is first resolved to the model it meant
246
+ * at `at` (default now).
134
247
  */
135
- export function detectPricingTier(model) {
248
+ export function detectPricingTier(model, { at } = {}) {
136
249
  if (!model) return 'claude-sonnet';
137
- const m = model.toLowerCase();
250
+ const resolved = resolveAlias(model, at);
251
+ const m = (resolved || model).toLowerCase();
138
252
 
139
253
  // Fable 5 / Mythos 5 — must be checked before the generic fallback:
140
254
  // without this, 'claude-fable-5' fell through to the Sonnet tier and
@@ -283,10 +397,13 @@ function tokensToMillions(n) {
283
397
  * ephemeral5m — portion of cacheCreation billed at 5m rate (1.25x input)
284
398
  * ephemeral1h — portion of cacheCreation billed at 1h rate (2x input)
285
399
  * output — output tokens
400
+ *
401
+ * `at` (ms or a date string, default now) is when the tokens were spent: the
402
+ * list price is the one in effect then (see ratesAt).
286
403
  */
287
- export function estimateCost(totals, model, { price } = {}) {
404
+ export function estimateCost(totals, model, { price, at } = {}) {
288
405
  if (price) return estimateCostAtPrice(totals, price);
289
- const tier = detectPricingTier(model);
406
+ const tier = detectPricingTier(model, { at });
290
407
 
291
408
  // Haiku 5.5 prices each request by its own prompt length, so the long-prompt
292
409
  // part (`totals.long`, same shape) is priced at the long rates and the rest
@@ -294,8 +411,8 @@ export function estimateCost(totals, model, { price } = {}) {
294
411
  let c;
295
412
  if (tier === 'claude-haiku-5-5' && totals.long) {
296
413
  const short = subtractTotals(totals, totals.long);
297
- const a = priceTotals(short, PRICING[tier]);
298
- const b = priceTotals(totals.long, PRICING['claude-haiku-5-5-long']);
414
+ const a = priceTotals(short, ratesAt(tier, at));
415
+ const b = priceTotals(totals.long, ratesAt('claude-haiku-5-5-long', at));
299
416
  c = {
300
417
  actual: a.actual + b.actual,
301
418
  noCacheCost: a.noCacheCost + b.noCacheCost,
@@ -303,7 +420,7 @@ export function estimateCost(totals, model, { price } = {}) {
303
420
  write1h: a.write1h + b.write1h,
304
421
  };
305
422
  } else {
306
- c = priceTotals(totals, PRICING[tier]);
423
+ c = priceTotals(totals, ratesAt(tier, at));
307
424
  }
308
425
  const { actual, noCacheCost, scenario5mCost, write1h } = c;
309
426
 
@@ -449,13 +566,13 @@ function estimateCostAtPrice(totals, price) {
449
566
  * Sessions whose model has no known rate are skipped, as month-spend does.
450
567
  * `estimate` lets a caller price by path (see claude-price.js); null skips a session.
451
568
  */
452
- export function estimateCostAcross(sessions, estimate = estimateCost) {
569
+ export function estimateCostAcross(sessions, estimate = (totals, model) => estimateCost(totals, model)) {
453
570
  const acc = { actual: 0, noCacheCost: 0, scenario5mCost: 0, extraCostIf5mApplicable: false };
454
571
  const tiers = new Map();
455
572
  for (const s of sessions || []) {
456
573
  if (!s?.totals) continue;
457
574
  let c;
458
- try { c = estimate(s.totals, s.model); } catch { continue; }
575
+ try { c = estimate(s.totals, s.model, s); } catch { continue; }
459
576
  if (!c) continue;
460
577
  acc.actual += c.actual;
461
578
  acc.noCacheCost += c.noCacheCost;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * gateway-price-history: dated copies of a LiteLLM gateway's price table (#15).
3
+ *
4
+ * `/model/info` only reports today's prices, so a figure for past usage priced
5
+ * from the current table drifts whenever the gateway changes a price. Every
6
+ * successful refresh is recorded here instead, and a call is priced with the
7
+ * table in effect when it happened.
8
+ *
9
+ * File: <userDataDir>/gateway-price-history.json
10
+ * { "version": 1,
11
+ * "gateways": { "<base>": { "checkedAt": <ms of the latest successful fetch>,
12
+ * "rows": [ { "from": "YYYY-MM-DD", "prices": {...} } ] } } }
13
+ * Rows are oldest first; `from` is the UTC day of the fetch that first showed
14
+ * those prices. A row is appended only when the prices changed, and a fetch on
15
+ * the day of the last row replaces it.
16
+ *
17
+ * Same principle as the rest of the gateway path: only the gateway's own
18
+ * numbers are used and a model its table lacks stays unpriced (null). Prices
19
+ * for a time later than `checkedAt + PRICE_MAX_AGE_MS` are unknown, the same
20
+ * freshness rule the current table follows.
21
+ *
22
+ * An install that refreshed before this file existed has its table in
23
+ * profile-map.json (`gateway.prices`). That table stands in as a single row
24
+ * from its `fetchedAt` day until the history has an entry for the gateway.
25
+ */
26
+
27
+ import { readFileSync, statSync } from 'node:fs';
28
+ import { join } from 'node:path';
29
+ import { userDataDir } from './paths.js';
30
+ import { writeStateFile } from './state-file.js';
31
+ import { PRICE_MAX_AGE_MS } from './gateway-prices.js';
32
+ import { loadProfileMap } from './model-alias.js';
33
+ import { normalizeCandidate } from './litellm-models.js';
34
+
35
+ export const HISTORY_VERSION = 1;
36
+
37
+ export function priceHistoryPath() {
38
+ return join(userDataDir(), 'gateway-price-history.json');
39
+ }
40
+
41
+ const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
42
+
43
+ // Sorted keys at every level, so equal tables compare equal whatever order the gateway listed them in.
44
+ function canonical(value) {
45
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
46
+ if (value && typeof value === 'object') {
47
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
48
+ }
49
+ return JSON.stringify(value) ?? 'null';
50
+ }
51
+
52
+ let cache = null; // { path, mtimeMs, size, data }
53
+
54
+ function readHistory() {
55
+ const path = priceHistoryPath();
56
+ try {
57
+ const st = statSync(path);
58
+ if (cache && cache.path === path && cache.mtimeMs === st.mtimeMs && cache.size === st.size) return cache.data;
59
+ const data = JSON.parse(readFileSync(path, 'utf8'));
60
+ const ok = data && data.version === HISTORY_VERSION && data.gateways && typeof data.gateways === 'object';
61
+ const out = ok ? data : { version: HISTORY_VERSION, gateways: {} };
62
+ cache = { path, mtimeMs: st.mtimeMs, size: st.size, data: out };
63
+ return out;
64
+ } catch {
65
+ return { version: HISTORY_VERSION, gateways: {} };
66
+ }
67
+ }
68
+
69
+ /** The table profile-map.json holds for `base`, as a one-row history, or null. */
70
+ function seedEntry(base) {
71
+ try {
72
+ const gw = loadProfileMap()?.gateway;
73
+ if (!gw || gw.base !== base || !gw.prices || typeof gw.prices !== 'object') return null;
74
+ const fetchedAt = Date.parse(gw.fetchedAt);
75
+ if (!Number.isFinite(fetchedAt)) return null;
76
+ return { checkedAt: fetchedAt, rows: [{ from: dayOf(fetchedAt), prices: gw.prices }] };
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Record a successful fetch of `base`'s table. Appends a row only when the
84
+ * prices differ from the last row; on the same UTC day as the last row the row
85
+ * is replaced instead. Call it before the profile-map section is overwritten:
86
+ * for a gateway the history has not seen yet, the table still stored there is
87
+ * kept as the first row, so the prices known before this fetch are not lost.
88
+ */
89
+ export function recordGatewayPrices(base, prices, fetchedAtMs = Date.now()) {
90
+ if (!base || !prices || typeof prices !== 'object' || !Number.isFinite(fetchedAtMs)) return;
91
+ const data = readHistory();
92
+ const gateways = { ...data.gateways };
93
+ const prev = gateways[base] && Array.isArray(gateways[base].rows) ? gateways[base] : seedEntry(base);
94
+ const rows = prev ? prev.rows.map((r) => ({ from: r.from, prices: r.prices })) : [];
95
+ const from = dayOf(fetchedAtMs);
96
+ const last = rows[rows.length - 1];
97
+ if (!last || canonical(last.prices) !== canonical(prices)) {
98
+ if (last && last.from === from) rows[rows.length - 1] = { from, prices };
99
+ else rows.push({ from, prices });
100
+ }
101
+ gateways[base] = { checkedAt: fetchedAtMs, rows };
102
+ writeStateFile(priceHistoryPath(), JSON.stringify({ version: HISTORY_VERSION, gateways }) + '\n');
103
+ cache = null;
104
+ }
105
+
106
+ /**
107
+ * Price of `model` on `base` at time `at` (ms or ISO string): the newest row
108
+ * whose day is not after the UTC day of `at`, or the first row for an earlier
109
+ * time. null when the gateway has no history, `at` is later than the freshness
110
+ * limit, or that row lacks the model (or lists it as ambiguous).
111
+ */
112
+ export function gatewayPriceAt(model, base, at) {
113
+ if (!base || typeof model !== 'string' || !model) return null;
114
+ const t = typeof at === 'number' ? at : Date.parse(at);
115
+ if (!Number.isFinite(t)) return null;
116
+ const entry = readHistory().gateways[base] ?? seedEntry(base);
117
+ if (!entry || !Array.isArray(entry.rows) || entry.rows.length === 0) return null;
118
+ if (!Number.isFinite(entry.checkedAt) || t > entry.checkedAt + PRICE_MAX_AGE_MS) return null;
119
+ const day = dayOf(t);
120
+ let row = entry.rows[0];
121
+ for (const r of entry.rows) if (r.from <= day) row = r;
122
+ const prices = row?.prices;
123
+ if (!prices || typeof prices !== 'object') return null;
124
+ for (const key of [model, normalizeCandidate(model)]) {
125
+ if (key && Object.hasOwn(prices, key)) return prices[key] || null;
126
+ }
127
+ return null;
128
+ }
@@ -29,6 +29,7 @@ import { loadProfileMap, updateProfileMap, resetModelAliasCache, profileIdFrom,
29
29
  import { isRecognizedModelId } from './cost.js';
30
30
  import { deploymentPrice, mergePrices, PRICE_MAX_AGE_MS } from './gateway-prices.js';
31
31
  import { debug } from './debug.js';
32
+ import { recordGatewayPrices, gatewayPriceAt } from './gateway-price-history.js';
32
33
 
33
34
  /** 게이트웨이 모델 맵의 신선도 기준. 배포 구성은 하루에 여러 번 바뀌지 않습니다. */
34
35
  export const MODEL_MAP_TTL_MS = 24 * 60 * 60 * 1000;
@@ -58,7 +59,7 @@ const PROVIDER_PREFIXES = ['bedrock/converse/', 'bedrock/', 'openai/', 'vertex_a
58
59
  * 줄이지 않으면 isRecognizedModelId()가 계열명을 품은 ARN 전체를 "인식됨"으로
59
60
  * 판정해(cost.js의 정규식 한 줄이므로) 계정 ID가 값 쪽으로도 새어 나갑니다.
60
61
  */
61
- function normalizeCandidate(id) {
62
+ export function normalizeCandidate(id) {
62
63
  if (typeof id !== 'string' || !id) return '';
63
64
  let s = id;
64
65
  if (isGatewayModelId(s)) return profileIdFrom(s) || '';
@@ -180,9 +181,12 @@ export function deriveGatewayPrices(payload) {
180
181
  /**
181
182
  * LiteLLM 경로로 나간 호출의 모델 가격(토큰당 USD). 게이트웨이 표에 없거나,
182
183
  * 표가 PRICE_MAX_AGE_MS보다 오래됐거나, 키가 모호하면 null입니다. 정가표로
183
- * 대신 채우지 않습니다. 호출이 실제로 지난 경로의 가격만 씁니다.
184
+ * 대신 채우지 않습니다. 호출이 실제로 지난 경로의 가격만 씁니다. `at`(호출 시각)이
185
+ * 있으면 그 시각에 적용되던 표를 gateway-price-history.js에서 찾습니다.
184
186
  */
185
- export function gatewayPriceFor(model, env = process.env, now = Date.now()) {
187
+ export function gatewayPriceFor(model, env = process.env, now = Date.now(), at) {
188
+ // With `at`, the price is the one in effect then, from the dated history (#15).
189
+ if (at !== undefined && at !== null) return gatewayPriceAt(model, gatewayBase(env), at);
186
190
  const gateway = readGatewayModelMap(env);
187
191
  if (!gateway?.prices || typeof gateway.prices !== 'object') return null;
188
192
  const fetchedAt = Date.parse(gateway.fetchedAt);
@@ -295,12 +299,16 @@ export async function refreshGatewayModelMap({ base, key, fetchImpl = fetch } =
295
299
  // gateway 절만 갱신합니다. updateProfileMap이 쓰기 직전에 파일을 다시 읽어
296
300
  // 병합하므로, 이 네트워크 호출이 오가는 동안 route-scan의 학습 경로가
297
301
  // learned를 기록했더라도 그 결과를 지우지 않습니다. 반대 방향도 같습니다.
302
+ const fetchedAt = Date.now();
303
+ const prices = deriveGatewayPrices(payload);
304
+ // 날짜별 가격 이력에 먼저 남깁니다(옛 표가 아직 profile-map에 있을 때). 이력은 부가 기록이라 실패해도 갱신은 계속합니다.
305
+ try { recordGatewayPrices(base, prices, fetchedAt); } catch (e) { debug('litellm-models:price-history', e); }
298
306
  updateProfileMap({
299
307
  gateway: {
300
308
  base,
301
- fetchedAt: new Date().toISOString(),
309
+ fetchedAt: new Date(fetchedAt).toISOString(),
302
310
  aliases: result.aliases,
303
- prices: deriveGatewayPrices(payload),
311
+ prices,
304
312
  skipped: result.skipped,
305
313
  count: result.count,
306
314
  },
@@ -5,7 +5,7 @@
5
5
  * "Same period" as `sprag saved`: the routing reset mark, or the start of the
6
6
  * calendar month when nothing was ever reset, capped at 90 days of parsing.
7
7
  */
8
- import { pricedParts, sessionCost } from './claude-price.js';
8
+ import { pricedParts, partCost } from './claude-price.js';
9
9
  import { modelFamily } from './savings-ledger.js';
10
10
  import { readResetMarks } from './saved-reset.cjs';
11
11
  import { RESET, RED, GREEN, YELLOW, CYAN, MAGENTA, GRAY } from './formatters/statusline.js';
@@ -84,7 +84,7 @@ export function computeModelShare(sessions, { env = process.env } = {}) {
84
84
  for (const part of pricedParts(s)) {
85
85
  if (!part || !part.totals) continue;
86
86
  let cost = null;
87
- try { cost = sessionCost(part.totals, part.model, { env }); } catch { cost = null; }
87
+ try { cost = partCost(part, { env }); } catch { cost = null; }
88
88
  if (!cost || !Number.isFinite(cost.actual)) { unpriced++; continue; }
89
89
  const family = modelFamily(part.model);
90
90
  all.set(family, (all.get(family) || 0) + cost.actual);