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.
@@ -40,7 +40,11 @@ const CACHE_PATH = join(userDataDir(), 'session-cache.json');
40
40
  // tokens from requests whose prompt exceeds 100k, which Haiku 5.5 prices at a
41
41
  // higher rate. A v4 entry lacks it, so a Haiku 5.5 session cached before the
42
42
  // bump would keep being priced at the short rate until its transcript changed.
43
- const CACHE_VERSION = 5;
43
+ // 6: sessions spanning more than one UTC day carry `dayTotals` (totals per UTC
44
+ // day and model), so cost can use each day's price row (#15). A v5 entry lacks
45
+ // it, so a session crossing a price change would be priced at one day's rate
46
+ // until its transcript changed.
47
+ const CACHE_VERSION = 6;
44
48
  // Entries for transcripts this old are pruned on write. Keeps the file
45
49
  // bounded without an existence check per entry (which would cost the syscalls
46
50
  // the cache exists to avoid).
@@ -57,6 +61,7 @@ const PRUNE_AFTER_MS = 90 * 24 * 60 * 60 * 1000;
57
61
  * @property {number} maxContextPerRequest
58
62
  * @property {string} model
59
63
  * @property {Record<string, object>} [modelTotals] totals per model, present only when more than one model spent tokens
64
+ * @property {Record<string, Record<string, object>>} [dayTotals] totals per UTC day and model, present only when the requests span more than one UTC day
60
65
  * @property {string} [projectDir]
61
66
  */
62
67
 
@@ -71,6 +76,7 @@ function serialize(session) {
71
76
  maxContextPerRequest: session.maxContextPerRequest,
72
77
  model: session.model,
73
78
  ...(session.modelTotals ? { modelTotals: session.modelTotals } : {}),
79
+ ...(session.dayTotals ? { dayTotals: session.dayTotals } : {}),
74
80
  gatewayObserved: !!session.gatewayObserved,
75
81
  };
76
82
  }
@@ -87,6 +93,7 @@ function deserialize(stored, filePath, projectDir) {
87
93
  maxContextPerRequest: stored.maxContextPerRequest || 0,
88
94
  model: stored.model || 'unknown',
89
95
  ...(stored.modelTotals && typeof stored.modelTotals === 'object' ? { modelTotals: stored.modelTotals } : {}),
96
+ ...(stored.dayTotals && typeof stored.dayTotals === 'object' ? { dayTotals: stored.dayTotals } : {}),
90
97
  gatewayObserved: !!stored.gatewayObserved,
91
98
  };
92
99
  }
package/src/team-sync.js CHANGED
@@ -47,7 +47,7 @@ import { userLanguage } from './config.js';
47
47
  import { debug } from './debug.js';
48
48
  import { trustSystemCA } from './system-ca.js';
49
49
  import { loadLedger, modelFamily, roundUsd, changedSinceForSync, clearChangedSince } from './savings-ledger.js';
50
- import { sessionCost, pricedParts } from './claude-price.js';
50
+ import { partCost, pricedParts } from './claude-price.js';
51
51
  import { uploadPrompts, dropOffsets, promptOffsetsExist } from './team-prompts.js';
52
52
  import { ruleStatsSummary } from './team-rule-stats.js';
53
53
  import { rulesPullDue, syncTeamRatchet, ensureTeamImport } from './team-ratchet.js';
@@ -476,7 +476,7 @@ export async function aggregateDaily({
476
476
  const d = get(dayKey(t));
477
477
  for (const part of pricedParts(s)) {
478
478
  try {
479
- const c = sessionCost(part.totals, part.model, { env });
479
+ const c = partCost(part, { env });
480
480
  if (!c) { d.unpriced += 1; continue; }
481
481
  d.spent += c.actual;
482
482
  if (!part.own) d.subagent += c.actual;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * usage-ledger: token usage per session, UTC day and model, kept after Claude
3
+ * Code deletes the transcript (#15).
4
+ *
5
+ * Month spend is computed from transcripts, and Claude Code removes old ones.
6
+ * A deleted session would drop out of the month's total and the figure would
7
+ * shrink for no reason. This file keeps the tokens (never dollars), so cost is
8
+ * still priced when it is read, at the price row of each day, and a later
9
+ * price correction applies to the history too.
10
+ *
11
+ * Shape: `{ version: 1, writtenAt, sessions: { [id]: { days: { 'YYYY-MM-DD':
12
+ * { [model]: totals } }, updatedAt } } }`. A subagent run is keyed
13
+ * `<session id>/<agent file>`. Days are UTC days, because price rows change at
14
+ * UTC midnight.
15
+ */
16
+
17
+ import { readFileSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { userDataDir } from './paths.js';
20
+ import { writeStateFile } from './state-file.js';
21
+ import { sumTotals } from './claude-price.js';
22
+ import { debug } from './debug.js';
23
+
24
+ const DAY_MS = 24 * 60 * 60 * 1000;
25
+ // Entries whose newest day is older than this are dropped on write.
26
+ const KEEP_DAYS = 400;
27
+ // The statusline calls this on every refresh; hourly is plenty for a history.
28
+ const THROTTLE_MS = 60 * 60 * 1000;
29
+
30
+ const ledgerPath = () => join(userDataDir(), 'usage-ledger.json');
31
+ const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
32
+
33
+ function load() {
34
+ try {
35
+ const data = JSON.parse(readFileSync(ledgerPath(), 'utf8'));
36
+ if (data && data.version === 1 && data.sessions && typeof data.sessions === 'object') return data;
37
+ } catch (e) {
38
+ if (e && e.code !== 'ENOENT') debug('usage-ledger:load', e);
39
+ }
40
+ return { version: 1, sessions: {} };
41
+ }
42
+
43
+ /** `{ day: { model: totals } }` of a parsed session or subagent run, or null when it has no usable time. */
44
+ function daysOf(x) {
45
+ if (!x) return null;
46
+ if (x.dayTotals) return x.dayTotals;
47
+ const t = x.startTime || x.endTime;
48
+ const ms = t ? new Date(t).getTime() : NaN;
49
+ if (!Number.isFinite(ms)) return null;
50
+ const models = x.modelTotals || (x.totals ? { [x.model || 'unknown']: x.totals } : null);
51
+ return models ? { [utcDay(ms)]: models } : null;
52
+ }
53
+
54
+ /**
55
+ * Upsert the usage of the given sessions (and their subagent runs). Safe to
56
+ * repeat: an entry is replaced by what the transcript says now, day by day, so
57
+ * days only an earlier, wider parse knew about are kept. Skipped entirely when
58
+ * the file was written less than an hour ago. Returns true when it wrote.
59
+ */
60
+ export function recordUsage(sessions, { now = Date.now() } = {}) {
61
+ const ledger = load();
62
+ const age = now - (ledger.writtenAt || 0);
63
+ if (ledger.writtenAt && age >= 0 && age < THROTTLE_MS) return false;
64
+
65
+ const upsert = (id, days) => {
66
+ if (!id || !days) return;
67
+ const old = ledger.sessions[id];
68
+ const merged = { ...(old ? old.days : {}), ...days };
69
+ if (old && JSON.stringify(old.days) === JSON.stringify(merged)) return;
70
+ ledger.sessions[id] = { days: merged, updatedAt: now };
71
+ };
72
+ for (const s of sessions || []) {
73
+ if (!s) continue;
74
+ upsert(s.sessionId, daysOf(s));
75
+ for (const r of s.subagentRuns || []) if (s.sessionId && r.agent) upsert(`${s.sessionId}/${r.agent}`, daysOf(r));
76
+ }
77
+
78
+ const oldest = utcDay(now - KEEP_DAYS * DAY_MS);
79
+ for (const [id, e] of Object.entries(ledger.sessions)) {
80
+ const newest = Object.keys(e.days || {}).sort().pop();
81
+ if (!newest || newest < oldest) delete ledger.sessions[id];
82
+ }
83
+
84
+ ledger.writtenAt = now;
85
+ writeStateFile(ledgerPath(), JSON.stringify(ledger) + '\n');
86
+ return true;
87
+ }
88
+
89
+ /**
90
+ * Ledger usage from the UTC day of `sinceMs` on, as parts that partCost can
91
+ * price (one per session and model). Entries named in `exclude` are skipped:
92
+ * the caller already has those from a live transcript. `own` is false for a
93
+ * subagent run, as for the parts pricedParts builds.
94
+ */
95
+ export function usageSince(sinceMs, { exclude = new Set() } = {}) {
96
+ const sinceDay = utcDay(sinceMs);
97
+ const parts = [];
98
+ for (const [id, e] of Object.entries(load().sessions)) {
99
+ if (exclude.has(id)) continue;
100
+ const byModel = {};
101
+ for (const [day, models] of Object.entries(e.days || {})) {
102
+ if (day < sinceDay) continue;
103
+ for (const [model, totals] of Object.entries(models)) (byModel[model] ||= {})[day] = totals;
104
+ }
105
+ for (const [model, byDay] of Object.entries(byModel)) {
106
+ const days = Object.keys(byDay).sort();
107
+ parts.push({
108
+ id,
109
+ model,
110
+ totals: sumTotals(days.map((d) => byDay[d])),
111
+ at: Date.parse(`${days[0]}T12:00:00Z`),
112
+ byDay,
113
+ own: !id.includes('/'),
114
+ });
115
+ }
116
+ }
117
+ return parts;
118
+ }