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.
@@ -7,9 +7,12 @@
7
7
  * 다르므로 세션별로 호출 경로에 맞는 가격(sessionCost)을 적용해 합산합니다.
8
8
  * LiteLLM 게이트웨이 세션은 게이트웨이 가격표로만 계산하고, 표에 없는 모델은
9
9
  * 합계에서 빼고 unpriced 로 셉니다. 정가표로 대신 채우지 않습니다.
10
+ * 가격은 토큰을 쓴 날 기준입니다. 가격표는 UTC 자정에 바뀌므로 오늘 단가로
11
+ * 계산하면 가격이 바뀔 때 지난 지출까지 달라집니다(#15).
10
12
  */
11
13
 
12
- import { sessionCost, pricedParts } from './claude-price.js';
14
+ import { partCost, pricedParts } from './claude-price.js';
15
+ import { usageSince } from './usage-ledger.js';
13
16
 
14
17
  /** 이번 달 1일 00:00(로컬)의 epoch ms. */
15
18
  export function monthStartMs(now = new Date()) {
@@ -27,32 +30,61 @@ export function monthLabel(now = new Date()) {
27
30
  * 호출하는 쪽이 parser.js 의 sessionsSince 로 월초 이후 요청만 남겨서
28
31
  * 넘겨야 합니다. 그대로 넘기면 세션 전체가 이번 달 지출로 계산됩니다.
29
32
  *
33
+ * Claude Code 가 transcript 를 지운 세션은 sessions 에 없으므로 사용량 장부
34
+ * (usage-ledger.js)에서 월초 이후 일자분을 더합니다. sessions 에 있는 세션과
35
+ * 그 서브에이전트 실행은 장부에서 빼서 두 번 세지 않습니다. 장부는 UTC 일자 단위라
36
+ * 월초가 UTC 날짜와 어긋나면 장부 전용 세션은 최대 하루치를 더 셀 수 있습니다.
37
+ * `ledger: false` 는 일부 프로젝트만 넘기는 호출처가 다른 프로젝트의 장부분을
38
+ * 섞지 않으려고 씁니다.
39
+ *
30
40
  * @param {Array} sessions parseAllSessions 결과
31
41
  * @param {Date} [now]
42
+ * @param {{ledger?: boolean}} [opts]
32
43
  * @returns {{usd:number, sessions:number, unpriced:number, sinceMs:number, label:string}}
33
44
  */
34
- export function monthSpend(sessions, now = new Date()) {
45
+ export function monthSpend(sessions, now = new Date(), { ledger = true } = {}) {
35
46
  const since = monthStartMs(now);
36
47
  let usd = 0;
37
48
  let count = 0;
38
49
  let unpriced = 0;
50
+ const price = (part) => {
51
+ try {
52
+ const c = partCost(part);
53
+ if (!c) { unpriced += 1; return false; }
54
+ usd += c.actual;
55
+ return true;
56
+ } catch {
57
+ // 단가를 모르는 모델은 합계에서 빠집니다. 통계선에서는 침묵이 낫습니다.
58
+ return false;
59
+ }
60
+ };
61
+ const seen = new Set();
39
62
  for (const s of sessions || []) {
63
+ if (s && s.sessionId) {
64
+ seen.add(s.sessionId);
65
+ for (const r of s.subagentRuns || []) if (r.agent) seen.add(`${s.sessionId}/${r.agent}`);
66
+ }
40
67
  if (!s || !s.endTime || s.endTime.getTime() < since) continue;
41
68
  if (!s.totals) continue;
42
- // 세션이 띄운 서브에이전트 실행도 같은 청구서에 들어가므로, 실행마다 그 모델의
69
+ // 세션이 띄운 서브에이전트 실행도 같은 청구서에 들어가므로 실행마다 그 모델의
43
70
  // 단가로 계산해 더합니다. 세션 수에는 넣지 않습니다.
44
71
  let priced = false;
45
72
  for (const part of pricedParts(s)) {
46
- try {
47
- const c = sessionCost(part.totals, part.model);
48
- if (!c) { unpriced += 1; continue; }
49
- usd += c.actual;
50
- if (part.own) priced = true;
51
- } catch {
52
- // 단가를 모르는 모델은 합계에서 빠집니다. 통계선에서는 침묵이 낫습니다.
53
- }
73
+ if (price(part) && part.own) priced = true;
54
74
  }
55
75
  if (priced) count += 1;
56
76
  }
77
+ if (ledger) {
78
+ try {
79
+ // 모델이 둘 이상인 장부 세션도 한 번만 세려고 id 로 모읍니다.
80
+ const ids = new Set();
81
+ for (const part of usageSince(since, { exclude: seen })) {
82
+ if (price(part) && part.own) ids.add(part.id);
83
+ }
84
+ count += ids.size;
85
+ } catch {
86
+ // 장부를 못 읽어도 transcript 기준 합계는 그대로 냅니다.
87
+ }
88
+ }
57
89
  return { usd, sessions: count, unpriced, sinceMs: since, label: monthLabel(now) };
58
90
  }
package/src/net-saving.js CHANGED
@@ -49,11 +49,11 @@ export function priceSource(env = process.env) {
49
49
  * touches. Cache writes are taken at the 5-minute rate, the cheaper of the two.
50
50
  * null when any of them has no price.
51
51
  */
52
- export function unitRates(model, { env = process.env } = {}) {
52
+ export function unitRates(model, { env = process.env, at } = {}) {
53
53
  if (!model) return null;
54
54
  const rate = (totals) => {
55
55
  let c;
56
- try { c = sessionCost({ ...ZERO, ...totals }, model, { env }); } catch { return null; }
56
+ try { c = sessionCost({ ...ZERO, ...totals }, model, { env, at }); } catch { return null; }
57
57
  return c ? c.actual / RATE_SCALE : null;
58
58
  };
59
59
  const cacheRead = rate({ cacheRead: RATE_SCALE });
@@ -67,7 +67,7 @@ export function unitRates(model, { env = process.env } = {}) {
67
67
  * What a run's tokens cost on a model, in USD, to better than a cent. null when
68
68
  * the model has no price on this path.
69
69
  */
70
- export function exactCost(totals, model, { env = process.env } = {}) {
70
+ export function exactCost(totals, model, { env = process.env, at } = {}) {
71
71
  if (!model) return null;
72
72
  const scale = (t) => {
73
73
  const out = {};
@@ -77,7 +77,7 @@ export function exactCost(totals, model, { env = process.env } = {}) {
77
77
  const scaled = scale(totals);
78
78
  if (totals.long) scaled.long = scale(totals.long);
79
79
  let c;
80
- try { c = sessionCost(scaled, model, { env }); } catch { return null; }
80
+ try { c = sessionCost(scaled, model, { env, at }); } catch { return null; }
81
81
  return c ? c.actual / COST_SCALE : null;
82
82
  }
83
83
 
@@ -131,3 +131,50 @@ export function netSavingV3({ calls, mainCtx, followUps, promptTokens, resultTok
131
131
  // input and output. Split out so the savings page can show each term.
132
132
  return { usd: cfWork + cfCarry - actual, cfWork, cfReread, cfCarry, overhead, actual, subActual };
133
133
  }
134
+
135
+ /**
136
+ * The v3 saving is linear in the main model's three rates, so a run can be
137
+ * stored as three token quantities and priced later at whatever rates applied
138
+ * when it ran (#15). With G = grow_last + the run's output and N = followUps:
139
+ * cacheRead = sum(mainCtx + grow_i) + G * N - R * N
140
+ * write = sum(newIn_i) (the first call's left out under skipFirstWrite) - R
141
+ * output = sum(out_i) - P
142
+ * and usd = cacheRead * rates.cacheRead + write * rates.write
143
+ * + output * rates.output - subActual (see savingFromQuantities).
144
+ * Same inputs and validation as netSavingV3, minus rates and subActual.
145
+ *
146
+ * @returns {{cacheRead:number,write:number,output:number}|null}
147
+ */
148
+ export function netSavingQuantities({ calls, mainCtx, followUps, promptTokens, resultTokens, skipFirstWrite = false }) {
149
+ if (!Array.isArray(calls) || calls.length === 0) return null;
150
+ if (!calls.every((c) => c && isNum(c.ctx) && isNum(c.newIn) && isNum(c.out))) return null;
151
+ if (!isNum(mainCtx) || mainCtx <= 0) return null;
152
+ if (!isNum(followUps) || followUps < 0) return null;
153
+ if (!isNum(promptTokens) || promptTokens < 0) return null;
154
+ if (!isNum(resultTokens) || resultTokens < 0) return null;
155
+
156
+ const ctx1 = calls[0].ctx;
157
+ const grow = (c) => Math.max(0, c.ctx - ctx1);
158
+ let reread = 0;
159
+ let newIn = 0;
160
+ let totalOut = 0;
161
+ calls.forEach((c, i) => {
162
+ reread += mainCtx + grow(c);
163
+ if (!(skipFirstWrite && i === 0)) newIn += c.newIn;
164
+ totalOut += c.out;
165
+ });
166
+ const G = grow(calls[calls.length - 1]) + totalOut;
167
+ return {
168
+ cacheRead: reread + G * followUps - resultTokens * followUps,
169
+ write: newIn - resultTokens,
170
+ output: totalOut - promptTokens,
171
+ };
172
+ }
173
+
174
+ /** The v3 saving in USD from stored quantities; null when any input is not finite. */
175
+ export function savingFromQuantities(q, rates, subActual) {
176
+ if (!q || !isNum(q.cacheRead) || !isNum(q.write) || !isNum(q.output)) return null;
177
+ if (!rates || !isNum(rates.cacheRead) || !isNum(rates.write) || !isNum(rates.output)) return null;
178
+ if (!isNum(subActual)) return null;
179
+ return q.cacheRead * rates.cacheRead + q.write * rates.write + q.output * rates.output - subActual;
180
+ }
@@ -1,13 +1,14 @@
1
1
  // OpenAI list prices for Codex calls that go straight to OpenAI (ChatGPT/OpenAI login).
2
2
  // Source: https://developers.openai.com/api/docs/pricing , "Standard" tier, short-context
3
- // rates, checked 2026-10-01. Long-context surcharges are not modeled, so requests past the
3
+ // rates, checked 2026-11-07. Long-context surcharges are not modeled, so requests past the
4
4
  // long-context threshold are under-priced. Calls through a LiteLLM gateway never use this table.
5
- export const OPENAI_PRICES_CHECKED_AT = Date.parse('2026-10-01T00:00:00Z');
5
+ export const OPENAI_PRICES_CHECKED_AT = Date.parse('2026-11-07T00:00:00Z');
6
6
 
7
7
  // Per-1M-token numbers as listed on the page; null where the page shows "-".
8
- const PER_MILLION = {
8
+ export const PER_MILLION = {
9
9
  'gpt-6-astra': [10, 1, 12.5, 50],
10
10
  'gpt-6.1-sol': [2, 0.1, 2.5, 10],
11
+ 'gpt-6.1-terra': [1, 0.05, 1.25, 5],
11
12
  'gpt-6-luna': [0.1, 0.01, 0.125, 0.5],
12
13
  'gpt-6-sol': [2, 0.2, 2.5, 10],
13
14
  'gpt-5.6-sol': [4, 0.4, 5, 20],
@@ -23,6 +24,9 @@ const PER_MILLION = {
23
24
  'gpt-5.2-pro': [21, null, null, 168],
24
25
  'gpt-5.1': [1.25, 0.125, null, 10],
25
26
  'gpt-5': [1.25, 0.125, null, 10],
27
+ 'gpt-5-mini': [0.25, 0.025, null, 2],
28
+ 'gpt-5-nano': [0.05, 0.005, null, 0.4],
29
+ 'gpt-5-pro': [15, null, null, 120],
26
30
  };
27
31
 
28
32
  // Parse "<n>e-6" instead of dividing so 0.1 per 1M is exactly 1e-7, without float noise.
package/src/parser.js CHANGED
@@ -105,7 +105,7 @@ export async function parseSessionFile(filePath) {
105
105
  if (n > best) { best = n; model = m; }
106
106
  }
107
107
  if (best === 0 && reqs.length > 0) model = reqs[0].model || 'unknown';
108
- const { totals, maxContextPerRequest, modelTotals } = sumRequests(reqs);
108
+ const { totals, maxContextPerRequest, modelTotals, dayTotals } = sumRequests(reqs);
109
109
 
110
110
  return {
111
111
  sessionId,
@@ -118,6 +118,7 @@ export async function parseSessionFile(filePath) {
118
118
  maxContextPerRequest,
119
119
  model,
120
120
  ...(modelTotals ? { modelTotals } : {}),
121
+ ...(dayTotals ? { dayTotals } : {}),
121
122
  gatewayObserved,
122
123
  };
123
124
  }
@@ -147,6 +148,8 @@ function addRequest(acc, r) {
147
148
  }
148
149
  }
149
150
 
151
+ const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
152
+
150
153
  /**
151
154
  * Totals of a set of requests, plus the same totals split by model when more
152
155
  * than one model spent tokens.
@@ -156,10 +159,20 @@ function addRequest(acc, r) {
156
159
  * model's rate billed a Haiku stretch at the Fable rate, or the reverse. The
157
160
  * split lets the cost side price each model's tokens at its own rate. It is
158
161
  * left out for the usual single-model session, so those keep their old shape.
162
+ *
163
+ * `dayTotals` is the same split by UTC day and then model:
164
+ * `{ 'YYYY-MM-DD': { [model]: totals } }`. Price rows change at UTC midnight,
165
+ * so a session that runs across one must be priced day by day or a price
166
+ * change rewrites the part spent before it (#15). Like `modelTotals` it is
167
+ * left out for the usual case, here a set of requests inside one UTC day. A
168
+ * request without a timestamp is put on the earliest day known; with no
169
+ * timestamp anywhere there is no day to name and `dayTotals` is left out.
159
170
  */
160
171
  function sumRequests(reqs) {
161
172
  const totals = emptyTotals();
162
173
  const byModel = new Map();
174
+ const timed = [];
175
+ const untimed = [];
163
176
  let maxContextPerRequest = 0;
164
177
  for (const r of reqs) {
165
178
  addRequest(totals, r);
@@ -169,8 +182,26 @@ function sumRequests(reqs) {
169
182
  const key = r.model || 'unknown';
170
183
  if (!byModel.has(key)) byModel.set(key, emptyTotals());
171
184
  addRequest(byModel.get(key), r);
185
+ (r.ts == null ? untimed : timed).push(r);
186
+ }
187
+ let dayTotals = null;
188
+ if (timed.length) {
189
+ const days = new Map();
190
+ const firstDay = utcDay(timed.reduce((m, r) => Math.min(m, r.ts), Infinity));
191
+ for (const r of [...timed, ...untimed]) {
192
+ const day = r.ts == null ? firstDay : utcDay(r.ts);
193
+ if (!days.has(day)) days.set(day, new Map());
194
+ const models = days.get(day);
195
+ const key = r.model || 'unknown';
196
+ if (!models.has(key)) models.set(key, emptyTotals());
197
+ addRequest(models.get(key), r);
198
+ }
199
+ if (days.size > 1) {
200
+ dayTotals = {};
201
+ for (const day of [...days.keys()].sort()) dayTotals[day] = Object.fromEntries(days.get(day));
202
+ }
172
203
  }
173
- return { totals, maxContextPerRequest, modelTotals: byModel.size > 1 ? Object.fromEntries(byModel) : null };
204
+ return { totals, maxContextPerRequest, modelTotals: byModel.size > 1 ? Object.fromEntries(byModel) : null, dayTotals };
174
205
  }
175
206
 
176
207
  /**
@@ -429,7 +460,7 @@ function trimToCutoff(session, cutoffMs) {
429
460
  if (firstTs === null || r.ts < firstTs) firstTs = r.ts;
430
461
  if (lastTs === null || r.ts > lastTs) lastTs = r.ts;
431
462
  }
432
- const { totals, maxContextPerRequest, modelTotals } = sumRequests(reqs);
463
+ const { totals, maxContextPerRequest, modelTotals, dayTotals } = sumRequests(reqs);
433
464
  return {
434
465
  sessionId: session.sessionId,
435
466
  filePath: session.filePath,
@@ -441,6 +472,7 @@ function trimToCutoff(session, cutoffMs) {
441
472
  maxContextPerRequest,
442
473
  model: session.model,
443
474
  ...(modelTotals ? { modelTotals } : {}),
475
+ ...(dayTotals ? { dayTotals } : {}),
444
476
  gatewayObserved: session.gatewayObserved,
445
477
  };
446
478
  }
@@ -520,8 +552,12 @@ export async function parseAllSessions(options = {}) {
520
552
  }
521
553
  }
522
554
  if (!run.requestCount || !run.endTime || run.endTime.getTime() < cutoffMs) continue;
555
+ // `agent` names the run for the usage ledger; `startTime` and `dayTotals`
556
+ // let the cost side price it at the rates of the days it ran (#15).
523
557
  runs.push({ model: run.model, totals: run.totals, requestCount: run.requestCount, endTime: run.endTime,
524
- ...(run.modelTotals ? { modelTotals: run.modelTotals } : {}) });
558
+ agent: basename(a.path, '.jsonl'), startTime: run.startTime,
559
+ ...(run.modelTotals ? { modelTotals: run.modelTotals } : {}),
560
+ ...(run.dayTotals ? { dayTotals: run.dayTotals } : {}) });
525
561
  } catch {
526
562
  continue;
527
563
  }
package/src/route-scan.js CHANGED
@@ -22,12 +22,13 @@ import { join } from 'node:path';
22
22
  import { userDataDir } from './paths.js';
23
23
  import { discoverSessionFiles } from './parser.js';
24
24
  import { collectSessionRecords, delegationContexts } from './session-records.js';
25
- import { netSavingV3, unitRates, exactCost, priceSource } from './net-saving.js';
25
+ import { netSavingV3, netSavingQuantities, unitRates, exactCost, priceSource } from './net-saving.js';
26
26
  import {
27
27
  collectSubagentRuns, indexRuns, exactRunsForEpisode, fallbackRunsForEpisode,
28
28
  } from './subagent-records.js';
29
29
  import { modelRank, isRecognizedModelId, TIER_TARGET_RANK, tierForRank } from './cost.js';
30
30
  import { sessionCost } from './claude-price.js';
31
+ import { gatewayBase } from './gateway-auth.js';
31
32
  import { learnProfileMapping, resetModelAliasCache } from './model-alias.js';
32
33
  import { modelRuleBaseText } from './model-rules.js';
33
34
  import { RULE_CATEGORY_LABELS } from './rule-categories.js';
@@ -377,11 +378,17 @@ export function worthDelegating(tier, rank) {
377
378
  * negative. null means a side has no price (a gateway session whose /model/info
378
379
  * table lacks the model), which is unpriced, not zero.
379
380
  */
381
+ /** When a run spent its tokens, for the dated price lookup; undefined means now. */
382
+ export const runTime = (run) => (Number.isFinite(run?.startedAt) ? run.startedAt : Number.isFinite(run?.endedAt) ? run.endedAt : undefined);
383
+
380
384
  export function runSaving(run, mainModel, { env = process.env } = {}) {
381
385
  if (!run.model || !mainModel) return null;
382
386
  const totals = runTotals(run);
383
- const actual = sessionCost(totals, run.model, { env });
384
- const counterfactual = sessionCost(totals, mainModel, { env });
387
+ // Priced at the rates in effect when the run happened, so a later price
388
+ // change does not rewrite a saving already earned (#15).
389
+ const at = runTime(run);
390
+ const actual = sessionCost(totals, run.model, { env, at });
391
+ const counterfactual = sessionCost(totals, mainModel, { env, at });
385
392
  if (!actual || !counterfactual) return null;
386
393
  return counterfactual.actual - actual.actual;
387
394
  }
@@ -396,28 +403,33 @@ export function runSaving(run, mainModel, { env = process.env } = {}) {
396
403
  * no price on either side) sends the run to the v2 formula instead, tagged
397
404
  * basis 'v2', so the figure is never invented. null still means unpriced.
398
405
  *
399
- * @returns {{usd:number, basis:'v3'|'v2', cfWork?:number, cfCarry?:number, overhead?:number}|null}
406
+ * On v3 the result also carries `main`, the main model's token quantities the
407
+ * saving is linear in (netSavingQuantities), which the ledger stores.
408
+ *
409
+ * @returns {{usd:number, basis:'v3'|'v2', main?:object, cfWork?:number, cfCarry?:number, overhead?:number}|null}
400
410
  */
401
411
  export function runSavingDetail(run, mainModel, info, { env = process.env } = {}) {
402
412
  if (!run.model || !mainModel) return null;
403
413
  const v3 = (() => {
404
414
  if (!info || !Array.isArray(run.perCall) || run.perCall.length === 0) return null;
405
415
  if (!Number.isFinite(info.resultChars)) return null;
406
- const rates = unitRates(mainModel, { env });
407
- const subActual = exactCost(runTotals(run), run.model, { env });
416
+ const at = runTime(run);
417
+ const rates = unitRates(mainModel, { env, at });
418
+ const subActual = exactCost(runTotals(run), run.model, { env, at });
408
419
  if (!rates || subActual === null) return null;
409
420
  // A background launch returns only an acknowledgement; the report that
410
421
  // follows is the run's final message.
411
422
  const chars = info.resultChars + (info.async ? (run.finalChars || 0) : 0);
412
- return netSavingV3({
423
+ const inputs = {
413
424
  calls: run.perCall,
414
425
  mainCtx: info.C,
415
426
  followUps: info.N,
416
427
  promptTokens: info.P,
417
428
  resultTokens: chars / 4,
418
- rates,
419
- subActual,
420
- });
429
+ };
430
+ const result = netSavingV3({ ...inputs, rates, subActual });
431
+ if (!result) return null;
432
+ return { ...result, main: netSavingQuantities(inputs) };
421
433
  })();
422
434
  if (v3) return { basis: 'v3', ...v3 };
423
435
  const v2 = runSaving(run, mainModel, { env });
@@ -431,11 +443,11 @@ export function runSavingDetail(run, mainModel, info, { env = process.env } = {}
431
443
  */
432
444
  export function runCost(run) {
433
445
  if (!run.model) return null;
434
- const actual = sessionCost(runTotals(run), run.model);
446
+ const actual = sessionCost(runTotals(run), run.model, { at: runTime(run) });
435
447
  return actual ? actual.actual : null;
436
448
  }
437
449
 
438
- function runTotals(run) {
450
+ export function runTotals(run) {
439
451
  return {
440
452
  input: run.input,
441
453
  cacheCreation: run.cacheCreation,
@@ -919,7 +931,7 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
919
931
  // to show up: the first wrote the new baseline but billed against the old
920
932
  // one, and the totals only settled on the second.
921
933
  try {
922
- const { recordDelegationEvents } = await import('./savings-ledger.js');
934
+ const { recordDelegationEvents, repriceDelegationLedger, priceLedgerEvent } = await import('./savings-ledger.js');
923
935
  const { loadModelRules } = await import('./model-rules.js');
924
936
  const fresh = loadModelRules().rules;
925
937
  const priced = [];
@@ -940,9 +952,10 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
940
952
  const detail = runSavingDetail(e.run, baseline, e.info);
941
953
  // A loss is recorded too; only an unpriced run (null) has nothing to record.
942
954
  if (!detail || !Number.isFinite(detail.usd)) continue;
943
- priced.push({
955
+ const ts = e.run.endedAt ?? e.run.startedAt ?? Date.now();
956
+ const event = {
944
957
  key: e.run.path,
945
- ts: e.run.endedAt ?? e.run.startedAt ?? Date.now(),
958
+ ts,
946
959
  usd: detail.usd,
947
960
  cost: runCost(e.run),
948
961
  rule: rule.signature,
@@ -951,7 +964,22 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
951
964
  basis: detail.basis,
952
965
  priceSource: priceSource(),
953
966
  baselineSource: fromEpisode ? 'episode' : 'rule',
954
- });
967
+ };
968
+ // Every run is stored as token quantities, and its dollars come from
969
+ // them through the one function every reader uses (#15): a list run from
970
+ // the list table, a gateway run from that gateway's price history, with
971
+ // the gateway recorded so a later shell cannot change the path.
972
+ if (event.priceSource === 'gateway') event.gw = gatewayBase();
973
+ event.q = {
974
+ at: runTime(e.run) ?? ts,
975
+ sub: runTotals(e.run),
976
+ ...(detail.basis === 'v3' && detail.main ? { main: detail.main } : {}),
977
+ };
978
+ const p = priceLedgerEvent(event);
979
+ if (!p) continue;
980
+ event.usd = p.usd;
981
+ event.cost = p.cost;
982
+ priced.push(event);
955
983
  if (Array.isArray(trace)) {
956
984
  trace.push({
957
985
  key: e.run.path,
@@ -967,7 +995,7 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
967
995
  startedAt: e.run.startedAt ?? null,
968
996
  cfCarry: detail.cfCarry,
969
997
  overhead: detail.overhead,
970
- firstWrite: detail.basis === 'v3' ? (e.run.perCall[0].newIn * (unitRates(baseline)?.write ?? 0)) : 0,
998
+ firstWrite: detail.basis === 'v3' ? (e.run.perCall[0].newIn * (unitRates(baseline, { at: runTime(e.run) })?.write ?? 0)) : 0,
971
999
  calls: e.run.calls,
972
1000
  C: e.info?.C ?? null,
973
1001
  N: e.info?.N ?? null,
@@ -975,6 +1003,7 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
975
1003
  }
976
1004
  }
977
1005
  recordDelegationEvents(priced);
1006
+ repriceDelegationLedger();
978
1007
  } catch {
979
1008
  // ledger write failure only delays the statusline totals, never the scan
980
1009
  }
@@ -11,7 +11,7 @@
11
11
  * File: <userDataDir>/delegation-ledger.json
12
12
  * { "version": 3,
13
13
  * "events": { "<run path>": { "ts", "usd", "cost", "rule", "from", "to",
14
- * "basis", "priceSource", "baselineSource" } } }
14
+ * "basis", "priceSource", "baselineSource", "gw", "q" } } }
15
15
  *
16
16
  * Version 3 prices a run on the net-saving basis (src/net-saving.js), and each
17
17
  * event says how it was priced: `basis` 'v3' (cache re-reads and carried
@@ -22,6 +22,20 @@
22
22
  * their value and read as basis v2; a rescan reprices those still inside the
23
23
  * scan window as v3 and leaves the older ones alone.
24
24
  *
25
+ * `q` holds the token quantities a run was priced from (#15):
26
+ * `at` (when the run spent its tokens), `sub` (the run's own token totals) and,
27
+ * on the v3 basis, `main` (cacheRead, write and output tokens of the main model,
28
+ * from src/net-saving.js). The dollars of such an event are computed from `q`
29
+ * every time the ledger is read, with the price in effect at `q.at`, so a
30
+ * corrected price table fixes the past; `usd` and `cost` stored beside it are
31
+ * only a cache of that figure. `q` is optional and the ledger stays version 3,
32
+ * so older sprag versions ignore it. A gateway event (`priceSource` 'gateway')
33
+ * also carries `gw`, the gateway address it went through, and is priced from
34
+ * that gateway's own price history (src/gateway-price-history.js) at `q.at`,
35
+ * never from the list table (stage 3 of #15). Events without `q` (written
36
+ * before it existed and outside the scan window), and gateway events without
37
+ * `gw`, keep their stored figure.
38
+ *
25
39
  * `from`/`to` are the models the routing decision moved between, and `usd` is
26
40
  * the price difference between them for this run's tokens. `cost` is what the
27
41
  * run itself cost on the model it ran on, so the statusline can show what the
@@ -41,6 +55,8 @@ import { join } from 'node:path';
41
55
  import { userDataDir } from './paths.js';
42
56
  import { writeStateFile } from './state-file.js';
43
57
  import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
58
+ import { exactCost, unitRates, savingFromQuantities } from './net-saving.js';
59
+ import { gatewayBase } from './gateway-auth.js';
44
60
 
45
61
  const WEEK_MS = 7 * 24 * 3600 * 1000;
46
62
  const MONTH_MS = 30 * 24 * 3600 * 1000;
@@ -69,7 +85,52 @@ export function runIdentity(key) {
69
85
  return i > 0 ? parts.slice(i - 1).join('/') : String(key);
70
86
  }
71
87
 
72
- export function loadLedger() {
88
+ /**
89
+ * What an event is worth, computed from its stored quantities `q` with the
90
+ * list price in effect at `q.at` (#15). { usd, cost } rounded like stored
91
+ * figures, or null when the event cannot be priced from quantities: no `q`, a
92
+ * gateway price, a missing model, or a model with no price. The empty env keeps
93
+ * a gateway set in the current shell from leaking into the list table.
94
+ */
95
+ export function priceLedgerEvent(e) {
96
+ try {
97
+ const q = e?.q;
98
+ if (!q || typeof q !== 'object' || !q.sub || typeof q.sub !== 'object') return null;
99
+ if (!e.from || !e.to) return null;
100
+ // A list event is priced with an empty env so a gateway set in the current
101
+ // shell cannot leak in. A gateway event names its gateway (`gw`) and is
102
+ // priced from that gateway's price history only; without `gw` it keeps its
103
+ // stored dollars.
104
+ let env;
105
+ if (e.priceSource === 'list') env = {};
106
+ else if (e.priceSource === 'gateway' && typeof e.gw === 'string' && e.gw) env = { ANTHROPIC_BASE_URL: e.gw };
107
+ else return null;
108
+ if (e.priceSource === 'gateway' && !gatewayBase(env)) return null; // gw is the official endpoint, not a gateway
109
+ const at = Number.isFinite(q.at) ? q.at : Number.isFinite(e.ts) ? e.ts : undefined;
110
+ if (e.priceSource === 'gateway' && at === undefined) return null;
111
+ const cost = exactCost(q.sub, e.to, { env, at });
112
+ if (!Number.isFinite(cost)) return null;
113
+ let usd;
114
+ if (q.main) {
115
+ const rates = unitRates(e.from, { env, at });
116
+ usd = rates ? savingFromQuantities(q.main, rates, cost) : null;
117
+ } else {
118
+ const base = exactCost(q.sub, e.from, { env, at });
119
+ usd = Number.isFinite(base) ? base - cost : null;
120
+ }
121
+ if (!Number.isFinite(usd)) return null;
122
+ return { usd: roundUsd(usd), cost: roundUsd(cost) };
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * `priced: false` returns the stored figures untouched; the writers use it so
130
+ * a write does not turn the read-time figures into stored ones (that is
131
+ * repriceDelegationLedger's job, which also marks the change for the team sync).
132
+ */
133
+ export function loadLedger({ priced = true } = {}) {
73
134
  try {
74
135
  const data = JSON.parse(readFileSync(ledgerPath(), 'utf8'));
75
136
  if (!data || typeof data.events !== 'object' || data.events === null) {
@@ -90,6 +151,14 @@ export function loadLedger() {
90
151
  if (seen.has(id)) delete data.events[key];
91
152
  else seen.add(id);
92
153
  }
154
+ // Dollars come from the stored quantities at the price in effect when each
155
+ // run happened, so every reader sees the current price table's figure.
156
+ if (priced) {
157
+ for (const e of Object.values(data.events)) {
158
+ const p = e && priceLedgerEvent(e);
159
+ if (p) { e.usd = p.usd; e.cost = p.cost; }
160
+ }
161
+ }
93
162
  return data;
94
163
  } catch {
95
164
  return { version: LEDGER_VERSION, events: {} };
@@ -98,7 +167,7 @@ export function loadLedger() {
98
167
 
99
168
  /**
100
169
  * Upsert saving events. `events` is an array of
101
- * { key, ts, usd, cost, rule, from, to, basis, priceSource, baselineSource } where `key` is the run's transcript
170
+ * { key, ts, usd, cost, rule, from, to, basis, priceSource, baselineSource, gw, q } where `key` is the run's transcript
102
171
  * path (unique per subagent run) and `from`/`to` name the models the routing
103
172
  * decision moved between. `usd` is signed: a run on a pricier model is a loss
104
173
  * and is recorded as a negative amount so it reduces the totals. Only
@@ -107,7 +176,7 @@ export function loadLedger() {
107
176
  */
108
177
  export function recordDelegationEvents(events) {
109
178
  if (!Array.isArray(events) || events.length === 0) return;
110
- const data = loadLedger();
179
+ const data = loadLedger({ priced: false });
111
180
  data.version = LEDGER_VERSION;
112
181
  let changed = false;
113
182
  // Earliest moment whose figures this call changed. A rescan that reprices or
@@ -129,7 +198,9 @@ export function recordDelegationEvents(events) {
129
198
  // The same goes for the basis fields: a v2 event rescanned as v3 differs.
130
199
  if (prev && prev.ts === e.ts && prev.usd === usd && prev.cost === cost
131
200
  && prev.basis === (e.basis || undefined) && prev.priceSource === (e.priceSource || undefined)
132
- && prev.baselineSource === (e.baselineSource || undefined)) continue;
201
+ && prev.baselineSource === (e.baselineSource || undefined)
202
+ && prev.gw === (e.gw || undefined)
203
+ && JSON.stringify(prev.q) === JSON.stringify(e.q || undefined)) continue;
133
204
  earliest = Math.min(earliest, e.ts, Number.isFinite(prev?.ts) ? prev.ts : Infinity);
134
205
  if (prevKey !== e.key) delete data.events[prevKey];
135
206
  keyOf.set(id, e.key);
@@ -143,6 +214,8 @@ export function recordDelegationEvents(events) {
143
214
  ...(e.basis ? { basis: e.basis } : {}),
144
215
  ...(e.priceSource ? { priceSource: e.priceSource } : {}),
145
216
  ...(e.baselineSource ? { baselineSource: e.baselineSource } : {}),
217
+ ...(e.gw ? { gw: e.gw } : {}),
218
+ ...(e.q ? { q: e.q } : {}),
146
219
  };
147
220
  changed = true;
148
221
  }
@@ -158,6 +231,45 @@ export function recordDelegationEvents(events) {
158
231
  }
159
232
  }
160
233
 
234
+ /**
235
+ * Store the figures computed from quantities where they differ from the stored
236
+ * ones, and mark the change for the team sync. A price correction changes days
237
+ * the sync already uploaded, and nothing else would tell it to reach back that
238
+ * far. Reads the file as stored (not loadLedger's computed view), so it sees
239
+ * what was uploaded. Returns the number of events changed.
240
+ */
241
+ export function repriceDelegationLedger() {
242
+ let data;
243
+ try {
244
+ data = JSON.parse(readFileSync(ledgerPath(), 'utf8'));
245
+ } catch {
246
+ return 0;
247
+ }
248
+ if (!data || typeof data.events !== 'object' || data.events === null || !READABLE_VERSIONS.has(data.version)) return 0;
249
+ let n = 0;
250
+ let earliest = Infinity;
251
+ for (const e of Object.values(data.events)) {
252
+ const p = e && priceLedgerEvent(e);
253
+ if (!p || (e.usd === p.usd && e.cost === p.cost)) continue;
254
+ e.usd = p.usd;
255
+ e.cost = p.cost;
256
+ n += 1;
257
+ if (Number.isFinite(e.ts)) earliest = Math.min(earliest, e.ts);
258
+ }
259
+ if (n === 0) return 0;
260
+ data.version = LEDGER_VERSION;
261
+ if (Number.isFinite(earliest)) {
262
+ data.changedSince = Math.min(Number.isFinite(data.changedSince) ? data.changedSince : Infinity, earliest);
263
+ data.changeSeq = (Number(data.changeSeq) || 0) + 1;
264
+ }
265
+ try {
266
+ writeStateFile(ledgerPath(), JSON.stringify(data) + '\n');
267
+ } catch {
268
+ return 0;
269
+ }
270
+ return n;
271
+ }
272
+
161
273
  /**
162
274
  * The ledger's pending change mark, for the team sync: `since` is the earliest
163
275
  * event time a recordDelegationEvents call changed after the last upload, and
@@ -183,7 +295,7 @@ export function changedSinceForSync() {
183
295
  * then kept, so the next sync covers that change too.
184
296
  */
185
297
  export function clearChangedSince(seq) {
186
- const data = loadLedger();
298
+ const data = loadLedger({ priced: false });
187
299
  if ((Number(data.changeSeq) || 0) !== seq) return false;
188
300
  if (!Number.isFinite(data.changedSince) && data.changeTracking === 1) return false;
189
301
  delete data.changedSince;