sprag-cli 3.114.0 → 3.115.1

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
@@ -44,7 +44,7 @@ import {
44
44
 
45
45
  import { ultracodeChipState } from '../src/ultracode.js';
46
46
 
47
- import { parseAllSessions, sessionsSince, getLastUserMessageTime } from '../src/parser.js';
47
+ import { parseAllSessions, sessionsSince, getLastUserMessageTime, flushPendingSessionCache, parseStats } from '../src/parser.js';
48
48
  import {
49
49
  dailyTrend,
50
50
  ttlBreakdown,
@@ -84,6 +84,22 @@ const PKG_VERSION = (() => {
84
84
  }
85
85
  })();
86
86
 
87
+ /**
88
+ * A session that was already open when the organisation raised its minimum
89
+ * version never runs SessionStart again, so the statusline starts the upgrade.
90
+ * maybeStartOrgUpgrade does the in-flight, cooldown and dev-checkout checks, and
91
+ * returns after one team.json read when there is no target. Called after the
92
+ * render is out, so it cannot eat into the statusline time budget.
93
+ */
94
+ async function startOrgUpgradeFromStatusline() {
95
+ try {
96
+ const { maybeStartOrgUpgrade } = await import('../src/org-upgrade.js');
97
+ maybeStartOrgUpgrade(PKG_VERSION, { agent: 'claude' });
98
+ } catch (e) {
99
+ debug('statusline:org-upgrade', e);
100
+ }
101
+ }
102
+
87
103
  const { getArg, hasFlag, numArg } = createArgs(args);
88
104
 
89
105
  /**
@@ -658,9 +674,15 @@ async function main() {
658
674
  if (last !== null) console.log(last);
659
675
  return;
660
676
  }
677
+ const budgetMs = g.statuslineBudgetMs();
661
678
  const timer = g.armStatuslineDeadline({
662
- budgetMs: g.statuslineBudgetMs(),
679
+ budgetMs,
663
680
  onExpire: () => {
681
+ // Keep what the parse got through, so the next render starts further along.
682
+ try { flushPendingSessionCache(); } catch (e) { debug('statusline:flush', e); }
683
+ try {
684
+ debug('statusline:budget', new Error('render over ' + budgetMs + 'ms: ' + JSON.stringify(parseStats())));
685
+ } catch { /* a diagnostic never breaks the statusline */ }
664
686
  const last = g.readLastRender({ key });
665
687
  if (last !== null) console.log(last);
666
688
  lock.release();
@@ -769,6 +791,7 @@ async function main() {
769
791
  ), { input: readStdinRaw() });
770
792
  if (guard) guard.finish(noSessionOut);
771
793
  console.log(noSessionOut);
794
+ if (!demoArg) await startOrgUpgradeFromStatusline();
772
795
  return;
773
796
  }
774
797
  // JSON mode stays JSON. A caller that asked for machine-readable output
@@ -1251,6 +1274,7 @@ async function main() {
1251
1274
  if (guard) guard.finish(output);
1252
1275
  }
1253
1276
  console.log(output);
1277
+ if (format === 'statusline' && !demoArg) await startOrgUpgradeFromStatusline();
1254
1278
  }
1255
1279
 
1256
1280
  main().catch((err) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.114.0",
3
+ "version": "3.115.1",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cost.js CHANGED
@@ -382,7 +382,9 @@ export function modelRank(model) {
382
382
 
383
383
  /**
384
384
  * Price rank each delegation tier targets: T2 → haiku, T1 → sonnet, T1H → opus.
385
- * T1H is worth it only from a rank-3 (Fable/Mythos) session.
385
+ * T1H is worth it only from a rank-3 (Fable/Mythos) session. Fable 5.2
386
+ * ($8/$40) still costs twice Opus 5.5 ($4/$20), so it keeps rank 3 and a
387
+ * Fable 5.2 session still saves about half by handing heavy work to opus.
386
388
  */
387
389
  export const TIER_TARGET_RANK = { T2: 0, T1: 1, T1H: 2 };
388
390
 
package/src/parser.js CHANGED
@@ -1,4 +1,5 @@
1
- import { openSync, readSync, closeSync, fstatSync } from 'node:fs';
1
+ import { openSync, readSync, closeSync, fstatSync, statSync, createReadStream } from 'node:fs';
2
+ import { once } from 'node:events';
2
3
  import { readdir, stat } from 'node:fs/promises';
3
4
  import { transcriptLines } from './transcript-lines.js';
4
5
  import { join, isAbsolute, basename } from 'node:path';
@@ -6,6 +7,8 @@ import { homedir } from 'node:os';
6
7
  import { loadCache, getCached, putCached, saveCache, getCachedSince, putCachedSince } from './session-cache.js';
7
8
  import { resolveModelAlias, isGatewayModelId } from './model-alias.js';
8
9
  import { LONG_PROMPT_THRESHOLD } from './cost.js';
10
+ import { storeEligible, readStore, writeStore, hashBefore } from './request-store.js';
11
+ import { debug } from './debug.js';
9
12
 
10
13
  const CLAUDE_DIR = join(homedir(), '.claude', 'projects');
11
14
 
@@ -22,73 +25,237 @@ function usageLooksGatewayShaped(usage) {
22
25
  return GATEWAY_USAGE_KEYS.some((k) => Object.prototype.hasOwnProperty.call(usage, k));
23
26
  }
24
27
 
28
+ // How often a long parse run writes its progress to the session cache, so that a
29
+ // render killed by the statusline time budget keeps what it already parsed.
30
+ const PROGRESS_SAVE_MS = 1000;
31
+
32
+ // Counters of the parse work done by this process. The statusline records them
33
+ // when its time budget runs out, which says whether the render was slow because
34
+ // of whole-file parses or because of the number of files.
35
+ const stats = { full: 0, resumed: 0, bytes: 0 };
36
+
37
+ /** @returns {{full:number, resumed:number, bytes:number}} files parsed whole, files resumed from the request store, bytes read */
38
+ export function parseStats() {
39
+ return { ...stats };
40
+ }
41
+
42
+ export function resetParseStats() {
43
+ stats.full = 0;
44
+ stats.resumed = 0;
45
+ stats.bytes = 0;
46
+ }
47
+
48
+ // The session cache a parseAllSessions run is filling right now, so a caller
49
+ // that is about to exit (the statusline deadline) can persist the progress.
50
+ let pendingCache = null;
51
+
52
+ /** Save the in-flight parse run's cache when it holds entries not written yet. */
53
+ export function flushPendingSessionCache() {
54
+ const p = pendingCache;
55
+ if (!p || !(p.misses > p.saved)) return;
56
+ p.saved = p.misses;
57
+ saveCache(p.cache, p.path);
58
+ }
59
+
60
+ function newParseState(track) {
61
+ return {
62
+ requests: new Map(),
63
+ // Raw model id per request, kept only when a request store is being written.
64
+ raw: track ? new Map() : null,
65
+ sessionId: null,
66
+ firstTimestamp: null,
67
+ lastTimestamp: null,
68
+ gatewayObserved: false,
69
+ };
70
+ }
71
+
72
+ /** Fold one transcript line into the parse state. Shared by the whole-file and the resumed read. */
73
+ function consumeLine(st, line) {
74
+ let entry;
75
+ try {
76
+ entry = JSON.parse(line);
77
+ } catch {
78
+ return;
79
+ }
80
+
81
+ const ts = entry.timestamp;
82
+ if (ts) {
83
+ if (!st.firstTimestamp || ts < st.firstTimestamp) st.firstTimestamp = ts;
84
+ if (!st.lastTimestamp || ts > st.lastTimestamp) st.lastTimestamp = ts;
85
+ }
86
+
87
+ if (!st.sessionId && entry.sessionId) {
88
+ st.sessionId = entry.sessionId;
89
+ }
90
+
91
+ const msg = entry.message;
92
+ if (!msg?.usage || !msg.id) return;
93
+
94
+ const usage = msg.usage;
95
+ // "<synthetic>" marks a stub Claude Code wrote locally, such as an error or
96
+ // an interrupt notice. No API call was made and no token was billed, so it
97
+ // is not a request, and a transcript holding nothing else is not a session.
98
+ // Counted, they put hundreds of calls that never happened into the report.
99
+ if (msg.model === '<synthetic>' && !(usage.input_tokens || usage.output_tokens ||
100
+ usage.cache_creation_input_tokens || usage.cache_read_input_tokens)) return;
101
+ const cc = usage.cache_creation || {};
102
+ const reqId = entry.requestId || msg.id;
103
+
104
+ // Recorded from the RAW id, before resolveModelAlias() turns the ARN into
105
+ // a plain model name. Downstream this is the only thing that distinguishes
106
+ // "no cache writes yet" from "a gateway that never reports the TTL split",
107
+ // and those two states want opposite countdown defaults.
108
+ if (!st.gatewayObserved && (isGatewayModelId(msg.model) || usageLooksGatewayShaped(usage))) {
109
+ st.gatewayObserved = true;
110
+ }
111
+
112
+ st.requests.set(reqId, {
113
+ requestId: reqId,
114
+ // Per-request timestamp so callers can filter by time window — the
115
+ // mtime-based file filter alone lets a long-lived session drag
116
+ // months-old requests into a narrow --days window.
117
+ ts: ts ? Date.parse(ts) : null,
118
+ model: resolveModelAlias(msg.model),
119
+ inputTokens: usage.input_tokens || 0,
120
+ cacheCreationTokens: usage.cache_creation_input_tokens || 0,
121
+ cacheReadTokens: usage.cache_read_input_tokens || 0,
122
+ ephemeral5mTokens: cc.ephemeral_5m_input_tokens || 0,
123
+ ephemeral1hTokens: cc.ephemeral_1h_input_tokens || 0,
124
+ outputTokens: usage.output_tokens || 0,
125
+ });
126
+ if (st.raw) st.raw.set(reqId, msg.model ?? null);
127
+ }
128
+
129
+ /** The request store's view of the parse state as of `offset`. */
130
+ function snapshotStore(st, offset, filePath) {
131
+ const tailHash = hashBefore(filePath, offset);
132
+ if (!tailHash) return null;
133
+ const reqs = [];
134
+ for (const [id, r] of st.requests) {
135
+ // A timestamp that does not parse is NaN, which JSON would turn into null.
136
+ reqs.push([id, Number.isNaN(r.ts) ? 'NaN' : r.ts, st.raw.get(id) ?? null, r.inputTokens, r.cacheCreationTokens,
137
+ r.cacheReadTokens, r.ephemeral5mTokens, r.ephemeral1hTokens, r.outputTokens]);
138
+ }
139
+ return {
140
+ offset, tailHash, sessionId: st.sessionId, firstTs: st.firstTimestamp, lastTs: st.lastTimestamp,
141
+ gatewayObserved: !!st.gatewayObserved, reqs,
142
+ };
143
+ }
144
+
145
+ function restoreState(st, stored) {
146
+ st.sessionId = stored.sessionId ?? null;
147
+ st.firstTimestamp = stored.firstTs ?? null;
148
+ st.lastTimestamp = stored.lastTs ?? null;
149
+ st.gatewayObserved = !!stored.gatewayObserved;
150
+ for (const row of stored.reqs) {
151
+ if (!Array.isArray(row) || row.length < 9) throw new Error('malformed request row');
152
+ const [id, ts, rawModel, input, cacheCreation, cacheRead, e5m, e1h, output] = row;
153
+ st.requests.set(id, {
154
+ requestId: id,
155
+ ts: ts === 'NaN' ? NaN : ts,
156
+ model: resolveModelAlias(rawModel),
157
+ inputTokens: input,
158
+ cacheCreationTokens: cacheCreation,
159
+ cacheReadTokens: cacheRead,
160
+ ephemeral5mTokens: e5m,
161
+ ephemeral1hTokens: e1h,
162
+ outputTokens: output,
163
+ });
164
+ st.raw.set(id, rawModel);
165
+ }
166
+ }
167
+
25
168
  /**
26
- * Parse a single session JSONL file.
27
- * Deduplicates by requestId (last-write-wins for streaming chunks).
169
+ * Read a transcript from byte `start`, feeding each complete line to the state.
170
+ * A final line without its newline may still be growing, so it is not consumed:
171
+ * it is returned as `tail` and `consumed` stops before it.
28
172
  */
29
- export async function parseSessionFile(filePath) {
30
- const requests = new Map();
31
- let sessionId = null;
32
- let firstTimestamp = null;
33
- let lastTimestamp = null;
34
- let gatewayObserved = false;
35
-
36
- for await (const line of transcriptLines(filePath)) {
37
- let entry;
38
- try {
39
- entry = JSON.parse(line);
40
- } catch {
41
- continue;
42
- }
43
-
44
- const ts = entry.timestamp;
45
- if (ts) {
46
- if (!firstTimestamp || ts < firstTimestamp) firstTimestamp = ts;
47
- if (!lastTimestamp || ts > lastTimestamp) lastTimestamp = ts;
173
+ async function readFromOffset(filePath, start, st) {
174
+ let consumed = start;
175
+ let bytes = 0;
176
+ let pending = [];
177
+ let pendingLen = 0;
178
+ const stream = createReadStream(filePath, { start });
179
+ try {
180
+ for await (const chunk of stream) {
181
+ bytes += chunk.length;
182
+ let from = 0;
183
+ let nl;
184
+ while ((nl = chunk.indexOf(0x0a, from)) !== -1) {
185
+ let lineBuf = chunk.subarray(from, nl);
186
+ if (pendingLen) {
187
+ lineBuf = Buffer.concat([...pending, lineBuf]);
188
+ pending = [];
189
+ pendingLen = 0;
190
+ }
191
+ consumed += lineBuf.length + 1;
192
+ consumeLine(st, lineBuf.toString('utf8'));
193
+ from = nl + 1;
194
+ }
195
+ if (from < chunk.length) {
196
+ const rest = chunk.subarray(from);
197
+ pending.push(rest);
198
+ pendingLen += rest.length;
199
+ }
48
200
  }
201
+ } finally {
202
+ stream.destroy();
203
+ if (!stream.closed) await once(stream, 'close').catch(() => {});
204
+ }
205
+ return { consumed, bytes, tail: pendingLen ? Buffer.concat(pending).toString('utf8') : null };
206
+ }
49
207
 
50
- if (!sessionId && entry.sessionId) {
51
- sessionId = entry.sessionId;
208
+ /**
209
+ * Parse a single session JSONL file.
210
+ * Deduplicates by requestId (last-write-wins for streaming chunks).
211
+ *
212
+ * A transcript of `STORE_MIN_BYTES` or more is parsed incrementally from its
213
+ * request store (see request-store.js): only the bytes appended since the last
214
+ * parse are read. The result is identical to a whole-file parse.
215
+ *
216
+ * @param {string} filePath
217
+ * @param {{ store?: boolean, minBytes?: number }} [options] `store: false` parses the
218
+ * whole file and neither reads nor writes the request store; `minBytes` replaces
219
+ * the size from which a transcript gets a store.
220
+ */
221
+ export async function parseSessionFile(filePath, { store = true, minBytes } = {}) {
222
+ let size = 0;
223
+ try { size = statSync(filePath).size; } catch { /* the read below reports the problem */ }
224
+ let st = newParseState(false);
225
+
226
+ if (!(store && storeEligible(filePath, size, minBytes))) {
227
+ for await (const line of transcriptLines(filePath)) consumeLine(st, line);
228
+ stats.full++;
229
+ stats.bytes += size;
230
+ } else {
231
+ st = newParseState(true);
232
+ let prior = readStore(filePath, size);
233
+ let start = 0;
234
+ if (prior) {
235
+ try {
236
+ restoreState(st, prior);
237
+ start = prior.offset;
238
+ } catch (e) {
239
+ debug('request-store:restore', e);
240
+ st = newParseState(true);
241
+ prior = null;
242
+ }
52
243
  }
53
-
54
- const msg = entry.message;
55
- if (!msg?.usage || !msg.id) continue;
56
-
57
- const usage = msg.usage;
58
- // "<synthetic>" marks a stub Claude Code wrote locally, such as an error or
59
- // an interrupt notice. No API call was made and no token was billed, so it
60
- // is not a request, and a transcript holding nothing else is not a session.
61
- // Counted, they put hundreds of calls that never happened into the report.
62
- if (msg.model === '<synthetic>' && !(usage.input_tokens || usage.output_tokens ||
63
- usage.cache_creation_input_tokens || usage.cache_read_input_tokens)) continue;
64
- const cc = usage.cache_creation || {};
65
- const reqId = entry.requestId || msg.id;
66
-
67
- // Recorded from the RAW id, before resolveModelAlias() turns the ARN into
68
- // a plain model name. Downstream this is the only thing that distinguishes
69
- // "no cache writes yet" from "a gateway that never reports the TTL split",
70
- // and those two states want opposite countdown defaults.
71
- if (!gatewayObserved && (isGatewayModelId(msg.model) || usageLooksGatewayShaped(usage))) {
72
- gatewayObserved = true;
244
+ let consumed = start;
245
+ let bytes = 0;
246
+ let tail = null;
247
+ if (start < size) ({ consumed, bytes, tail } = await readFromOffset(filePath, start, st));
248
+ if (prior) stats.resumed++; else stats.full++;
249
+ stats.bytes += bytes;
250
+ if (consumed > 0 && (!prior || consumed !== prior.offset)) {
251
+ const snap = snapshotStore(st, consumed, filePath);
252
+ if (snap) writeStore(filePath, snap);
73
253
  }
74
-
75
- requests.set(reqId, {
76
- requestId: reqId,
77
- // Per-request timestamp so callers can filter by time window — the
78
- // mtime-based file filter alone lets a long-lived session drag
79
- // months-old requests into a narrow --days window.
80
- ts: ts ? Date.parse(ts) : null,
81
- model: resolveModelAlias(msg.model),
82
- inputTokens: usage.input_tokens || 0,
83
- cacheCreationTokens: usage.cache_creation_input_tokens || 0,
84
- cacheReadTokens: usage.cache_read_input_tokens || 0,
85
- ephemeral5mTokens: cc.ephemeral_5m_input_tokens || 0,
86
- ephemeral1hTokens: cc.ephemeral_1h_input_tokens || 0,
87
- outputTokens: usage.output_tokens || 0,
88
- });
254
+ // The unterminated last line counts for this result but not for the store.
255
+ if (tail) consumeLine(st, tail);
89
256
  }
90
257
 
91
- const reqs = [...requests.values()];
258
+ const reqs = [...st.requests.values()];
92
259
  // Representative model: the one that handled the most requests, skipping
93
260
  // "<synthetic>" (Claude Code's local error-stub placeholder — no real API
94
261
  // call). Taking reqs[0] blindly let an error stub at session start
@@ -108,10 +275,10 @@ export async function parseSessionFile(filePath) {
108
275
  const { totals, maxContextPerRequest, modelTotals, dayTotals } = sumRequests(reqs);
109
276
 
110
277
  return {
111
- sessionId,
278
+ sessionId: st.sessionId,
112
279
  filePath,
113
- startTime: firstTimestamp ? new Date(firstTimestamp) : null,
114
- endTime: lastTimestamp ? new Date(lastTimestamp) : null,
280
+ startTime: st.firstTimestamp ? new Date(st.firstTimestamp) : null,
281
+ endTime: st.lastTimestamp ? new Date(st.lastTimestamp) : null,
115
282
  requestCount: reqs.length,
116
283
  requests: reqs,
117
284
  totals,
@@ -119,7 +286,7 @@ export async function parseSessionFile(filePath) {
119
286
  model,
120
287
  ...(modelTotals ? { modelTotals } : {}),
121
288
  ...(dayTotals ? { dayTotals } : {}),
122
- gatewayObserved,
289
+ gatewayObserved: st.gatewayObserved,
123
290
  };
124
291
  }
125
292
 
@@ -494,7 +661,10 @@ export async function parseAllSessions(options = {}) {
494
661
  const results = [];
495
662
  const useCache = !options.noCache;
496
663
  const cache = useCache ? loadCache(options.cachePath) : { entries: {} };
497
- let misses = 0;
664
+ // `misses` counts entries added to the cache; `saved` is how many of them are on disk.
665
+ const prog = { cache, path: options.cachePath, misses: 0, saved: 0 };
666
+ let lastSaveAt = Date.now();
667
+ if (useCache) pendingCache = prog;
498
668
  // The file-level mtime filter (discoverSessionFiles) is only a cheap
499
669
  // pre-selection: a session started months ago but touched today passes it,
500
670
  // and its old requests would pollute every aggregate in the window. Any
@@ -526,9 +696,20 @@ export async function parseAllSessions(options = {}) {
526
696
  }),
527
697
  );
528
698
  results.push(...parsed.filter(Boolean));
699
+ // A cold machine can spend longer than the statusline budget here; saving
700
+ // as it goes keeps the progress when the process is cut off.
701
+ if (useCache && prog.misses > prog.saved && Date.now() - lastSaveAt >= PROGRESS_SAVE_MS) {
702
+ prog.saved = prog.misses;
703
+ lastSaveAt = Date.now();
704
+ saveCache(cache, options.cachePath);
705
+ }
529
706
  }
530
707
 
531
- if (useCache && misses > 0) saveCache(cache, options.cachePath);
708
+ if (useCache && prog.misses > prog.saved) {
709
+ prog.saved = prog.misses;
710
+ saveCache(cache, options.cachePath);
711
+ }
712
+ if (pendingCache === prog) pendingCache = null;
532
713
 
533
714
  return results.filter((s) => s.requestCount > 0);
534
715
 
@@ -548,7 +729,7 @@ export async function parseAllSessions(options = {}) {
548
729
  run = await parseSessionFile(a.path);
549
730
  if (useCache) {
550
731
  putCached(cache, a, run);
551
- misses++;
732
+ prog.misses++;
552
733
  }
553
734
  }
554
735
  if (!run.requestCount || !run.endTime || run.endTime.getTime() < cutoffMs) continue;
@@ -585,7 +766,7 @@ export async function parseAllSessions(options = {}) {
585
766
  session.projectDir = f.projectDir;
586
767
  if (useCache) {
587
768
  putCached(cache, f, session);
588
- misses++;
769
+ prog.misses++;
589
770
  }
590
771
  const { requests, ...whole } = session;
591
772
  const summary = spansCutoff(session, cutoffMs) ? trimToCutoff(session, cutoffMs) : whole;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Per-transcript request store: a sidecar file that lets a large transcript be
3
+ * parsed incrementally.
4
+ *
5
+ * The session cache keys a summary on (mtime, size), so a transcript that is
6
+ * still being written misses on every statusline tick, and a session that
7
+ * started before the window cutoff has to be re-read whole because the summary
8
+ * carries no per-request data. Both cost a full pass over a file that can be
9
+ * hundreds of megabytes. The store keeps the compact per-request records and
10
+ * the byte offset up to which the transcript has been consumed, so the next
11
+ * parse reads only the bytes appended since.
12
+ *
13
+ * Transcripts are append-only. A store is trusted only while the bytes just
14
+ * before its offset still hash to `tailHash`; anything else (a rewritten file,
15
+ * a truncated one) discards it and the caller parses from the start. Every
16
+ * failure here is soft: the caller falls back to a full parse.
17
+ */
18
+
19
+ import { createHash } from 'node:crypto';
20
+ import { openSync, readSync, closeSync, readFileSync, mkdirSync, readdirSync, lstatSync, unlinkSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+ import { userDataDir } from './paths.js';
23
+ import { writeViaTmp } from './state-file.js';
24
+ import { envVar } from './env.js';
25
+ import { debug } from './debug.js';
26
+
27
+ export const STORE_VERSION = 1;
28
+ /** Transcripts smaller than this are cheap to parse whole and get no store. */
29
+ export const STORE_MIN_BYTES = 4 * 1024 * 1024;
30
+ /** How many bytes before the offset are hashed to prove the prefix is unchanged. */
31
+ const TAIL_HASH_BYTES = 256;
32
+ /** A store untouched for this long belongs to a transcript nobody reads any more. */
33
+ export const STORE_MAX_AGE_MS = 35 * 24 * 60 * 60 * 1000;
34
+
35
+ let minBytesOverride = null;
36
+
37
+ /** Tests lower the threshold; pass null to restore the default. */
38
+ export function setStoreMinBytes(n) {
39
+ minBytesOverride = Number.isFinite(n) ? n : null;
40
+ }
41
+
42
+ export function storeMinBytes() {
43
+ return minBytesOverride ?? STORE_MIN_BYTES;
44
+ }
45
+
46
+ export function storeDir() {
47
+ return join(userDataDir(), 'request-store');
48
+ }
49
+
50
+ export function storePathFor(transcriptPath) {
51
+ const id = createHash('sha1').update(transcriptPath).digest('hex').slice(0, 20);
52
+ return join(storeDir(), `${id}.json`);
53
+ }
54
+
55
+ /** Whether a transcript of this path and size gets a store. */
56
+ export function storeEligible(filePath, size, minBytes) {
57
+ if (envVar('NO_REQUEST_STORE') === '1') return false;
58
+ if (filePath.endsWith('.zst')) return false;
59
+ return size >= (minBytes ?? storeMinBytes());
60
+ }
61
+
62
+ /** sha1 of file bytes [max(0, offset - 256), offset), or null when they cannot be read in full. */
63
+ export function hashBefore(filePath, offset) {
64
+ let fd = null;
65
+ try {
66
+ const start = Math.max(0, offset - TAIL_HASH_BYTES);
67
+ const len = offset - start;
68
+ const buf = Buffer.alloc(len);
69
+ if (len > 0) {
70
+ fd = openSync(filePath, 'r');
71
+ const got = readSync(fd, buf, 0, len, start);
72
+ if (got !== len) return null;
73
+ }
74
+ return createHash('sha1').update(buf).digest('hex');
75
+ } catch (e) {
76
+ debug('request-store:hash', e);
77
+ return null;
78
+ } finally {
79
+ if (fd !== null) try { closeSync(fd); } catch { /* already closed */ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * The stored state for a transcript when it is still a valid prefix of the
85
+ * file, else null. `size` is the file's current size.
86
+ */
87
+ export function readStore(filePath, size) {
88
+ let store;
89
+ try {
90
+ store = JSON.parse(readFileSync(storePathFor(filePath), 'utf8'));
91
+ } catch (e) {
92
+ if (e && e.code !== 'ENOENT') debug('request-store:read', e);
93
+ return null;
94
+ }
95
+ try {
96
+ if (!store || store.v !== STORE_VERSION || store.path !== filePath) return null;
97
+ if (!Number.isInteger(store.offset) || store.offset <= 0 || store.offset > size) return null;
98
+ if (!Array.isArray(store.reqs) || typeof store.tailHash !== 'string') return null;
99
+ if (hashBefore(filePath, store.offset) !== store.tailHash) return null;
100
+ return store;
101
+ } catch (e) {
102
+ debug('request-store:validate', e);
103
+ return null;
104
+ }
105
+ }
106
+
107
+ /** Atomically write the store. Never throws. */
108
+ export function writeStore(filePath, state) {
109
+ try {
110
+ const file = storePathFor(filePath);
111
+ mkdirSync(storeDir(), { recursive: true });
112
+ const body = JSON.stringify({ v: STORE_VERSION, path: filePath, ...state });
113
+ writeViaTmp(`${file}.${process.pid}.tmp`, file, body + '\n');
114
+ } catch (e) {
115
+ debug('request-store:write', e);
116
+ }
117
+ }
118
+
119
+ /** Remove stores (and stray temp files) not modified for `maxAgeMs`. Returns the count removed. */
120
+ export function pruneRequestStore({ now = Date.now(), maxAgeMs = STORE_MAX_AGE_MS, dir = storeDir() } = {}) {
121
+ let names;
122
+ try { names = readdirSync(dir); } catch { return 0; }
123
+ let removed = 0;
124
+ for (const name of names) {
125
+ const path = join(dir, name);
126
+ try {
127
+ const st = lstatSync(path);
128
+ if (!st.isFile() || now - st.mtimeMs <= maxAgeMs) continue;
129
+ unlinkSync(path);
130
+ removed += 1;
131
+ } catch { /* already gone, or not ours to remove */ }
132
+ }
133
+ return removed;
134
+ }
@@ -23,6 +23,7 @@ import { join } from 'node:path';
23
23
  import { userDataDir } from './paths.js';
24
24
  import { writeViaTmp, runHousekeeping, sweepStaleTmp } from './state-file.js';
25
25
  import { debug } from './debug.js';
26
+ import { pruneRequestStore } from './request-store.js';
26
27
 
27
28
  const CACHE_PATH = join(userDataDir(), 'session-cache.json');
28
29
  // Bump when the cached summary's shape changes — old entries are dropped
@@ -205,7 +206,10 @@ export function saveCache(cache, path = CACHE_PATH) {
205
206
  // sweep itself runs at most once a day (see runHousekeeping).
206
207
  try {
207
208
  const dir = userDataDir();
208
- runHousekeeping(dir, { 'stale-tmp': () => sweepStaleTmp(dir) });
209
+ runHousekeeping(dir, {
210
+ 'stale-tmp': () => sweepStaleTmp(dir),
211
+ 'request-store': () => pruneRequestStore(),
212
+ });
209
213
  } catch (e) {
210
214
  debug('session-cache:housekeeping', e);
211
215
  }