token-goat 2.9.13 → 2.9.15

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.
Files changed (52) hide show
  1. package/README.md +28 -1
  2. package/dist/token-goat-chunk-2X2EBBC6.mjs +277 -0
  3. package/dist/token-goat-chunk-3BTK54F3.mjs +1733 -0
  4. package/dist/token-goat-chunk-3NSDDTGL.mjs +34 -0
  5. package/dist/token-goat-chunk-4EXFN2AW.mjs +29 -0
  6. package/dist/token-goat-chunk-5V7DAC7V.mjs +123 -0
  7. package/dist/token-goat-chunk-6DLVZDB6.mjs +34 -0
  8. package/dist/token-goat-chunk-7ZYK25AO.mjs +24 -0
  9. package/dist/token-goat-chunk-A4JYKD5H.mjs +144 -0
  10. package/dist/token-goat-chunk-AH6QILZM.mjs +26 -0
  11. package/dist/token-goat-chunk-ASYEPR3S.mjs +212 -0
  12. package/dist/{token-goat-chunk-RDITECDL.mjs → token-goat-chunk-ATIFTMRC.mjs} +31 -13
  13. package/dist/{token-goat-chunk-ZZI3IDQZ.mjs → token-goat-chunk-BL5LNGBG.mjs} +3935 -11949
  14. package/dist/{token-goat-chunk-4NXUKV7D.mjs → token-goat-chunk-C5JIO6HK.mjs} +8 -4
  15. package/dist/{token-goat-chunk-FZU7GMUS.mjs → token-goat-chunk-DQ4J5AFF.mjs} +50 -18
  16. package/dist/token-goat-chunk-ERTXEKB6.mjs +228 -0
  17. package/dist/{token-goat-chunk-6B44WLIF.mjs → token-goat-chunk-GIIHUSZX.mjs} +142 -21
  18. package/dist/token-goat-chunk-GMOUBOX4.mjs +386 -0
  19. package/dist/{token-goat-chunk-3ESRORNM.mjs → token-goat-chunk-GMQQA7E4.mjs} +12576 -12326
  20. package/dist/token-goat-chunk-IVUQLQWN.mjs +2046 -0
  21. package/dist/token-goat-chunk-K7F2BFIK.mjs +2430 -0
  22. package/dist/{token-goat-chunk-U7X6LQD2.mjs → token-goat-chunk-LCZBPOIN.mjs} +10197 -9717
  23. package/dist/token-goat-chunk-LMFO66YD.mjs +331 -0
  24. package/dist/token-goat-chunk-LT7JRU6K.mjs +22 -0
  25. package/dist/token-goat-chunk-MZDIJJ3R.mjs +420 -0
  26. package/dist/token-goat-chunk-NDPO7GAH.mjs +177 -0
  27. package/dist/token-goat-chunk-NDRP4KJQ.mjs +4371 -0
  28. package/dist/token-goat-chunk-NEI4NC54.mjs +424 -0
  29. package/dist/token-goat-chunk-NU7TLMQK.mjs +585 -0
  30. package/dist/token-goat-chunk-OSUFN2FV.mjs +326 -0
  31. package/dist/token-goat-chunk-OUGNPMDA.mjs +959 -0
  32. package/dist/token-goat-chunk-PM76YS22.mjs +1341 -0
  33. package/dist/token-goat-chunk-S4XRY446.mjs +2637 -0
  34. package/dist/{token-goat-chunk-YOA4N6WA.mjs → token-goat-chunk-SFAS46RE.mjs} +5 -3
  35. package/dist/{token-goat-chunk-QWSUZWFP.mjs → token-goat-chunk-SZWYESBS.mjs} +793 -650
  36. package/dist/{token-goat-chunk-B3CTCQTH.mjs → token-goat-chunk-XEPXYDPI.mjs} +3 -2
  37. package/dist/token-goat-chunk-XTQAOTSO.mjs +89 -0
  38. package/dist/token-goat-chunk-Y4AFKTHK.mjs +22 -0
  39. package/dist/token-goat-chunk-YKG35VHC.mjs +228 -0
  40. package/dist/{token-goat-chunk-JOXLE672.mjs → token-goat-chunk-YQ7WI2CO.mjs} +990 -106
  41. package/dist/{token-goat-chunk-2WC4ZUXN.mjs → token-goat-chunk-YZX7EFG4.mjs} +1 -1
  42. package/dist/token-goat-chunk-Z6UXPYJA.mjs +62 -0
  43. package/dist/token-goat-hook.mjs +16 -8
  44. package/dist/token-goat.core.mjs +27 -10
  45. package/docs/cli.md +9 -6
  46. package/package.json +4 -2
  47. package/dist/token-goat-chunk-FQCNJV4V.mjs +0 -693
  48. package/dist/token-goat-chunk-JVNPCQB7.mjs +0 -31
  49. package/dist/token-goat-chunk-P2PU4CR5.mjs +0 -26
  50. package/dist/token-goat-chunk-QKXBGBQR.mjs +0 -3653
  51. package/dist/token-goat-chunk-UM47DRD3.mjs +0 -242
  52. package/dist/token-goat-chunk-UMXJN7DI.mjs +0 -5521
@@ -0,0 +1,2046 @@
1
+ import { createRequire as __cjsRequire } from 'node:module';
2
+ const require = __cjsRequire(import.meta.url);
3
+ import {
4
+ getDb
5
+ } from "./token-goat-chunk-K7F2BFIK.mjs";
6
+ import {
7
+ getHarnessName,
8
+ loadConfig
9
+ } from "./token-goat-chunk-S4XRY446.mjs";
10
+ import {
11
+ registerReset
12
+ } from "./token-goat-chunk-EEIDFMEM.mjs";
13
+ import {
14
+ VERSION,
15
+ atomicWriteText,
16
+ countNoun,
17
+ dataDir,
18
+ dataDirForHome,
19
+ ensureDirSync,
20
+ sanitizeIdForFilename,
21
+ tokenGoatHome
22
+ } from "./token-goat-chunk-PM76YS22.mjs";
23
+ import {
24
+ displaySafeText
25
+ } from "./token-goat-chunk-ERTXEKB6.mjs";
26
+ import {
27
+ growsExponentially,
28
+ hasNestedQuantifier
29
+ } from "./token-goat-chunk-GMOUBOX4.mjs";
30
+ import {
31
+ init_define_import_meta_env
32
+ } from "./token-goat-chunk-A37V4PBF.mjs";
33
+
34
+ // src/render/ansi.ts
35
+ init_define_import_meta_env();
36
+ function _colorStream(isatty) {
37
+ if (process.env["NO_COLOR"]) return false;
38
+ return isatty;
39
+ }
40
+ function colorStdout() {
41
+ return _colorStream(process.stdout.isTTY === true);
42
+ }
43
+ var _E = "\x1B";
44
+ var RESET = `${_E}[0m`;
45
+ var _ANSI_ESCAPE_RE = /\x1B\[[0-?]*[ -/]*[@-~]|\x1B\].*?(?:\x07|\x1B\\|$)|\x1B[PX^_].*?\x1B\\|\x1B[@-_]/gs;
46
+ var _PUA_RE = /[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}]/gu;
47
+ function stripAnsiEscapes(s) {
48
+ if (!s.includes("\x1B")) {
49
+ return s;
50
+ }
51
+ return s.replace(_ANSI_ESCAPE_RE, "");
52
+ }
53
+ function stripAnsi(s) {
54
+ if (!s.includes("\x1B")) {
55
+ return s;
56
+ }
57
+ return stripAnsiEscapes(s).replace(_PUA_RE, "");
58
+ }
59
+ function fmtBytes(n) {
60
+ let value = n;
61
+ const units = ["B", "KB", "MB", "GB", "TB"];
62
+ for (const unit of units) {
63
+ if (Math.abs(value) < 1024) {
64
+ return unit === "B" ? `${Math.trunc(value)}${unit}` : `${value.toFixed(1)}${unit}`;
65
+ }
66
+ value = value / 1024;
67
+ }
68
+ return `${value.toFixed(1)}PB`;
69
+ }
70
+ function fg(r, g, b) {
71
+ return `${_E}[38;2;${r};${g};${b}m`;
72
+ }
73
+ function vlen(s) {
74
+ return stripAnsi(s).length;
75
+ }
76
+ function padR(s, w) {
77
+ return s + " ".repeat(Math.max(0, w - vlen(s)));
78
+ }
79
+ function padL(s, w) {
80
+ return " ".repeat(Math.max(0, w - vlen(s))) + s;
81
+ }
82
+ function lerpRgb(a, b, t) {
83
+ return [
84
+ Math.round(a[0] + (b[0] - a[0]) * t),
85
+ Math.round(a[1] + (b[1] - a[1]) * t),
86
+ Math.round(a[2] + (b[2] - a[2]) * t)
87
+ ];
88
+ }
89
+ var C = {
90
+ TEXT_PRIMARY: [201, 209, 217],
91
+ TEXT_BRIGHT: [240, 246, 252],
92
+ TEXT_MUTED: [125, 133, 144],
93
+ TEXT_DIM: [72, 79, 88],
94
+ BG_TILE: [22, 27, 34],
95
+ TRACK: [28, 35, 41],
96
+ GREEN1: [31, 77, 44],
97
+ GREEN2: [46, 160, 67],
98
+ GREEN3: [63, 185, 80],
99
+ GREEN4: [86, 211, 100],
100
+ GREEN5: [126, 231, 135],
101
+ BLUE: [88, 166, 255],
102
+ PURPLE: [188, 140, 255],
103
+ TEAL: [138, 212, 255],
104
+ ORANGE: [235, 165, 80],
105
+ YELLOW: [240, 215, 80],
106
+ RED: [200, 60, 60]
107
+ };
108
+
109
+ // src/stats.ts
110
+ init_define_import_meta_env();
111
+ import * as path from "node:path";
112
+
113
+ // src/render/stats_renderer.ts
114
+ init_define_import_meta_env();
115
+ var _STATS_MESSAGES_FALLBACK = {
116
+ bytesModeOnlyNote: "tracks bytes, not vision tokens",
117
+ sessionHintSplitNote: "session_hint shows realized savings; session_hint_overhead shows injected hint cost",
118
+ insights: {
119
+ biggestSaver: "Biggest saver ",
120
+ mostActive: "Most active ",
121
+ tokenLeader: "Token leader "
122
+ }
123
+ };
124
+ var _STATS_MESSAGES = _STATS_MESSAGES_FALLBACK;
125
+ var _TERM_W = process.stdout.columns || 100;
126
+ var _CONTENT_W = Math.min(Math.max(_TERM_W, 80), 140);
127
+ var _M = " ";
128
+ var _COL_NAME = 18;
129
+ var _COL_DATA = 10;
130
+ var _COL_TOKENS = 12;
131
+ var _COL_SHARE = 6;
132
+ var _COL_EVENTS = 6;
133
+ var _COLS_FIXED = _COL_NAME + 1 + 2 + _COL_DATA + 2 + _COL_TOKENS + 2 + _COL_SHARE + 2 + _COL_EVENTS;
134
+ var _BAR_W = Math.max(16, _CONTENT_W - _M.length * 2 - _COLS_FIXED);
135
+ var _RULE = _M + fg(...C.TEXT_DIM) + "\u2500".repeat(_CONTENT_W - _M.length * 2) + RESET;
136
+ var _BYTE_TIERS = [
137
+ { threshold: 1e15, divisor: 1e15, unit: "PB", color: C.PURPLE },
138
+ { threshold: 1e12, divisor: 1e12, unit: "TB", color: C.BLUE },
139
+ { threshold: 1e9, divisor: 1e9, unit: "GB", color: C.TEAL },
140
+ { threshold: 1e6, divisor: 1e6, unit: "MB", color: C.GREEN4 },
141
+ { threshold: 1e3, divisor: 1e3, unit: "KB", color: C.TEXT_MUTED },
142
+ { threshold: 0, divisor: 1, unit: "B", color: C.TEXT_DIM }
143
+ ];
144
+ var _TOKEN_TIERS = [
145
+ { threshold: 1e12, divisor: 1e12, unit: "Tt", color: C.GREEN5 },
146
+ { threshold: 1e9, divisor: 1e9, unit: "Gt", color: C.TEAL },
147
+ { threshold: 1e6, divisor: 1e6, unit: "Mt", color: C.PURPLE },
148
+ { threshold: 1e3, divisor: 1e3, unit: "kt", color: C.BLUE },
149
+ { threshold: 0, divisor: 1, unit: "t", color: C.TEXT_DIM }
150
+ ];
151
+ function _fmtMagnitude(n, tiers, zeroLabel) {
152
+ if (zeroLabel !== void 0 && n === 0) {
153
+ return `${fg(...C.TEXT_DIM)}${zeroLabel}${RESET}`;
154
+ }
155
+ if (n < 0) {
156
+ const a = -n;
157
+ const color = C.TEXT_DIM;
158
+ for (const tier of tiers) {
159
+ if (a >= tier.threshold && tier.threshold > 0) {
160
+ return `${fg(...color)}-${(a / tier.divisor).toLocaleString("en", { maximumFractionDigits: 1 })} ${tier.unit}${RESET}`;
161
+ }
162
+ }
163
+ const lastTier2 = tiers[tiers.length - 1];
164
+ if (lastTier2) {
165
+ return `${fg(...color)}-${a} ${lastTier2.unit}${RESET}`;
166
+ }
167
+ return `${fg(...color)}-${a}${RESET}`;
168
+ }
169
+ for (const tier of tiers) {
170
+ if (n >= tier.threshold && tier.threshold > 0) {
171
+ return `${fg(...tier.color)}${(n / tier.divisor).toLocaleString("en", { maximumFractionDigits: 1 })} ${tier.unit}${RESET}`;
172
+ }
173
+ }
174
+ const lastTier = tiers[tiers.length - 1];
175
+ if (lastTier) {
176
+ return `${fg(...lastTier.color)}${n} ${lastTier.unit}${RESET}`;
177
+ }
178
+ return `${n}${RESET}`;
179
+ }
180
+ function _fmtBytes(n) {
181
+ return _fmtMagnitude(n, _BYTE_TIERS);
182
+ }
183
+ function _fmtTokens(n) {
184
+ return _fmtMagnitude(n, _TOKEN_TIERS, "0 t");
185
+ }
186
+ function _fmtPct(fraction) {
187
+ return `${(fraction * 100).toFixed(1)}%`;
188
+ }
189
+ function _fmtDelta(delta) {
190
+ if (!delta && delta !== 0) {
191
+ return "";
192
+ }
193
+ const up = (delta ?? 0) >= 0;
194
+ const color = up ? C.GREEN5 : C.RED;
195
+ const arrow = up ? "\u2191" : "\u2193";
196
+ return ` ${fg(...color)}${arrow} ${Math.round(Math.abs(delta ?? 0))}%${RESET}`;
197
+ }
198
+ var _EIGHTHS = ["\u258F", "\u258E", "\u258D", "\u258C", "\u258B", "\u258A", "\u2589"];
199
+ var _BLOCK = "\u2588";
200
+ var _TRACK = "\u2591";
201
+ var _GRADIENT = [C.GREEN1, C.GREEN2, C.GREEN3, C.GREEN4, C.GREEN5];
202
+ function _distribute(total, n) {
203
+ if (total <= 0 || n <= 0) {
204
+ return Array(Math.max(0, n)).fill(0);
205
+ }
206
+ const base = Math.floor(total / n);
207
+ const rem = total % n;
208
+ return Array.from({ length: n }, (_, i) => base + (i >= n - rem ? 1 : 0));
209
+ }
210
+ function _renderBar(fraction, width = _BAR_W) {
211
+ const f = Math.max(0, Math.min(1, fraction));
212
+ const raw = f * width;
213
+ let nFull = Math.floor(raw);
214
+ const eighths = Math.round((raw - nFull) * 8);
215
+ if (eighths >= 8) {
216
+ nFull += 1;
217
+ }
218
+ const hasPartial = eighths > 0 && eighths < 8;
219
+ const nTrack = Math.max(0, width - nFull - (hasPartial ? 1 : 0));
220
+ const counts = _distribute(nFull, _GRADIENT.length);
221
+ let bar = counts.map((count, i) => count > 0 ? `${fg(_GRADIENT[i][0], _GRADIENT[i][1], _GRADIENT[i][2])}${_BLOCK.repeat(count)}` : "").join("");
222
+ if (hasPartial) {
223
+ const lastGrad = _GRADIENT[_GRADIENT.length - 1];
224
+ bar += `${fg(lastGrad[0], lastGrad[1], lastGrad[2])}${_EIGHTHS[eighths - 1]}`;
225
+ }
226
+ if (nTrack > 0) {
227
+ bar += `${fg(...C.TRACK)}${_TRACK.repeat(nTrack)}`;
228
+ }
229
+ return bar + RESET;
230
+ }
231
+ var _SPARK = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
232
+ function _resample(vals, length) {
233
+ if (vals.length === 0) {
234
+ return Array(length).fill(0);
235
+ }
236
+ if (vals.length === length) {
237
+ return [...vals];
238
+ }
239
+ const result = [];
240
+ for (let i = 0; i < length; i++) {
241
+ const src = i / (length - 1 || 1) * (vals.length - 1);
242
+ const lo = Math.floor(src);
243
+ const hi = Math.min(vals.length - 1, lo + 1);
244
+ const t = src - lo;
245
+ const loVal = vals[lo] ?? 0;
246
+ const hiVal = vals[hi] ?? 0;
247
+ result.push(loVal * (1 - t) + hiVal * t);
248
+ }
249
+ return result;
250
+ }
251
+ function _renderSparkline(values, width = 8) {
252
+ const pts = _resample(values, width);
253
+ const hi = pts.length > 0 ? Math.max(...pts) : 1;
254
+ const lo = pts.length > 0 ? Math.min(...pts) : 0;
255
+ const span = hi - lo || 1;
256
+ const chars = [];
257
+ for (let i = 0; i < pts.length; i++) {
258
+ const v = pts[i];
259
+ if (v === void 0) continue;
260
+ const idx = Math.min(7, Math.floor((v - lo) / span * 8));
261
+ const color = lerpRgb(C.GREEN1, C.GREEN5, i / (width - 1 || 1));
262
+ chars.push(`${fg(color[0], color[1], color[2])}${_SPARK[idx]}`);
263
+ }
264
+ return chars.join("") + RESET;
265
+ }
266
+ function _tokenOrByteShare(itemTokens, itemBytes, totalTokens, totalBytes) {
267
+ if (totalTokens > 0) {
268
+ return itemTokens / totalTokens;
269
+ }
270
+ if (totalBytes > 0) {
271
+ return itemBytes / totalBytes;
272
+ }
273
+ return 0;
274
+ }
275
+ function _barFraction(itemBytes, grossBytes) {
276
+ return itemBytes > 0 ? itemBytes / grossBytes : 0;
277
+ }
278
+ function _computeShareDenominators(items) {
279
+ let grossBytesSum = 0;
280
+ let shareByteSum = 0;
281
+ let shareTokensSum = 0;
282
+ for (const item of items) {
283
+ if (item.bytes > 0) {
284
+ grossBytesSum += item.bytes;
285
+ }
286
+ shareByteSum += Math.abs(item.bytes);
287
+ shareTokensSum += Math.abs(item.tokens);
288
+ }
289
+ return {
290
+ grossBytes: Math.max(grossBytesSum, 1),
291
+ shareBytesDenom: Math.max(shareByteSum, 1),
292
+ shareTokensDenom: shareTokensSum
293
+ };
294
+ }
295
+ function _absShare(itemBytes, itemTokens, shareBytesDenom, shareTokensDenom) {
296
+ if (shareTokensDenom === 0) {
297
+ return itemBytes / shareBytesDenom;
298
+ }
299
+ return itemTokens / shareTokensDenom;
300
+ }
301
+ function _sectionHeader(title, subtitle = "") {
302
+ const sub = subtitle ? ` ${fg(...C.TEXT_MUTED)}${subtitle}${RESET}` : "";
303
+ return [
304
+ "",
305
+ `${_M}${fg(...C.TEXT_BRIGHT)}${title}${RESET}${sub}`,
306
+ _RULE
307
+ ];
308
+ }
309
+ function _tableHeader(firstColLabel) {
310
+ return [
311
+ _M,
312
+ padR(`${fg(...C.TEXT_DIM)}${firstColLabel}${RESET}`, _COL_NAME),
313
+ " ",
314
+ padR(`${fg(...C.TEXT_DIM)}savings${RESET}`, _BAR_W),
315
+ " ",
316
+ padL(`${fg(...C.TEXT_DIM)}data saved${RESET}`, _COL_DATA),
317
+ " ",
318
+ padL(`${fg(...C.TEXT_DIM)}tokens saved${RESET}`, _COL_TOKENS),
319
+ " ",
320
+ padL(`${fg(...C.TEXT_DIM)}share${RESET}`, _COL_SHARE),
321
+ " ",
322
+ padL(`${fg(...C.TEXT_DIM)}events${RESET}`, _COL_EVENTS)
323
+ ].join("");
324
+ }
325
+ function _tableRow({
326
+ name,
327
+ fraction,
328
+ bytes,
329
+ tokens,
330
+ events,
331
+ share,
332
+ bytesModeOnly = false,
333
+ namePrefix = "",
334
+ nameColor = C.TEXT_PRIMARY
335
+ }) {
336
+ const prefixW = vlen(namePrefix);
337
+ const maxName = _COL_NAME - prefixW;
338
+ const truncated = name.length > maxName ? name.slice(0, maxName - 1) + "\u2026" : name;
339
+ const nameStr = padR(`${namePrefix}${fg(...nameColor)}${truncated}${RESET}`, _COL_NAME);
340
+ const dataStr = padL(_fmtBytes(bytes), _COL_DATA);
341
+ const tokStr = bytesModeOnly ? padL(`${fg(...C.TEXT_DIM)}\u2014${RESET}`, _COL_TOKENS) : padL(_fmtTokens(tokens), _COL_TOKENS);
342
+ const sharePct = share * 100;
343
+ let shareColor;
344
+ if (sharePct < 0) {
345
+ shareColor = C.RED;
346
+ } else if (sharePct >= 50) {
347
+ shareColor = C.GREEN5;
348
+ } else if (sharePct >= 10) {
349
+ shareColor = C.TEXT_PRIMARY;
350
+ } else {
351
+ shareColor = C.TEXT_MUTED;
352
+ }
353
+ const shareStr = padL(`${fg(...shareColor)}${_fmtPct(share)}${RESET}`, _COL_SHARE);
354
+ const evStr = padL(`${fg(...C.TEXT_PRIMARY)}${events.toLocaleString()}${RESET}`, _COL_EVENTS);
355
+ return [_M, nameStr, " ", _renderBar(fraction), " ", dataStr, " ", tokStr, " ", shareStr, " ", evStr].join("");
356
+ }
357
+ function _renderKpiSection(stats) {
358
+ const totals = stats.totals;
359
+ const colW = Math.floor((_CONTENT_W - _M.length * 2) / 3);
360
+ function card(label, value, delta, spark2) {
361
+ return [
362
+ padR(`${fg(C.TEXT_MUTED[0], C.TEXT_MUTED[1], C.TEXT_MUTED[2])}${label}${RESET}`, colW),
363
+ padR(`${fg(C.TEXT_BRIGHT[0], C.TEXT_BRIGHT[1], C.TEXT_BRIGHT[2])}${value}${RESET}${delta}`, colW),
364
+ spark2 !== null ? padR(spark2, colW) : padR("", colW)
365
+ ];
366
+ }
367
+ const spark = totals.sparklines;
368
+ const c1 = card(
369
+ "events",
370
+ `${totals.events.toLocaleString()}`,
371
+ _fmtDelta(totals.events_delta ?? null),
372
+ spark ? _renderSparkline(spark.events) : null
373
+ );
374
+ const c2 = card(
375
+ "data saved",
376
+ _fmtBytes(totals.bytes),
377
+ _fmtDelta(totals.bytes_delta ?? null),
378
+ spark ? _renderSparkline(spark.bytes) : null
379
+ );
380
+ const c3 = card(
381
+ "tokens saved",
382
+ _fmtTokens(totals.tokens),
383
+ _fmtDelta(totals.tokens_delta ?? null),
384
+ spark ? _renderSparkline(spark.tokens) : null
385
+ );
386
+ const border = fg(C.TEXT_DIM[0], C.TEXT_DIM[1], C.TEXT_DIM[2]);
387
+ const frameBar = "\u2500".repeat(colW * 3 + 2);
388
+ function framed(content) {
389
+ return `${_M}${border}\u2502${RESET} ${content} ${border}\u2502${RESET}`;
390
+ }
391
+ const lines = [
392
+ "",
393
+ `${_M}${border}\u256D${frameBar}\u256E${RESET}`,
394
+ framed(c1[0] + c2[0] + c3[0]),
395
+ framed(c1[1] + c2[1] + c3[1])
396
+ ];
397
+ if (spark) {
398
+ lines.push(framed(c1[2] + c2[2] + c3[2]));
399
+ }
400
+ lines.push(`${_M}${border}\u2570${frameBar}\u256F${RESET}`);
401
+ return lines;
402
+ }
403
+ var _KIND_GROUPS = [
404
+ {
405
+ label: "Read savings",
406
+ members: /* @__PURE__ */ new Set([
407
+ "read_replacement",
408
+ "section_replacement",
409
+ "symbol_read",
410
+ "section_read",
411
+ "stub_view",
412
+ "outline",
413
+ "exports",
414
+ "imports",
415
+ "changed_lookup",
416
+ "dep_docs",
417
+ // Every other SOURCE_READ kind in stats.ts's KIND_TO_SOURCE: the surgical-read commands over documents, structured data and session/PR state. They were registered and produced but grouped nowhere, so `stats --full` printed the whole family under 'Other', away from the read-savings siblings they are measured against. image_meta/image_text sit here rather than under 'Images' because stats.ts files them as SOURCE_READ: they save read bytes, they do not shrink an image.
418
+ "brief_view",
419
+ "conflicts",
420
+ "coverage_report_gaps",
421
+ "csv_query",
422
+ "csv_profile",
423
+ "compact_doc",
424
+ "docx_outline",
425
+ "docx_tables",
426
+ "docx_text",
427
+ "gdrive_sections",
428
+ "image_meta",
429
+ "image_text",
430
+ "json_query",
431
+ "json_outline",
432
+ "note_read",
433
+ "note_list",
434
+ "openapi_op",
435
+ "openapi_outline",
436
+ "pdf_extract",
437
+ "pdf_locate",
438
+ "pdf_outline",
439
+ "pdf_meta",
440
+ "pptx_outline",
441
+ "pptx_slide",
442
+ "pptx_notes",
443
+ "pptx_text",
444
+ "pr_slice",
445
+ "session_outline",
446
+ "session_slice",
447
+ "sqlite_query",
448
+ "sqlite_schema",
449
+ "sqlite_tables",
450
+ "transcript",
451
+ "transcript_outline",
452
+ "video_chapters",
453
+ "xlsx_sheets",
454
+ "xlsx_head",
455
+ "xlsx_range",
456
+ "xlsx_query",
457
+ "xlsx_columns",
458
+ "xml_query",
459
+ "xml_outline",
460
+ "html_query",
461
+ "html_outline",
462
+ "yaml_query",
463
+ "yaml_outline",
464
+ "zip_list",
465
+ "zip_read"
466
+ ])
467
+ },
468
+ { label: "Lookups", members: /* @__PURE__ */ new Set(["symbol_lookup", "semantic_search", "map_lookup"]) },
469
+ {
470
+ label: "Images",
471
+ members: /* @__PURE__ */ new Set([
472
+ "image_shrink",
473
+ "gdrive_image",
474
+ "webfetch_image",
475
+ "image_shrink_skipped",
476
+ "image_shrink_cache_hit",
477
+ "image_ocr"
478
+ ])
479
+ },
480
+ {
481
+ label: "Hints",
482
+ members: /* @__PURE__ */ new Set([
483
+ "session_hint",
484
+ "session_hint_overhead",
485
+ "session_hint_suppressed",
486
+ "read_count_deny",
487
+ "read_served_deny",
488
+ "subagent_markdown_first_read_deny",
489
+ "grep_dedup_hint",
490
+ "glob_dedup_hint",
491
+ "diff_hint",
492
+ "predictive_prefetch_hit",
493
+ "structured_file_hint",
494
+ "write_rewrite_hint",
495
+ "websearch_dedup_hint",
496
+ "large_file_hint_followed",
497
+ "large_file_hint_ignored",
498
+ "evidence_cache_hit"
499
+ ])
500
+ },
501
+ // Empty for the same reason as MCP below: every live Bash kind arrives through _kindGroupLabel's `bash_compress:` prefix branch, not through a literal name. The fifteen literal names this set used to carry (bash_output_cached, bash_dedup_hint, env_probe_cache_hit and the rest) came over with the Python port and were never recorded or registered anywhere in this tree, so they grouped rows that could not exist.
502
+ { label: "Bash", members: /* @__PURE__ */ new Set() },
503
+ {
504
+ label: "Web",
505
+ members: /* @__PURE__ */ new Set([
506
+ "web_fetch",
507
+ "injection_detected"
508
+ ])
509
+ },
510
+ // Membership comes from _kindGroupLabel's `mcp:` prefix branch, not from this set, which is why
511
+ // it is empty. The entry still has to exist: _renderByKindSection iterates _KIND_GROUPS' labels
512
+ // (plus 'Other') to decide what to print, so a label _kindGroupLabel returns but that is missing
513
+ // here does not fall back to 'Other' -- its rows disappear from the table entirely.
514
+ { label: "MCP", members: /* @__PURE__ */ new Set() },
515
+ {
516
+ label: "Compact / Skills",
517
+ members: /* @__PURE__ */ new Set([
518
+ "skill_load",
519
+ "skill_oversized_first_load",
520
+ "skill_compact_inlined",
521
+ "skill_heading_tree_inlined"
522
+ ])
523
+ },
524
+ // SOURCE_CONTENT: real rewrites of tool output that remove real bytes (agent report compaction, Grep fold, browser tab dedup, bash/content compression and the handoff pair). The by-source table has shown a 'content' row since the source was added, but the by-kind table had no member set for it, so every one of these kinds printed under 'Other'. The taskoutput: prefix branch in _kindGroupLabel routes here too.
525
+ {
526
+ label: "Content",
527
+ members: /* @__PURE__ */ new Set([
528
+ "content_compress",
529
+ "content_retrieve",
530
+ "agent_report_compact",
531
+ "agent_report_compact_declined",
532
+ "browser_tab_dedup",
533
+ "grep:fold",
534
+ "read:served_elide",
535
+ "read:body_fold",
536
+ "read:markdown_outline",
537
+ "read:source_skeleton",
538
+ "handoff_create",
539
+ "handoff_resolve",
540
+ "plan_echo_collapse"
541
+ ])
542
+ }
543
+ ];
544
+ function _kindGroupLabel(kind) {
545
+ if (kind.startsWith("bash_compress:") || kind.startsWith("bashoutput:")) {
546
+ return "Bash";
547
+ }
548
+ if (kind.startsWith("webfetch:") || kind.startsWith("gdrive:")) {
549
+ return "Web";
550
+ }
551
+ if (kind.startsWith("mcp:")) {
552
+ return "MCP";
553
+ }
554
+ if (kind.startsWith("skill_body:") || kind.startsWith("skill_compact:")) {
555
+ return "Compact / Skills";
556
+ }
557
+ if (kind.startsWith("taskoutput:")) {
558
+ return "Content";
559
+ }
560
+ for (const group of _KIND_GROUPS) {
561
+ if (group.members.has(kind)) {
562
+ return group.label;
563
+ }
564
+ }
565
+ return "Other";
566
+ }
567
+ function _groupSeparator(label) {
568
+ return `${_M} ${fg(...C.TEXT_DIM)}${label}${RESET}`;
569
+ }
570
+ function _renderByKindSection(stats) {
571
+ if (stats.by_kind.length === 0) {
572
+ return [];
573
+ }
574
+ const lines = [..._sectionHeader("By kind"), _tableHeader("name")];
575
+ const { grossBytes, shareBytesDenom, shareTokensDenom } = _computeShareDenominators(stats.by_kind);
576
+ const kindNames = new Set(stats.by_kind.map((k) => k.kind));
577
+ const bytesModeKinds = stats.by_kind.filter((k) => k.bytes_mode_only).map((k) => k.kind);
578
+ function share(k) {
579
+ if (k.bytes_mode_only) {
580
+ return k.bytes / shareBytesDenom;
581
+ }
582
+ return _absShare(k.bytes, k.tokens, shareBytesDenom, shareTokensDenom);
583
+ }
584
+ const byGroup = /* @__PURE__ */ new Map();
585
+ for (const k of stats.by_kind) {
586
+ const grp = _kindGroupLabel(k.kind);
587
+ if (!byGroup.has(grp)) {
588
+ byGroup.set(grp, []);
589
+ }
590
+ byGroup.get(grp).push(k);
591
+ }
592
+ for (const grpKinds of byGroup.values()) {
593
+ grpKinds.sort((a, b) => share(b) - share(a));
594
+ }
595
+ const groupLabels = [..._KIND_GROUPS.map((g) => g.label), "Other"];
596
+ let firstGroup = true;
597
+ for (const label of groupLabels) {
598
+ const groupKinds = byGroup.get(label);
599
+ if (!groupKinds || groupKinds.length === 0) {
600
+ continue;
601
+ }
602
+ if (!firstGroup) {
603
+ lines.push("");
604
+ }
605
+ firstGroup = false;
606
+ lines.push(_groupSeparator(label));
607
+ for (const k of groupKinds) {
608
+ const s = share(k);
609
+ lines.push(
610
+ _tableRow({
611
+ name: k.kind,
612
+ fraction: _barFraction(k.bytes, grossBytes),
613
+ bytes: k.bytes,
614
+ tokens: k.tokens,
615
+ events: k.events,
616
+ share: s,
617
+ bytesModeOnly: k.bytes_mode_only ?? false
618
+ })
619
+ );
620
+ }
621
+ }
622
+ if (bytesModeKinds.length > 0) {
623
+ const names = bytesModeKinds.join(", ");
624
+ lines.push(`${_M}${fg(...C.TEXT_DIM)}i ${names} ${_STATS_MESSAGES.bytesModeOnlyNote}${RESET}`);
625
+ }
626
+ if (kindNames.has("session_hint") && kindNames.has("session_hint_overhead")) {
627
+ lines.push(`${_M}${fg(...C.TEXT_DIM)}i ${_STATS_MESSAGES.sessionHintSplitNote}${RESET}`);
628
+ }
629
+ return lines;
630
+ }
631
+ var _SOURCE_COLORS = {
632
+ image: C.PURPLE,
633
+ hint: C.BLUE,
634
+ read: C.GREEN4,
635
+ compact: C.TEAL,
636
+ bash: C.ORANGE,
637
+ web: C.YELLOW,
638
+ other: C.TEXT_MUTED
639
+ };
640
+ function _sourceColor(source) {
641
+ const color = _SOURCE_COLORS[source];
642
+ return color || C.TEXT_MUTED;
643
+ }
644
+ function _renderBySourceSection(stats) {
645
+ if (!stats.by_source || stats.by_source.length === 0) {
646
+ return [];
647
+ }
648
+ const lines = [..._sectionHeader("By source"), _tableHeader("source")];
649
+ const { grossBytes, shareBytesDenom, shareTokensDenom } = _computeShareDenominators(stats.by_source);
650
+ function share(s) {
651
+ return _absShare(s.bytes, s.tokens, shareBytesDenom, shareTokensDenom);
652
+ }
653
+ for (const s of [...stats.by_source].sort((a, b) => share(b) - share(a))) {
654
+ const s_val = share(s);
655
+ const color = _sourceColor(s.source);
656
+ lines.push(
657
+ _tableRow({
658
+ name: s.source,
659
+ fraction: _barFraction(s.bytes, grossBytes),
660
+ bytes: s.bytes,
661
+ tokens: s.tokens,
662
+ events: s.events,
663
+ share: s_val,
664
+ namePrefix: `${fg(...color)}\u25CF${RESET} `,
665
+ nameColor: C.TEXT_PRIMARY
666
+ })
667
+ );
668
+ }
669
+ return lines;
670
+ }
671
+ function _renderByCommandSection(stats) {
672
+ if (!stats.by_command || stats.by_command.length === 0) {
673
+ return [];
674
+ }
675
+ const lines = [..._sectionHeader("By command"), _tableHeader("command")];
676
+ const { grossBytes, shareBytesDenom, shareTokensDenom } = _computeShareDenominators(stats.by_command);
677
+ function share(c) {
678
+ return _absShare(c.bytes, c.tokens, shareBytesDenom, shareTokensDenom);
679
+ }
680
+ for (const c of [...stats.by_command].sort((a, b) => share(b) - share(a))) {
681
+ const s_val = share(c);
682
+ lines.push(
683
+ _tableRow({
684
+ name: c.command,
685
+ fraction: _barFraction(c.bytes, grossBytes),
686
+ bytes: c.bytes,
687
+ tokens: c.tokens,
688
+ events: c.events,
689
+ share: s_val,
690
+ nameColor: C.TEXT_PRIMARY
691
+ })
692
+ );
693
+ }
694
+ return lines;
695
+ }
696
+ function _renderByHarnessSection(stats) {
697
+ if (!stats.by_harness || stats.by_harness.length < 2) {
698
+ return [];
699
+ }
700
+ const lines = [..._sectionHeader("By harness"), _tableHeader("harness")];
701
+ const { grossBytes, shareBytesDenom, shareTokensDenom } = _computeShareDenominators(stats.by_harness);
702
+ function share(h) {
703
+ return _absShare(h.bytes, h.tokens, shareBytesDenom, shareTokensDenom);
704
+ }
705
+ for (const h of [...stats.by_harness].sort((a, b) => share(b) - share(a))) {
706
+ lines.push(
707
+ _tableRow({
708
+ name: h.harness,
709
+ fraction: _barFraction(h.bytes, grossBytes),
710
+ bytes: h.bytes,
711
+ tokens: h.tokens,
712
+ events: h.events,
713
+ share: share(h),
714
+ nameColor: C.TEXT_PRIMARY
715
+ })
716
+ );
717
+ }
718
+ return lines;
719
+ }
720
+ function _renderByDaySection(stats) {
721
+ if (stats.by_day.length === 0) {
722
+ return [];
723
+ }
724
+ const lines = [..._sectionHeader("By day"), _tableHeader("date")];
725
+ function share(d) {
726
+ return _tokenOrByteShare(d.tokens, d.bytes, stats.totals.tokens, stats.totals.bytes);
727
+ }
728
+ for (const d of [...stats.by_day].sort((a, b) => b.date < a.date ? -1 : b.date > a.date ? 1 : 0)) {
729
+ const s = share(d);
730
+ lines.push(
731
+ _tableRow({
732
+ name: d.date,
733
+ fraction: s,
734
+ bytes: d.bytes,
735
+ tokens: d.tokens,
736
+ events: d.events,
737
+ share: s
738
+ })
739
+ );
740
+ }
741
+ return lines;
742
+ }
743
+ var _PROJECT_COLORS = [C.PURPLE, C.TEAL, C.BLUE, C.GREEN4, C.TEXT_MUTED];
744
+ function _hashColor(hashStr) {
745
+ let n = 0;
746
+ for (const c of hashStr) {
747
+ n += c.charCodeAt(0);
748
+ }
749
+ return _PROJECT_COLORS[n % _PROJECT_COLORS.length] ?? C.TEXT_MUTED;
750
+ }
751
+ function _renderByProjectSection(stats) {
752
+ if (stats.by_project.length === 0) {
753
+ return [];
754
+ }
755
+ const lines = [..._sectionHeader(`By project (top ${stats.by_project.length})`), _tableHeader("project")];
756
+ function share(p) {
757
+ return _tokenOrByteShare(p.tokens, p.bytes, stats.totals.tokens, stats.totals.bytes);
758
+ }
759
+ for (const p of [...stats.by_project].sort((a, b) => share(b) - share(a))) {
760
+ const s = share(p);
761
+ const color = _hashColor(p.hash);
762
+ lines.push(
763
+ _tableRow({
764
+ name: p.project,
765
+ fraction: s,
766
+ bytes: p.bytes,
767
+ tokens: p.tokens,
768
+ events: p.events,
769
+ share: s,
770
+ namePrefix: `${fg(...color)}\u25CF${RESET} `,
771
+ nameColor: C.TEXT_PRIMARY
772
+ })
773
+ );
774
+ lines.push(`${_M} ${fg(...C.TEXT_DIM)}\u2514\u2500 ${p.hash} ${displaySafeText(stripAnsi(p.path))}${RESET}`);
775
+ }
776
+ return lines;
777
+ }
778
+ function _renderInsightsSection(stats) {
779
+ const lines = [..._sectionHeader("Insights")];
780
+ const bullet = `${fg(...C.GREEN3)}\u25B8${RESET}`;
781
+ function dim(s) {
782
+ return `${fg(...C.TEXT_MUTED)}${s}${RESET}`;
783
+ }
784
+ const savingKinds = stats.by_kind.filter((k) => k.bytes > 0);
785
+ const topKind = savingKinds.reduce((max, k) => k.bytes > (max?.bytes || -Infinity) ? k : max, savingKinds[0]);
786
+ if (topKind) {
787
+ const share = stats.totals.bytes > 0 ? topKind.bytes / stats.totals.bytes : 0;
788
+ lines.push(
789
+ `${_M}${bullet} ${dim(_STATS_MESSAGES.insights.biggestSaver)}${fg(...C.TEXT_PRIMARY)}${topKind.kind}${RESET}${dim(" \u2014 ")}${fg(...C.GREEN5)}${_fmtPct(share)}${RESET}${dim(` of saved data across ${topKind.events.toLocaleString()} events`)}`
790
+ );
791
+ }
792
+ const topDay = stats.by_day.reduce((max, d) => d.events > (max?.events || -Infinity) ? d : max, stats.by_day[0]);
793
+ if (topDay) {
794
+ lines.push(
795
+ `${_M}${bullet} ${dim(_STATS_MESSAGES.insights.mostActive)}${fg(...C.TEXT_PRIMARY)}${topDay.date}${RESET}${dim(" \u2014 ")}${topDay.events.toLocaleString()} events, ${_fmtBytes(topDay.bytes)}${dim(" saved")}`
796
+ );
797
+ }
798
+ const tokenKinds = stats.by_kind.filter((k) => !k.bytes_mode_only && k.tokens > 0);
799
+ const topToken = tokenKinds.reduce((max, k) => k.tokens > (max?.tokens || -Infinity) ? k : max, tokenKinds[0]);
800
+ if (topToken) {
801
+ lines.push(
802
+ `${_M}${bullet} ${dim(_STATS_MESSAGES.insights.tokenLeader)}${fg(...C.TEXT_PRIMARY)}${topToken.kind}${RESET}${dim(" \u2014 ")}${_fmtTokens(topToken.tokens)}${dim(` saved in ${topToken.events.toLocaleString()} events`)}`
803
+ );
804
+ }
805
+ if ((stats.by_command?.length ?? 0) === 0) {
806
+ const hintSource = stats.by_source?.find((s) => s.source === "hint");
807
+ if (hintSource && hintSource.events > 0) {
808
+ lines.push(
809
+ `${_M}${fg(...C.YELLOW)}\u25B8${RESET} ${dim("0 direct commands ")}${fg(...C.TEXT_PRIMARY)}${hintSource.events.toLocaleString()}${RESET}${dim(" hint(s) fired but not acted on \u2014 run symbol/read/section/semantic/outline/skeleton directly to capture these savings")}`
810
+ );
811
+ }
812
+ }
813
+ return lines;
814
+ }
815
+ function _renderHeader(stats) {
816
+ let line = `${_M}${fg(...C.TEXT_BRIGHT)}token-goat${RESET}`;
817
+ if (stats.version) {
818
+ line += ` ${fg(...C.TEXT_MUTED)}v${stats.version}${RESET}`;
819
+ }
820
+ if (stats.window_label) {
821
+ line += ` ${fg(...C.TEXT_DIM)}\xB7 ${stats.window_label}${RESET}`;
822
+ }
823
+ return [line];
824
+ }
825
+ function _renderShortHint() {
826
+ return [
827
+ "",
828
+ `${_M}${fg(...C.TEXT_MUTED)}Run 'token-goat stats --full' for the full breakdown (by source, by command, by day).${RESET}`
829
+ ];
830
+ }
831
+ function renderStats(stats, opts) {
832
+ if (opts?.short) {
833
+ const sections2 = [_renderHeader(stats), _renderKpiSection(stats), _renderShortHint(), [""]];
834
+ return sections2.flatMap((s) => s).join("\n");
835
+ }
836
+ const sections = [
837
+ _renderHeader(stats),
838
+ _renderKpiSection(stats),
839
+ _renderByKindSection(stats),
840
+ _renderBySourceSection(stats),
841
+ _renderByCommandSection(stats),
842
+ _renderByHarnessSection(stats),
843
+ _renderByDaySection(stats),
844
+ _renderByProjectSection(stats),
845
+ _renderInsightsSection(stats),
846
+ [""]
847
+ ];
848
+ return sections.flatMap((s) => s).join("\n");
849
+ }
850
+
851
+ // src/stats.ts
852
+ var HARNESS_UNRECORDED = "unrecorded (pre-2.8.1)";
853
+ var PRICING_VERSION_UNRECORDED = "unrecorded (pre-tg_version column)";
854
+ function hasMixedPricingEras(summary) {
855
+ return Object.keys(summary.by_pricing_version).length > 1;
856
+ }
857
+ var SOURCE_IMAGE = "image";
858
+ var SOURCE_HINT = "hint";
859
+ var SOURCE_READ = "read";
860
+ var SOURCE_BASH = "bash";
861
+ var SOURCE_WEB = "web";
862
+ var SOURCE_MCP = "mcp";
863
+ var SOURCE_SKILL = "skill";
864
+ var SOURCE_CONTENT = "content";
865
+ var SOURCE_OTHER = "other";
866
+ var _BYTES_MODE_ONLY_KINDS = /* @__PURE__ */ new Set(["webfetch_image", "gdrive_image"]);
867
+ var COUNT_ONLY_KINDS = /* @__PURE__ */ new Set(["secret_redacted"]);
868
+ function savedTokensFromBytes(bytes) {
869
+ return Math.round(Math.max(0, bytes) / 4);
870
+ }
871
+ var KIND_TO_SOURCE = {
872
+ image_shrink: SOURCE_IMAGE,
873
+ image_shrink_cache_hit: SOURCE_IMAGE,
874
+ image_shrink_skipped: SOURCE_IMAGE,
875
+ image_ocr: SOURCE_IMAGE,
876
+ webfetch_image: SOURCE_IMAGE,
877
+ gdrive_image: SOURCE_IMAGE,
878
+ session_hint: SOURCE_HINT,
879
+ session_hint_suppressed: SOURCE_HINT,
880
+ diff_hint: SOURCE_HINT,
881
+ evidence_cache_hit: SOURCE_HINT,
882
+ structured_file_hint: SOURCE_HINT,
883
+ predictive_prefetch_hit: SOURCE_HINT,
884
+ grep_dedup_hint: SOURCE_HINT,
885
+ glob_dedup_hint: SOURCE_HINT,
886
+ write_rewrite_hint: SOURCE_HINT,
887
+ websearch_dedup_hint: SOURCE_HINT,
888
+ large_file_hint_followed: SOURCE_HINT,
889
+ large_file_hint_ignored: SOURCE_HINT,
890
+ read_count_deny: SOURCE_HINT,
891
+ read_served_deny: SOURCE_HINT,
892
+ // hooks_read.ts's subagent first-read markdown deny (hints.subagent_markdown_first_read_deny, off by default). Always recorded at 0 bytes / 0 tokens: no first-read deny of this shape exists in the transcript corpus, so its abandoned/substituted/shell-read/retried rates are unknown and can only be borrowed from the re-read heading-tree census. Booking withheld bytes against borrowed rates would claim a saving this path cannot back up. The kind exists to make the intervention countable in session-audit, not to claim a win.
893
+ subagent_markdown_first_read_deny: SOURCE_HINT,
894
+ read_replacement: SOURCE_READ,
895
+ section_replacement: SOURCE_READ,
896
+ symbol_read: SOURCE_READ,
897
+ section_read: SOURCE_READ,
898
+ stub_view: SOURCE_READ,
899
+ symbol_lookup: SOURCE_READ,
900
+ semantic_search: SOURCE_READ,
901
+ map_lookup: SOURCE_READ,
902
+ changed_lookup: SOURCE_READ,
903
+ outline: SOURCE_READ,
904
+ exports: SOURCE_READ,
905
+ imports: SOURCE_READ,
906
+ dep_docs: SOURCE_READ,
907
+ csv_query: SOURCE_READ,
908
+ csv_profile: SOURCE_READ,
909
+ pdf_extract: SOURCE_READ,
910
+ pdf_locate: SOURCE_READ,
911
+ pdf_outline: SOURCE_READ,
912
+ pdf_meta: SOURCE_READ,
913
+ xlsx_sheets: SOURCE_READ,
914
+ xlsx_head: SOURCE_READ,
915
+ xlsx_range: SOURCE_READ,
916
+ xlsx_query: SOURCE_READ,
917
+ xlsx_columns: SOURCE_READ,
918
+ pptx_outline: SOURCE_READ,
919
+ pptx_slide: SOURCE_READ,
920
+ pptx_notes: SOURCE_READ,
921
+ pptx_text: SOURCE_READ,
922
+ docx_outline: SOURCE_READ,
923
+ docx_tables: SOURCE_READ,
924
+ docx_text: SOURCE_READ,
925
+ transcript_outline: SOURCE_READ,
926
+ transcript: SOURCE_READ,
927
+ video_chapters: SOURCE_READ,
928
+ image_meta: SOURCE_READ,
929
+ image_text: SOURCE_READ,
930
+ coverage_report_gaps: SOURCE_READ,
931
+ json_query: SOURCE_READ,
932
+ json_outline: SOURCE_READ,
933
+ yaml_query: SOURCE_READ,
934
+ yaml_outline: SOURCE_READ,
935
+ xml_query: SOURCE_READ,
936
+ xml_outline: SOURCE_READ,
937
+ html_query: SOURCE_READ,
938
+ html_outline: SOURCE_READ,
939
+ openapi_op: SOURCE_READ,
940
+ openapi_outline: SOURCE_READ,
941
+ zip_list: SOURCE_READ,
942
+ zip_read: SOURCE_READ,
943
+ sqlite_query: SOURCE_READ,
944
+ sqlite_schema: SOURCE_READ,
945
+ sqlite_tables: SOURCE_READ,
946
+ conflicts: SOURCE_READ,
947
+ brief_view: SOURCE_READ,
948
+ session_outline: SOURCE_READ,
949
+ session_slice: SOURCE_READ,
950
+ gdrive_sections: SOURCE_READ,
951
+ pr_slice: SOURCE_READ,
952
+ compact_doc: SOURCE_READ,
953
+ note_read: SOURCE_READ,
954
+ note_list: SOURCE_READ,
955
+ // note-add is a write (like insert-section/replace, which record no stat at all -- neither
956
+ // has a "full source it replaces" savings concept). It still gets an event-only entry here
957
+ // (no bytesSaved/tokensSaved argument, same as skill_load) purely so `token-goat note-add`
958
+ // usage is visible in `token-goat stats --full` at all -- SOURCE_OTHER, not SOURCE_READ,
959
+ // since it is not a token-savings substitute for a read.
960
+ note_write: SOURCE_OTHER,
961
+ web_fetch: SOURCE_WEB,
962
+ injection_detected: SOURCE_WEB,
963
+ skill_load: SOURCE_SKILL,
964
+ skill_oversized_first_load: SOURCE_SKILL,
965
+ // Cold first load of an oversized skill where preSkillHandler inlined the compact slice in its reply instead of pointing at `skill-body --compact`. Unlike its skill_oversized_first_load sibling (event-only, 0 bytes -- the pointer deny saves nothing by itself, the follow-up command does) this one records real savings: the full body never landed, the slice did, so bytesSaved is body minus slice.
966
+ skill_compact_inlined: SOURCE_SKILL,
967
+ // Cold first load of an oversized skill with no compact marker at all, where preSkillHandler inlined a heading tree in its reply instead of letting the whole body fall through. Same shape as skill_compact_inlined: real savings, bytesSaved is body minus the rendered tree.
968
+ skill_heading_tree_inlined: SOURCE_SKILL,
969
+ secret_redacted: SOURCE_OTHER,
970
+ // Fail-soft diagnostic counters from hooks_edit.ts: they record that a side task threw, never a byte saving, so "other" is the right home. Listed explicitly rather than left to kindToSource()'s fallback so the registration guard can tell a deliberate placement from an unregistered kind.
971
+ dirty_queue_append_failed: SOURCE_OTHER,
972
+ worker_healthcheck_failed: SOURCE_OTHER,
973
+ known_root_record_failed: SOURCE_OTHER,
974
+ // Measurement of what a compaction produced (hooks_compact.ts postCompactHandler): summary size and how many manifest paths survived into it. SOURCE_OTHER and always recorded at (0, 0) -- the summary was written whether or not token-goat was watching, so there is no counterfactual in which those bytes were saved. Filing it anywhere with a savings total would credit token-goat for the whole summary, which is the accounting mistake this registry exists to prevent.
975
+ compact_summary: SOURCE_OTHER,
976
+ // Envelope compaction of an oversized subagent report (hooks_agent_spawn.ts). SOURCE_CONTENT, not SOURCE_HINT: the handler's sibling session_hint entry is advisory (it only appends a recall pointer and genuinely saves nothing), whereas this kind records a real rewrite with real bytes removed, so filing it under the advisory bucket would understate the compaction and repeat the zero-savings desync this registry keeps getting bitten by.
977
+ agent_report_compact: SOURCE_CONTENT,
978
+ // Decline counterpart to agent_report_compact: the fence-collapse net-benefit gate ran and found at least one over-long fence, but declined to rewrite because net savings did not clear the notice cost. Always recorded at (0, 0) -- see the recordStat call site -- so it never contributes to any savings total; it exists purely to make gate hit-rate and near-misses visible instead of the decline being invisible.
979
+ agent_report_compact_declined: SOURCE_CONTENT,
980
+ content_compress: SOURCE_CONTENT,
981
+ // Verbatim-repeat collapse of a browser tool's "Tab Context:" text block (hooks_browser_image.ts postBrowserImageHandler). SOURCE_CONTENT for the same reason as agent_report_compact above: it is a real rewrite with real bytes removed, not an advisory nudge. Deliberately not SOURCE_IMAGE -- it shares a handler with image_shrink but collapses text, and folding text bytes into the image ledger is the two-units-under-one-label mistake this file's image_shrink entry was just fixed for.
982
+ browser_tab_dedup: SOURCE_CONTENT,
983
+ // Collapse of the plan echo in an approved ExitPlanMode result (hooks_exitplanmode.ts). SOURCE_CONTENT for the same reason as agent_report_compact: real bytes removed from a tool result, not an advisory nudge. The handler shipped for releases emitting this rewrite and recording nothing at all, so the mechanism was invisible in `stats` and its net benefit could not be checked against the gate that admits it.
984
+ plan_echo_collapse: SOURCE_CONTENT,
985
+ // Lossless re-layout of Grep content-mode output (hooks_grep.ts foldGrepContentHandler). SOURCE_CONTENT, not SOURCE_HINT, for the same reason as agent_report_compact above: its sibling grep_dedup_hint is advisory and saves nothing directly, whereas this is a real rewrite with real bytes removed. Filing it under the advisory bucket would silently add non-hint savings to hint_stats.ts's savedBytes (which reads by_source[SOURCE_HINT] wholesale) and overstate the hint ledger's net benefit.
986
+ "grep:fold": SOURCE_CONTENT,
987
+ // Withholding of already-served stretches from a completed Read (hooks_read.ts
988
+ // elideAlreadyServedLines). SOURCE_CONTENT, not SOURCE_HINT, for the same reason as
989
+ // grep:fold above: its siblings read_count_deny and read_served_deny are decisions about
990
+ // whether a read happens at all, whereas this is a rewrite of a result that did happen,
991
+ // with real bytes removed from it. Filing it under the advisory bucket would add non-hint
992
+ // savings to hint_stats.ts's savedBytes, which reads by_source[SOURCE_HINT] wholesale.
993
+ "read:served_elide": SOURCE_CONTENT,
994
+ // Same bucket and same reasoning as read:served_elide directly above: a rewrite of a Read that did happen, with real bytes removed, not an advisory about whether to read at all.
995
+ "read:body_fold": SOURCE_CONTENT,
996
+ // Same bucket and same reasoning as read:body_fold directly above: a coarser sibling rewrite of a large untargeted markdown Read (hooks_read.ts foldMarkdownOutline) that replaces the body with a heading tree plus preamble, with real bytes removed, not an advisory about whether to read at all.
997
+ "read:markdown_outline": SOURCE_CONTENT,
998
+ // Same bucket and same reasoning as read:markdown_outline directly above, on source instead of prose: the structural-skeleton replacement of a large untargeted source Read (hooks_read.ts foldSourceSkeleton), with real bytes removed, not an advisory about whether to read at all.
999
+ "read:source_skeleton": SOURCE_CONTENT,
1000
+ content_retrieve: SOURCE_CONTENT,
1001
+ handoff_create: SOURCE_CONTENT,
1002
+ handoff_resolve: SOURCE_CONTENT
1003
+ };
1004
+ var KIND_PREFIX_TO_SOURCE = [
1005
+ ["bash_compress:", SOURCE_BASH],
1006
+ ["webfetch:", SOURCE_WEB],
1007
+ ["gdrive:", SOURCE_WEB],
1008
+ ["mcp:", SOURCE_MCP],
1009
+ ["skill_body:", SOURCE_SKILL],
1010
+ ["skill_compact:", SOURCE_SKILL],
1011
+ ["bashoutput:", SOURCE_BASH],
1012
+ ["taskoutput:", SOURCE_CONTENT]
1013
+ ];
1014
+ var COMMAND_KINDS = {
1015
+ symbol: /* @__PURE__ */ new Set(["symbol_lookup"]),
1016
+ read: /* @__PURE__ */ new Set(["read_replacement"]),
1017
+ section: /* @__PURE__ */ new Set(["section_replacement", "section_read"]),
1018
+ semantic: /* @__PURE__ */ new Set(["semantic_search"]),
1019
+ outline: /* @__PURE__ */ new Set(["outline"]),
1020
+ exports: /* @__PURE__ */ new Set(["exports"]),
1021
+ imports: /* @__PURE__ */ new Set(["imports"]),
1022
+ skeleton: /* @__PURE__ */ new Set(["stub_view"]),
1023
+ refs: /* @__PURE__ */ new Set(["symbol_read"]),
1024
+ map: /* @__PURE__ */ new Set(["map_lookup"]),
1025
+ changed: /* @__PURE__ */ new Set(["changed_lookup"]),
1026
+ "dep-docs": /* @__PURE__ */ new Set(["dep_docs"]),
1027
+ "csv-query": /* @__PURE__ */ new Set(["csv_query"]),
1028
+ "csv-profile": /* @__PURE__ */ new Set(["csv_profile"]),
1029
+ "pdf-extract": /* @__PURE__ */ new Set(["pdf_extract"]),
1030
+ "pdf-locate": /* @__PURE__ */ new Set(["pdf_locate"]),
1031
+ "pdf-outline": /* @__PURE__ */ new Set(["pdf_outline"]),
1032
+ "pdf-meta": /* @__PURE__ */ new Set(["pdf_meta"]),
1033
+ "xlsx-sheets": /* @__PURE__ */ new Set(["xlsx_sheets"]),
1034
+ "xlsx-head": /* @__PURE__ */ new Set(["xlsx_head"]),
1035
+ "xlsx-range": /* @__PURE__ */ new Set(["xlsx_range"]),
1036
+ "xlsx-query": /* @__PURE__ */ new Set(["xlsx_query"]),
1037
+ "xlsx-columns": /* @__PURE__ */ new Set(["xlsx_columns"]),
1038
+ "pptx-outline": /* @__PURE__ */ new Set(["pptx_outline"]),
1039
+ "pptx-slide": /* @__PURE__ */ new Set(["pptx_slide"]),
1040
+ "pptx-notes": /* @__PURE__ */ new Set(["pptx_notes"]),
1041
+ "pptx-text": /* @__PURE__ */ new Set(["pptx_text"]),
1042
+ "docx-outline": /* @__PURE__ */ new Set(["docx_outline"]),
1043
+ "docx-tables": /* @__PURE__ */ new Set(["docx_tables"]),
1044
+ "docx-text": /* @__PURE__ */ new Set(["docx_text"]),
1045
+ "transcript-outline": /* @__PURE__ */ new Set(["transcript_outline"]),
1046
+ transcript: /* @__PURE__ */ new Set(["transcript"]),
1047
+ "video-chapters": /* @__PURE__ */ new Set(["video_chapters"]),
1048
+ "image-meta": /* @__PURE__ */ new Set(["image_meta"]),
1049
+ "image-text": /* @__PURE__ */ new Set(["image_text"]),
1050
+ "coverage-report-gaps": /* @__PURE__ */ new Set(["coverage_report_gaps"]),
1051
+ "json-query": /* @__PURE__ */ new Set(["json_query"]),
1052
+ "json-outline": /* @__PURE__ */ new Set(["json_outline"]),
1053
+ "yaml-query": /* @__PURE__ */ new Set(["yaml_query"]),
1054
+ "yaml-outline": /* @__PURE__ */ new Set(["yaml_outline"]),
1055
+ "xml-query": /* @__PURE__ */ new Set(["xml_query"]),
1056
+ "xml-outline": /* @__PURE__ */ new Set(["xml_outline"]),
1057
+ "html-query": /* @__PURE__ */ new Set(["html_query"]),
1058
+ "html-outline": /* @__PURE__ */ new Set(["html_outline"]),
1059
+ "openapi-op": /* @__PURE__ */ new Set(["openapi_op"]),
1060
+ "openapi-outline": /* @__PURE__ */ new Set(["openapi_outline"]),
1061
+ "zip-list": /* @__PURE__ */ new Set(["zip_list"]),
1062
+ "zip-read": /* @__PURE__ */ new Set(["zip_read"]),
1063
+ "sqlite-query": /* @__PURE__ */ new Set(["sqlite_query"]),
1064
+ "sqlite-schema": /* @__PURE__ */ new Set(["sqlite_schema"]),
1065
+ "sqlite-tables": /* @__PURE__ */ new Set(["sqlite_tables"]),
1066
+ conflicts: /* @__PURE__ */ new Set(["conflicts"]),
1067
+ brief: /* @__PURE__ */ new Set(["brief_view"]),
1068
+ "session-outline": /* @__PURE__ */ new Set(["session_outline"]),
1069
+ "session-slice": /* @__PURE__ */ new Set(["session_slice"]),
1070
+ "gdrive-sections": /* @__PURE__ */ new Set(["gdrive_sections"]),
1071
+ "pr-slice": /* @__PURE__ */ new Set(["pr_slice"]),
1072
+ "compact-doc": /* @__PURE__ */ new Set(["compact_doc"]),
1073
+ "note-add": /* @__PURE__ */ new Set(["note_write"]),
1074
+ "note-get": /* @__PURE__ */ new Set(["note_read"]),
1075
+ "note-list": /* @__PURE__ */ new Set(["note_list"]),
1076
+ "compress-text": /* @__PURE__ */ new Set(["content_compress"]),
1077
+ retrieve: /* @__PURE__ */ new Set(["content_retrieve"]),
1078
+ "handoff-create": /* @__PURE__ */ new Set(["handoff_create"]),
1079
+ "handoff-resolve": /* @__PURE__ */ new Set(["handoff_resolve"]),
1080
+ npm: /* @__PURE__ */ new Set([
1081
+ "bash_compress:npm_install",
1082
+ "bash_compress:npm_ci",
1083
+ "bash_compress:npm_audit",
1084
+ "bash_compress:npm_ls",
1085
+ "bash_compress:npm_outdated",
1086
+ "bash_compress:npx"
1087
+ ])
1088
+ };
1089
+ var OVERHEAD_SUFFIX = "_overhead";
1090
+ function kindToSource(kind) {
1091
+ const src = KIND_TO_SOURCE[kind];
1092
+ if (src !== void 0) return src;
1093
+ if (kind.endsWith(OVERHEAD_SUFFIX)) {
1094
+ const base = kind.slice(0, -OVERHEAD_SUFFIX.length);
1095
+ const baseSrc = KIND_TO_SOURCE[base];
1096
+ if (baseSrc !== void 0) return baseSrc;
1097
+ }
1098
+ for (const [prefix, prefixSrc] of KIND_PREFIX_TO_SOURCE) {
1099
+ if (kind.startsWith(prefix)) return prefixSrc;
1100
+ }
1101
+ return SOURCE_OTHER;
1102
+ }
1103
+ function toLocalDateKey(d) {
1104
+ const year = d.getFullYear();
1105
+ const month = String(d.getMonth() + 1).padStart(2, "0");
1106
+ const day = String(d.getDate()).padStart(2, "0");
1107
+ return `${year}-${month}-${day}`;
1108
+ }
1109
+ function formatLocalTimestamp(d) {
1110
+ const hours = String(d.getHours()).padStart(2, "0");
1111
+ const minutes = String(d.getMinutes()).padStart(2, "0");
1112
+ const seconds = String(d.getSeconds()).padStart(2, "0");
1113
+ return `${toLocalDateKey(d)}T${hours}:${minutes}:${seconds}`;
1114
+ }
1115
+ function zeroBucket() {
1116
+ return { events: 0, bytes_saved: 0, tokens_saved: 0 };
1117
+ }
1118
+ function incBucket(bucket, bytesSaved, tokensSaved) {
1119
+ bucket.events += 1;
1120
+ bucket.bytes_saved += bytesSaved;
1121
+ bucket.tokens_saved += tokensSaved;
1122
+ }
1123
+ var GLOBAL_SCHEMA_SQL = `
1124
+ CREATE TABLE IF NOT EXISTS stats (
1125
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1126
+ ts INTEGER NOT NULL,
1127
+ kind TEXT NOT NULL,
1128
+ tokens_saved INTEGER NOT NULL DEFAULT 0,
1129
+ bytes_saved INTEGER NOT NULL DEFAULT 0,
1130
+ detail TEXT,
1131
+ harness TEXT,
1132
+ traceparent TEXT,
1133
+ tg_version TEXT
1134
+ );
1135
+ CREATE INDEX IF NOT EXISTS idx_stats_ts ON stats(ts);
1136
+ CREATE INDEX IF NOT EXISTS idx_stats_kind ON stats(kind);
1137
+ -- Day-granularity rollup of stats rows older than STATS_RETENTION_DAYS -- see
1138
+ -- rollupAndPruneStats's doc comment for why raw rows are pruned instead of kept forever, and
1139
+ -- summarize()'s rollup merge for how a --window-days report spanning pruned days still gets a
1140
+ -- correct total. Deliberately day+kind+harness+tg_version, not day+kind alone: those are exactly
1141
+ -- the dimensions summarize() breaks totals out by, and collapsing any of them here would make an
1142
+ -- old --window-days report under-report a breakdown a recent one still shows in full.
1143
+ CREATE TABLE IF NOT EXISTS stats_daily_rollup (
1144
+ day TEXT NOT NULL,
1145
+ kind TEXT NOT NULL,
1146
+ harness TEXT NOT NULL DEFAULT '',
1147
+ tg_version TEXT NOT NULL DEFAULT '',
1148
+ events INTEGER NOT NULL DEFAULT 0,
1149
+ bytes_saved INTEGER NOT NULL DEFAULT 0,
1150
+ tokens_saved INTEGER NOT NULL DEFAULT 0,
1151
+ PRIMARY KEY (day, kind, harness, tg_version)
1152
+ );
1153
+ CREATE INDEX IF NOT EXISTS idx_stats_daily_rollup_day ON stats_daily_rollup(day);
1154
+ -- Single-row (id=1, same pattern as embedding_provenance in db.ts) throttle so the rollup+prune
1155
+ -- pass -- an aggregate scan over the whole stats table -- runs at most once per
1156
+ -- STATS_ROLLUP_INTERVAL_MS regardless of how often recordStat() itself is called (many times a
1157
+ -- minute during active use).
1158
+ CREATE TABLE IF NOT EXISTS stats_maintenance (
1159
+ id INTEGER PRIMARY KEY CHECK (id = 1),
1160
+ last_rollup_ts INTEGER NOT NULL DEFAULT 0
1161
+ );
1162
+ CREATE TABLE IF NOT EXISTS unmapped_tools (
1163
+ harness TEXT NOT NULL,
1164
+ tool_name TEXT NOT NULL,
1165
+ event_name TEXT NOT NULL,
1166
+ near_miss TEXT,
1167
+ first_seen INTEGER NOT NULL,
1168
+ last_seen INTEGER NOT NULL,
1169
+ hits INTEGER NOT NULL DEFAULT 0,
1170
+ PRIMARY KEY (harness, tool_name, event_name)
1171
+ );
1172
+ `;
1173
+ var _globalSchemaApplied = /* @__PURE__ */ new Set();
1174
+ registerReset(() => _globalSchemaApplied.clear());
1175
+ function migrateGlobalSchema(db) {
1176
+ try {
1177
+ db.exec("ALTER TABLE stats ADD COLUMN harness TEXT");
1178
+ } catch (err) {
1179
+ if (!(err instanceof Error) || !/duplicate column/i.test(err.message)) throw err;
1180
+ }
1181
+ try {
1182
+ db.exec("ALTER TABLE stats ADD COLUMN traceparent TEXT");
1183
+ } catch (err) {
1184
+ if (!(err instanceof Error) || !/duplicate column/i.test(err.message)) throw err;
1185
+ }
1186
+ try {
1187
+ db.exec("ALTER TABLE stats ADD COLUMN tg_version TEXT");
1188
+ } catch (err) {
1189
+ if (!(err instanceof Error) || !/duplicate column/i.test(err.message)) throw err;
1190
+ }
1191
+ }
1192
+ var _harnessColumnByDb = /* @__PURE__ */ new WeakMap();
1193
+ function statsHasHarnessColumn(db) {
1194
+ const cached = _harnessColumnByDb.get(db);
1195
+ if (cached !== void 0) return cached;
1196
+ let present;
1197
+ try {
1198
+ present = db.prepare("PRAGMA table_info(stats)").all().some(
1199
+ (c) => c.name === "harness"
1200
+ );
1201
+ } catch {
1202
+ present = false;
1203
+ }
1204
+ _harnessColumnByDb.set(db, present);
1205
+ return present;
1206
+ }
1207
+ var _traceparentColumnByDb = /* @__PURE__ */ new WeakMap();
1208
+ function statsHasTraceparentColumn(db) {
1209
+ const cached = _traceparentColumnByDb.get(db);
1210
+ if (cached !== void 0) return cached;
1211
+ let present;
1212
+ try {
1213
+ present = db.prepare("PRAGMA table_info(stats)").all().some(
1214
+ (c) => c.name === "traceparent"
1215
+ );
1216
+ } catch {
1217
+ present = false;
1218
+ }
1219
+ _traceparentColumnByDb.set(db, present);
1220
+ return present;
1221
+ }
1222
+ var _versionColumnByDb = /* @__PURE__ */ new WeakMap();
1223
+ function statsHasVersionColumn(db) {
1224
+ const cached = _versionColumnByDb.get(db);
1225
+ if (cached !== void 0) return cached;
1226
+ let present;
1227
+ try {
1228
+ present = db.prepare("PRAGMA table_info(stats)").all().some(
1229
+ (c) => c.name === "tg_version"
1230
+ );
1231
+ } catch {
1232
+ present = false;
1233
+ }
1234
+ _versionColumnByDb.set(db, present);
1235
+ return present;
1236
+ }
1237
+ function getGlobalDb(homeDir) {
1238
+ const basePath = homeDir ? dataDirForHome(homeDir) : dataDir();
1239
+ const dbPath = path.join(basePath, "global.db");
1240
+ const db = getDb(dbPath);
1241
+ if (!_globalSchemaApplied.has(dbPath)) {
1242
+ db.exec(GLOBAL_SCHEMA_SQL);
1243
+ migrateGlobalSchema(db);
1244
+ _globalSchemaApplied.add(dbPath);
1245
+ }
1246
+ return db;
1247
+ }
1248
+ var STATS_RETENTION_DAYS = 180;
1249
+ var STATS_ROLLUP_INTERVAL_MS = 6 * 60 * 60 * 1e3;
1250
+ function rollupAndPruneStats(db, retentionDays = STATS_RETENTION_DAYS) {
1251
+ try {
1252
+ const cutoffTs = Math.floor(Date.now() / 1e3) - retentionDays * 86400;
1253
+ const run = db.transaction((cutoff) => {
1254
+ db.prepare(
1255
+ `INSERT INTO stats_daily_rollup (day, kind, harness, tg_version, events, bytes_saved, tokens_saved)
1256
+ SELECT strftime('%Y-%m-%d', ts, 'unixepoch', 'localtime') AS day,
1257
+ kind,
1258
+ COALESCE(harness, '') AS harness,
1259
+ COALESCE(tg_version, '') AS tg_version,
1260
+ COUNT(*), SUM(bytes_saved), SUM(tokens_saved)
1261
+ FROM stats
1262
+ WHERE ts < ?
1263
+ GROUP BY day, kind, harness, tg_version
1264
+ ON CONFLICT(day, kind, harness, tg_version) DO UPDATE SET
1265
+ events = events + excluded.events,
1266
+ bytes_saved = bytes_saved + excluded.bytes_saved,
1267
+ tokens_saved = tokens_saved + excluded.tokens_saved`
1268
+ ).run(cutoff);
1269
+ db.prepare(`DELETE FROM stats WHERE ts < ?`).run(cutoff);
1270
+ });
1271
+ run(cutoffTs);
1272
+ } catch {
1273
+ }
1274
+ }
1275
+ function maybeRunStatsMaintenance(db) {
1276
+ try {
1277
+ const now = Date.now();
1278
+ const row = db.prepare(`SELECT last_rollup_ts FROM stats_maintenance WHERE id = 1`).get();
1279
+ const last = row?.last_rollup_ts ?? 0;
1280
+ if (now - last < STATS_ROLLUP_INTERVAL_MS) return;
1281
+ db.prepare(
1282
+ `INSERT INTO stats_maintenance (id, last_rollup_ts) VALUES (1, ?)
1283
+ ON CONFLICT(id) DO UPDATE SET last_rollup_ts = excluded.last_rollup_ts`
1284
+ ).run(now);
1285
+ rollupAndPruneStats(db);
1286
+ } catch {
1287
+ }
1288
+ }
1289
+ function noStatsMessage(windowDays, homeDir) {
1290
+ if (windowDays <= 0) return "No stats recorded yet.";
1291
+ const db = getGlobalDb(homeDir);
1292
+ let total = db.prepare("SELECT COUNT(*) as c FROM stats").get().c;
1293
+ try {
1294
+ const rollupTable = db.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'stats_daily_rollup'`).get();
1295
+ if (rollupTable !== void 0) {
1296
+ const rolledUp = db.prepare("SELECT COALESCE(SUM(events), 0) as c FROM stats_daily_rollup").get().c;
1297
+ total += rolledUp;
1298
+ }
1299
+ } catch {
1300
+ }
1301
+ if (total === 0) return "No stats recorded yet.";
1302
+ return `No stats in the last ${countNoun(windowDays, "day")} (${total} recorded outside this window; use --window-days 0 for all time).`;
1303
+ }
1304
+ function recordStat(kind, bytesSaved = 0, tokensSaved = 0, _testDb, detail, traceparent) {
1305
+ try {
1306
+ const db = _testDb ?? getGlobalDb();
1307
+ const ts = Math.floor(Date.now() / 1e3);
1308
+ const tp = traceparent ?? process.env["TRACEPARENT"] ?? process.env["traceparent"] ?? null;
1309
+ const cols = ["ts", "kind", "bytes_saved", "tokens_saved", "detail"];
1310
+ const vals = [ts, kind, bytesSaved, tokensSaved, detail ?? null];
1311
+ if (statsHasHarnessColumn(db)) {
1312
+ cols.push("harness");
1313
+ vals.push(getHarnessName());
1314
+ }
1315
+ if (statsHasTraceparentColumn(db)) {
1316
+ cols.push("traceparent");
1317
+ vals.push(tp);
1318
+ }
1319
+ if (statsHasVersionColumn(db)) {
1320
+ cols.push("tg_version");
1321
+ vals.push(VERSION);
1322
+ }
1323
+ db.prepare(
1324
+ `INSERT INTO stats (${cols.join(", ")}) VALUES (${cols.map(() => "?").join(", ")})`
1325
+ ).run(...vals);
1326
+ maybeRunStatsMaintenance(db);
1327
+ } catch {
1328
+ }
1329
+ }
1330
+ var MAX_TOOL_NAME_CHARS = 200;
1331
+ function recordUnmappedTool(toolName, eventName, nearMiss, _testDb) {
1332
+ try {
1333
+ if (!toolName) return;
1334
+ const db = _testDb ?? getGlobalDb();
1335
+ const now = Math.floor(Date.now() / 1e3);
1336
+ db.prepare(
1337
+ `INSERT INTO unmapped_tools (harness, tool_name, event_name, near_miss, first_seen, last_seen, hits)
1338
+ VALUES (?, ?, ?, ?, ?, ?, 1)
1339
+ ON CONFLICT(harness, tool_name, event_name) DO UPDATE SET
1340
+ hits = hits + 1,
1341
+ last_seen = excluded.last_seen,
1342
+ near_miss = excluded.near_miss`
1343
+ ).run(getHarnessName(), toolName.slice(0, MAX_TOOL_NAME_CHARS), eventName, nearMiss, now, now);
1344
+ } catch {
1345
+ }
1346
+ }
1347
+ function readUnmappedTools(dbPath, homeDir) {
1348
+ try {
1349
+ const db = dbPath ? getDb(dbPath) : getGlobalDb(homeDir);
1350
+ return db.prepare(
1351
+ "SELECT harness, tool_name, event_name, near_miss, hits, last_seen FROM unmapped_tools ORDER BY hits DESC, tool_name ASC"
1352
+ ).all();
1353
+ } catch {
1354
+ return [];
1355
+ }
1356
+ }
1357
+ function summarize(windowDays = 30, testDb, homeDir) {
1358
+ const t0 = Date.now();
1359
+ const sinceTs = windowDays > 0 ? Math.floor((Date.now() - windowDays * 24 * 60 * 60 * 1e3) / 1e3) : null;
1360
+ const byKind = {};
1361
+ const byDay = {};
1362
+ const byHarness = {};
1363
+ const byPricingVersion = {};
1364
+ let totalEvents = 0;
1365
+ let totalBytes = 0;
1366
+ let totalTokens = 0;
1367
+ const db = testDb ?? getGlobalDb(homeDir);
1368
+ const hasHarness = statsHasHarnessColumn(db);
1369
+ const hasVersion = statsHasVersionColumn(db);
1370
+ const cols = [
1371
+ "ts",
1372
+ "kind",
1373
+ "bytes_saved",
1374
+ "tokens_saved",
1375
+ ...hasHarness ? ["harness"] : [],
1376
+ ...hasVersion ? ["tg_version"] : []
1377
+ ].join(", ");
1378
+ const query = sinceTs !== null ? `SELECT ${cols} FROM stats WHERE ts >= ? ORDER BY ts DESC` : `SELECT ${cols} FROM stats ORDER BY ts DESC`;
1379
+ const stmt = db.prepare(query);
1380
+ const rows = sinceTs !== null ? stmt.all(sinceTs) : stmt.all();
1381
+ const tsToDateCache = {};
1382
+ const counts = {};
1383
+ for (const row of rows) {
1384
+ const bytesSaved = row.bytes_saved ?? 0;
1385
+ const recorded = row.tokens_saved ?? 0;
1386
+ const kind = row.kind;
1387
+ const isCount = COUNT_ONLY_KINDS.has(kind);
1388
+ if (isCount) counts[kind] = (counts[kind] ?? 0) + recorded;
1389
+ const tokensSaved = isCount ? 0 : recorded;
1390
+ const tsRaw = row.ts;
1391
+ if (tsRaw === void 0) continue;
1392
+ const ts = tsRaw;
1393
+ totalEvents += 1;
1394
+ totalBytes += bytesSaved;
1395
+ totalTokens += tokensSaved;
1396
+ if (!byKind[kind]) {
1397
+ byKind[kind] = zeroBucket();
1398
+ }
1399
+ incBucket(byKind[kind], bytesSaved, tokensSaved);
1400
+ const dateKey = tsToDateCache[ts] || toLocalDateKey(new Date(ts * 1e3));
1401
+ tsToDateCache[ts] = dateKey;
1402
+ if (!byDay[dateKey]) {
1403
+ byDay[dateKey] = zeroBucket();
1404
+ }
1405
+ incBucket(byDay[dateKey], bytesSaved, tokensSaved);
1406
+ const harness = row.harness || HARNESS_UNRECORDED;
1407
+ if (!byHarness[harness]) {
1408
+ byHarness[harness] = zeroBucket();
1409
+ }
1410
+ incBucket(byHarness[harness], bytesSaved, tokensSaved);
1411
+ const pricingVersion = row.tg_version || PRICING_VERSION_UNRECORDED;
1412
+ if (!byPricingVersion[pricingVersion]) {
1413
+ byPricingVersion[pricingVersion] = zeroBucket();
1414
+ }
1415
+ incBucket(byPricingVersion[pricingVersion], bytesSaved, tokensSaved);
1416
+ }
1417
+ try {
1418
+ const rollupTable = db.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'stats_daily_rollup'`).get();
1419
+ if (rollupTable !== void 0) {
1420
+ const sinceDayKey = sinceTs !== null ? toLocalDateKey(new Date(sinceTs * 1e3)) : null;
1421
+ const rollupRows = sinceDayKey !== null ? db.prepare(`SELECT day, kind, harness, tg_version, events, bytes_saved, tokens_saved FROM stats_daily_rollup WHERE day >= ?`).all(sinceDayKey) : db.prepare(`SELECT day, kind, harness, tg_version, events, bytes_saved, tokens_saved FROM stats_daily_rollup`).all();
1422
+ const addBucket = (bucket, events, bytesSaved, tokensSaved) => {
1423
+ bucket.events += events;
1424
+ bucket.bytes_saved += bytesSaved;
1425
+ bucket.tokens_saved += tokensSaved;
1426
+ };
1427
+ for (const r of rollupRows) {
1428
+ const isCount = COUNT_ONLY_KINDS.has(r.kind);
1429
+ if (isCount) counts[r.kind] = (counts[r.kind] ?? 0) + r.tokens_saved;
1430
+ const tokensSaved = isCount ? 0 : r.tokens_saved;
1431
+ const bytesSaved = r.bytes_saved;
1432
+ totalEvents += r.events;
1433
+ totalBytes += bytesSaved;
1434
+ totalTokens += tokensSaved;
1435
+ if (!byKind[r.kind]) byKind[r.kind] = zeroBucket();
1436
+ addBucket(byKind[r.kind], r.events, bytesSaved, tokensSaved);
1437
+ if (!byDay[r.day]) byDay[r.day] = zeroBucket();
1438
+ addBucket(byDay[r.day], r.events, bytesSaved, tokensSaved);
1439
+ const harness = r.harness || HARNESS_UNRECORDED;
1440
+ if (!byHarness[harness]) byHarness[harness] = zeroBucket();
1441
+ addBucket(byHarness[harness], r.events, bytesSaved, tokensSaved);
1442
+ const pricingVersion = r.tg_version || PRICING_VERSION_UNRECORDED;
1443
+ if (!byPricingVersion[pricingVersion]) byPricingVersion[pricingVersion] = zeroBucket();
1444
+ addBucket(byPricingVersion[pricingVersion], r.events, bytesSaved, tokensSaved);
1445
+ }
1446
+ }
1447
+ } catch {
1448
+ }
1449
+ const bySourceDict = {};
1450
+ for (const [kind, bucket] of Object.entries(byKind)) {
1451
+ const source = kindToSource(kind);
1452
+ if (!bySourceDict[source]) {
1453
+ bySourceDict[source] = zeroBucket();
1454
+ }
1455
+ bySourceDict[source].events += bucket.events;
1456
+ bySourceDict[source].bytes_saved += bucket.bytes_saved;
1457
+ bySourceDict[source].tokens_saved += bucket.tokens_saved;
1458
+ }
1459
+ const byCommandDict = {};
1460
+ for (const [cmd, kinds] of Object.entries(COMMAND_KINDS)) {
1461
+ byCommandDict[cmd] = zeroBucket();
1462
+ for (const kind of kinds) {
1463
+ if (byKind[kind]) {
1464
+ byCommandDict[cmd].events += byKind[kind].events;
1465
+ byCommandDict[cmd].bytes_saved += byKind[kind].bytes_saved;
1466
+ byCommandDict[cmd].tokens_saved += byKind[kind].tokens_saved;
1467
+ }
1468
+ }
1469
+ }
1470
+ const byDayList = Object.entries(byDay).map(([date, bucket]) => ({ ...bucket, date })).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
1471
+ const byProjectList = [];
1472
+ const t1 = Date.now();
1473
+ if (t1 - t0 > 1e3) {
1474
+ console.warn(`summarize took ${t1 - t0}ms (window=${windowDays}d, total=${totalEvents} rows)`);
1475
+ }
1476
+ return {
1477
+ total_events: totalEvents,
1478
+ total_bytes_saved: totalBytes,
1479
+ total_tokens_saved: totalTokens,
1480
+ by_kind: byKind,
1481
+ by_day: byDayList,
1482
+ by_project: byProjectList,
1483
+ by_source: bySourceDict,
1484
+ by_harness: byHarness,
1485
+ by_pricing_version: byPricingVersion,
1486
+ counts,
1487
+ by_command: Object.entries(byCommandDict).map(([command, bucket]) => ({ ...bucket, command })).filter((r) => r.events > 0),
1488
+ window_days: windowDays
1489
+ };
1490
+ }
1491
+ function _totalsLines(summary) {
1492
+ return [
1493
+ "# token-goat stats",
1494
+ `Total events: ${summary.total_events}`,
1495
+ `Bytes saved: ${fmtBytes(summary.total_bytes_saved)}`,
1496
+ `Tokens saved: ${summary.total_tokens_saved}`,
1497
+ // Disclosure, not a correction: `total_tokens_saved` above sums rows written under whichever
1498
+ // pricing formula was live when each was recorded, and `tg_version` cannot be read back into
1499
+ // "which formula" for a row from before this disclosure existed (PRICING_VERSION_UNRECORDED is
1500
+ // the overwhelming majority of all-time rows). Excluding those rows from the headline would
1501
+ // discard nearly the whole figure rather than fix it, so the honest move is to keep the sum and
1502
+ // say plainly that it spans more than one era, not to quietly present a mixed total as single-formula.
1503
+ ...hasMixedPricingEras(summary) ? [
1504
+ `Pricing note: totals mix ${countNoun(Object.keys(summary.by_pricing_version).length, "tg_version era")} (${countNoun(summary.by_pricing_version[PRICING_VERSION_UNRECORDED]?.events ?? 0, "row")} unrecorded); see 'token-goat stats --json' -> by_pricing_version for the breakdown`
1505
+ ] : [],
1506
+ // Printed on its own line, below the token total and never inside it, because it counts
1507
+ // placeholders rather than tokens. Omitted entirely when nothing was redacted, so the line is
1508
+ // information rather than a permanent zero. See COUNT_ONLY_KINDS.
1509
+ ...summary.counts["secret_redacted"] ? [`Secrets hidden: ${summary.counts["secret_redacted"]} (a count, not tokens)`] : [],
1510
+ `Window: ${summary.window_days} days`
1511
+ ];
1512
+ }
1513
+ function _useRichStats() {
1514
+ if (process.env["NO_COLOR"]) return false;
1515
+ if (process.stdout.isTTY === true) return true;
1516
+ return process.stdout.isTTY === void 0 && !process.env["CI"];
1517
+ }
1518
+ function _renderShortTotals(summary) {
1519
+ const lines = [
1520
+ ..._totalsLines(summary),
1521
+ "",
1522
+ "Run 'token-goat stats --full' for the full breakdown (by source, by command, by day)."
1523
+ ];
1524
+ console.log(lines.join("\n"));
1525
+ }
1526
+ function _plainTextStats(summary) {
1527
+ const lines = _totalsLines(summary);
1528
+ if (Object.keys(summary.by_source).length > 0) {
1529
+ lines.push("", "## By Source");
1530
+ const sources = Object.entries(summary.by_source).filter(([, b]) => b.events > 0).sort((a, b) => b[1].tokens_saved - a[1].tokens_saved);
1531
+ for (const [source, bucket] of sources) {
1532
+ lines.push(
1533
+ ` ${source.padEnd(8)} ${bucket.events.toString().padStart(6)} events ${fmtBytes(bucket.bytes_saved).padStart(8)} ${bucket.tokens_saved.toString().padStart(8)} tokens`
1534
+ );
1535
+ }
1536
+ }
1537
+ const harnesses = Object.entries(summary.by_harness).filter(([, b]) => b.events > 0).sort((a, b) => b[1].tokens_saved - a[1].tokens_saved);
1538
+ if (harnesses.length > 1) {
1539
+ lines.push("", "## By Harness");
1540
+ for (const [harness, bucket] of harnesses) {
1541
+ lines.push(
1542
+ ` ${harness.padEnd(22)} ${bucket.events.toString().padStart(6)} events ${fmtBytes(bucket.bytes_saved).padStart(8)} ${bucket.tokens_saved.toString().padStart(8)} tokens`
1543
+ );
1544
+ }
1545
+ }
1546
+ if (summary.by_command.length > 0) {
1547
+ lines.push("", "## By Command");
1548
+ for (const row of summary.by_command) {
1549
+ lines.push(
1550
+ ` ${row.command.padEnd(12)} ${row.events.toString().padStart(6)} events ${fmtBytes(row.bytes_saved).padStart(8)} ${row.tokens_saved.toString().padStart(8)} tokens`
1551
+ );
1552
+ }
1553
+ } else {
1554
+ const hintBucket = summary.by_source[SOURCE_HINT];
1555
+ if (hintBucket && hintBucket.events > 0) {
1556
+ lines.push(
1557
+ "",
1558
+ "## By Command",
1559
+ ` 0 direct command invocations this window -- ${hintBucket.events} hint(s) fired but not acted on.`,
1560
+ " Run token-goat symbol/read/section/semantic/outline/skeleton directly to capture these savings."
1561
+ );
1562
+ }
1563
+ }
1564
+ if (summary.by_day.length > 0) {
1565
+ lines.push("", "## Last 7 Days");
1566
+ for (const row of summary.by_day.slice(0, 7)) {
1567
+ lines.push(
1568
+ ` ${row.date} ${row.events.toString().padStart(6)} events ${fmtBytes(row.bytes_saved).padStart(8)} ${row.tokens_saved.toString().padStart(8)} tokens`
1569
+ );
1570
+ }
1571
+ }
1572
+ console.log(lines.join("\n"));
1573
+ }
1574
+ function _buildStatsData(summary, windowDays) {
1575
+ const now = /* @__PURE__ */ new Date();
1576
+ const periodStart = windowDays > 0 ? new Date(now.getTime() - windowDays * 24 * 60 * 60 * 1e3) : /* @__PURE__ */ new Date(0);
1577
+ const sparkDays = [...summary.by_day].reverse().slice(-30);
1578
+ const sparklines = sparkDays.length > 1 ? {
1579
+ events: sparkDays.map((d) => d.events),
1580
+ bytes: sparkDays.map((d) => d.bytes_saved),
1581
+ tokens: sparkDays.map((d) => d.tokens_saved)
1582
+ } : null;
1583
+ return {
1584
+ period_start: periodStart,
1585
+ period_end: now,
1586
+ version: VERSION,
1587
+ window_label: windowDays > 0 ? `last ${countNoun(windowDays, "day")}` : "all time",
1588
+ totals: {
1589
+ events: summary.total_events,
1590
+ bytes: summary.total_bytes_saved,
1591
+ tokens: summary.total_tokens_saved,
1592
+ sparklines
1593
+ },
1594
+ by_kind: Object.entries(summary.by_kind).map(([kind, bucket]) => ({
1595
+ kind,
1596
+ bytes: bucket.bytes_saved,
1597
+ tokens: bucket.tokens_saved,
1598
+ events: bucket.events,
1599
+ bytes_mode_only: _BYTES_MODE_ONLY_KINDS.has(kind)
1600
+ })).sort((a, b) => b.bytes - a.bytes),
1601
+ by_day: summary.by_day.map((d) => ({
1602
+ date: d.date,
1603
+ bytes: d.bytes_saved,
1604
+ tokens: d.tokens_saved,
1605
+ events: d.events
1606
+ })),
1607
+ by_project: [],
1608
+ by_source: Object.entries(summary.by_source).filter(([, b]) => b.events > 0).map(([source, bucket]) => ({
1609
+ source,
1610
+ bytes: bucket.bytes_saved,
1611
+ tokens: bucket.tokens_saved,
1612
+ events: bucket.events
1613
+ })).sort((a, b) => b.bytes - a.bytes),
1614
+ by_command: summary.by_command.map((c) => ({
1615
+ command: c.command,
1616
+ bytes: c.bytes_saved,
1617
+ tokens: c.tokens_saved,
1618
+ events: c.events
1619
+ })),
1620
+ by_harness: Object.entries(summary.by_harness).filter(([, b]) => b.events > 0).map(([harness, bucket]) => ({
1621
+ harness,
1622
+ bytes: bucket.bytes_saved,
1623
+ tokens: bucket.tokens_saved,
1624
+ events: bucket.events
1625
+ })).sort((a, b) => b.bytes - a.bytes)
1626
+ };
1627
+ }
1628
+ function renderShortStats(opts) {
1629
+ const windowDays = opts?.windowDays ?? 30;
1630
+ const summary = summarize(windowDays, void 0, opts?.homeDir);
1631
+ if (summary.total_events === 0) {
1632
+ console.log(noStatsMessage(windowDays, opts?.homeDir));
1633
+ return;
1634
+ }
1635
+ const useTty = process.env["NO_COLOR"] ? false : opts?.force === true ? true : _useRichStats();
1636
+ if (!useTty) {
1637
+ _renderShortTotals(summary);
1638
+ return;
1639
+ }
1640
+ const statsData = _buildStatsData(summary, windowDays);
1641
+ process.stdout.write(renderStats(statsData, { short: true }) + "\n");
1642
+ }
1643
+ function renderStats2(opts) {
1644
+ const windowDays = opts?.windowDays ?? 30;
1645
+ const summary = summarize(windowDays, void 0, opts?.homeDir);
1646
+ if (summary.total_events === 0) {
1647
+ console.log(noStatsMessage(windowDays, opts?.homeDir));
1648
+ return;
1649
+ }
1650
+ const useTty = _useRichStats();
1651
+ if (!useTty) {
1652
+ _plainTextStats(summary);
1653
+ return;
1654
+ }
1655
+ const statsData = _buildStatsData(summary, windowDays);
1656
+ process.stdout.write(renderStats(statsData) + "\n");
1657
+ }
1658
+
1659
+ // src/secret_redact.ts
1660
+ init_define_import_meta_env();
1661
+ var SECRET_PATTERNS = [
1662
+ // Anthropic keys share OpenAI's "sk-" prefix but are more specific ("sk-ant-"), so they're matched first — the generic OpenAI pattern's negative lookahead below is defense in depth, not the sole guard.
1663
+ ["anthropic_api_key", /sk-ant-[A-Za-z0-9_-]{20,}/g],
1664
+ // Modern (post-2024, now the default) OpenAI project keys: "sk-proj-" followed by a long base64url-ish body that legitimately contains '-' and '_' -- the generic pattern below deliberately excludes those characters (hyphenated prose would false-fire), so this needs its own entry with the more specific prefix matched first, like sk-ant- above.
1665
+ ["openai_project_key", /sk-proj-[A-Za-z0-9_-]{20,}/g],
1666
+ ["openai_api_key", /sk-(?!ant-|proj-)[A-Za-z0-9]{20,}/g],
1667
+ ["aws_access_key", /AKIA[0-9A-Z]{16}/g],
1668
+ // Fine-grained PATs ("github_pat_...") are matched before the classic gh[oprsu]_ pattern so the full token is always consumed as one match -- a fine-grained token's own body can contain '_' and could otherwise partially match the classic pattern.
1669
+ ["github_token", /github_pat_[A-Za-z0-9_]{22,}/g],
1670
+ ["github_token", /gh[oprsu]_[A-Za-z0-9]{36,}/g],
1671
+ // xapp- is Slack's app-level token (Socket Mode), a bearer credential in its own right that the xox[baprs]- prefix does not cover. It gets its own entry rather than joining the alternation above because it needs the full segmented shape (xapp-<ver>-<app id>-<digits>- <hex>) to be safe: a bare /xapp-[A-Za-z0-9-]+/ redacted ordinary identifiers like "xapp-config" and the css class "xapp-container", mangling normal source. The xox* prefixes are distinctive enough on their own; "xapp-" is not.
1672
+ ["slack_token", /xox[baprs]-[A-Za-z0-9-]+/g],
1673
+ ["slack_token", /xapp-\d-[A-Za-z0-9]{6,}-\d{8,}-[A-Za-z0-9]{16,}/g],
1674
+ // Matches the full block (BEGIN marker through its matching END marker), not just the header -- the actual secret material is the base64 body between them, so redacting only the header line would leave the key bytes themselves fully readable in the cached blob. The body is lazy and additionally refuses to cross a following BEGIN marker. Both halves matter. The laziness bounds a successful match at the very next END marker; the negative lookahead bounds a *failing* one, because a BEGIN with no END of its own would otherwise scan to end-of-input, and a blob full of such markers made the pass quadratic -- 6 ms, 20 ms and 78 ms for 2000, 4000 and 8000 of them, four times the work for twice the input, the same shape as the lookbehind incident described above. Private key blocks do not nest, so refusing to cross a BEGIN costs nothing in correctness. The algorithm and ` BLOCK` groups are backreferenced in the END marker rather than repeated, so a BEGIN only ever pairs with its own END spelling. Written as two independent optional groups, `BEGIN PGP PRIVATE KEY` would happily close on a distant `END RSA PRIVATE KEY BLOCK` and redact everything in between. A non-participating group backreferences as the empty string in JS, which is exactly what the unprefixed `BEGIN PRIVATE KEY` form needs. The algorithm list covers every armored private-key header openssl, ssh-keygen and gpg actually emit, not just the ones a first draft happened to think of. ENCRYPTED is the PKCS#8 passphrase-protected form (`openssl genpkey -aes256`, `ssh-keygen -m PKCS8`) and is the most common shape of all; DSA is legacy but still written verbatim; PGP carries the ` BLOCK` suffix, which is why that suffix is optional here. All three used to fall through to disk in full. An encrypted key is still key material: the passphrase can be attacked offline once the bytes are cached, so it is redacted like any other. PuTTY `.ppk` files are deliberately not matched. They have no END marker -- the private section is a `Private-Lines: N` count followed by exactly N base64 lines -- so bounding a match would take a stateful parse rather than a regex, on a path that runs over every command output. A regex guess at where the body ends is exactly the over-eager match this module's header warns against.
1675
+ ["private_key_block", /-----BEGIN (RSA |DSA |EC |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY( BLOCK)?-----(?:(?!-----BEGIN )[\s\S])*?-----END \1PRIVATE KEY\2-----/g],
1676
+ // Redacts only the token itself, not the "Authorization: Bearer " prefix -- the lookbehind anchors on the header name and scheme so the surrounding request-log line stays readable, matching how AWS_ACCESS_KEY_ID=... above keeps its own prefix intact. The optional quotes on either side of the colon are what let this see a header carried in JSON rather than in raw wire format. Without them the lookbehind demanded the colon sit directly against the header name and the scheme directly against the space, so a body like {"Authorization": "Bearer <token>"} -- the shape any logged fetch or MCP result arrives in -- matched nothing and the token was cached verbatim. `token` is the second scheme spelling in wide use -- it is what curl and gh examples pass for GitHub and many other APIs -- and an opaque value behind it carries exactly the same authority as one behind `Bearer`. The trailing gap is `{1,8}` rather than a single space for the same reason every other gap in this lookbehind already is: a hand-aligned or reformatted header ("Authorization: Bearer <token>") is ordinary, and demanding exactly one space there made this the one position in the pattern that a second space defeated.
1677
+ ["auth_bearer_token", /(?<=Authorization["']?[ \t]{0,8}:[ \t]{0,8}["']?[ \t]{0,8}(?:Bearer|token)[ \t]{1,8})[A-Za-z0-9\-._~+/]{10,}=*/gi],
1678
+ ["auth_basic_token", /(?<=Authorization["']?[ \t]{0,8}:[ \t]{0,8}["']?[ \t]{0,8}Basic[ \t])[A-Za-z0-9+/]{6,}=*/gi],
1679
+ // JWTs have no distinctive prefix of their own, but the base64url encoding of the smallest realistic header ('{"alg":' or similar) always starts with "eyJ", so that's the practical anchor here -- each of the three dot-separated segments requires a minimum length to avoid matching a short, coincidentally dotted token.
1680
+ //
1681
+ // The trailing `={0,2}` on each segment is what makes a padded token match. Base64url as the JWT spec defines it drops the `=` padding, but producers that reach for a plain base64 encoder emit it anyway, and a `=` in the header or payload segment used to defeat the match outright: not a partial redaction, but none at all, so the entire token was printed. `=` cannot appear anywhere except the end of a segment, since it is not one of the characters the segment body allows, so accepting it here cannot widen the match onto anything else.
1682
+ ["jwt", /eyJ[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]{10,}={0,2}/g],
1683
+ ["npm_token", /npm_[A-Za-z0-9]{36}/g],
1684
+ // rk_live_ (restricted keys) share the sk_live_/sk_test_ secret-key shape and risk level, so one pattern covers all three rather than adding a near-duplicate entry.
1685
+ ["stripe_key", /(?:sk_live_|sk_test_|rk_live_)[A-Za-z0-9]{20,}/g],
1686
+ ["google_api_key", /AIza[A-Za-z0-9_-]{35}/g],
1687
+ // Presigned-url signatures: AWS SigV4 (X-Amz-Signature), Google Cloud Storage (X-Goog-Signature), and Azure blob SAS (sig). These are bearer credentials in query-string clothing -- anyone holding the whole url can read or write the object until it expires, and none of the prefix-anchored patterns above match them because the signature is a bare hex or base64 blob with no distinctive prefix of its own. The '[?&]' anchor and the 16-char floor are what make the short, generic 'sig' name safe to key on: a prose or code mention of "sig" never sits directly after a query separator followed by that much opaque token.
1688
+ ["presigned_signature", /(?<=[?&](?:X-Amz-Signature|X-Goog-Signature|sig)=)[A-Za-z0-9%+/=_-]{16,}/gi],
1689
+ // A password inside a connection url. `postgres://user:hunter2@db.internal` carries the credential in the authority section, where there is no `key=value` separator for the generic pattern below to anchor on, so a DATABASE_URL echoed by a failing migration or a psql error went through untouched. The anchors are what keep this narrow: a scheme's `://`, a userinfo segment, the colon, and a following `@`. `http://host:8080/path` has no `@` and is left alone; so is any url without credentials.
1690
+ ["url_credentials", /(?<=:\/\/[^\s:@/]{1,64}:)[^\s:@/]{1,256}(?=@)/g],
1691
+ // Azure storage account connection strings (`DefaultEndpointsProtocol=https;AccountName=...; AccountKey=<base64>==;EndpointSuffix=core.windows.net`) carry a full read/write key to the account in the AccountKey field, and none of the generic patterns above catch it: generic_secret_assignment's keyword list (password|passwd|secret|api[_-]?key| access[_-]?token|refresh[_-]?token|id[_-]?token) has nothing that matches "AccountKey", and an unanchored base64-shape pattern was deliberately rejected -- this module's header already warns that a bare high-entropy-blob heuristic false-fires on ordinary code, JSON and log output, and an 88-char base64 value is exactly the shape a hash, a compiled asset digest or a generated id can also take. Anchoring on the literal `AccountKey=` field name instead keeps the match specific to this one connection-string field. The value class is base64 proper (letters, digits, `+`, `/`, trailing `=` padding) and none of those characters include `;`, so the match terminates on its own at the `;` that starts the next `Name=` field -- unlike generic_secret_assignment's separator characters (`& ; # , :`), which double as ordinary credential characters and need a lookahead to tell the two roles apart, `;` is never valid base64 and needs no such lookahead here. The lookbehind keeps `AccountKey=` itself in the output, matching auth_bearer_token and presigned_signature above, so `;EndpointSuffix=core.windows.net` after it stays fully readable too. `SharedAccessKey` is the same credential one Azure service over: Service Bus, Event Hubs and Relay spell it that way (`Endpoint=sb://ns.servicebus.windows.net/;SharedAccessKeyName=Root; SharedAccessKey=<base64>`) and it carries the same authority over that namespace that AccountKey does over a storage account. `SharedAccessKeyName` is a plain identifier rather than a secret, and never matches: the separator in the lookbehind sits directly against the key name, so the `Name` in between stops it dead. The separator is spelled the way auth_bearer_token above spells its own, for the same reasons that comment records having learned the hard way. Optional quotes on either side of it, so the JSON and YAML forms a logged MCP result or api response actually arrives in are matched rather than stopped dead at the opening quote. A bounded gap rather than exactly one space, so a hand-aligned or reformatted `AccountKey = ...` in an appsettings file is not the single variant that defeats the whole pattern. Case-insensitive for the same reason presigned_signature is. The leading word boundary is what keeps the widened name from reaching into the middle of a longer identifier such as `myaccountkey=`.
1692
+ ["azure_storage_key", /(?<=\b(?:AccountKey|SharedAccessKey)["']?[ \t]{0,8}[:=][ \t]{0,8}["']?)[A-Za-z0-9+/]{40,}=*/gi],
1693
+ // Generic key=value assignments in .env-file and connection-string/query-string shape. The lookbehind again redacts only the value, and the value's character class deliberately excludes whitespace, '&', ';', '#', quote characters, and '[' ']' ':' -- that exclusion is what stops this from swallowing the rest of the line (a trailing comment or the next key=value pair) or the remainder of a query string past the matched parameter, which is exactly the kind of over-eager match this module's own design note above warns broad heuristics produce. The '[' ']' ':' exclusion also matters because this pattern runs last: an earlier pattern's own "OPENAI_API_KEY=[REDACTED:openai_project_key]" replacement text contains "API_KEY=" too, and without excluding those characters this pattern would re-match and double-redact its own placeholder. The length has a lower bound only (no upper bound): capping it at 64 used to leave the tail of any longer secret unredacted in plain text, which is worse than no redaction because it looks handled. A single negated-class quantifier like this cannot backtrack catastrophically -- there is no nested or overlapping quantifier for the engine to explore multiple ways of matching, so removing the upper bound does not introduce a ReDoS risk. Quotes are permitted around the separator, but never inside the value class. A quoted value is the ordinary way secrets are written -- .env files, JSON, YAML, TOML all quote by default -- and the lookbehind used to stop dead at the opening quote, so `API_KEY="..."` passed through in full while the bare `API_KEY=...` was caught. The closing quote of the key name blocked it from the other side too, which is what kept every JSON body unredacted. Keeping quotes out of the value class is still what stops the match running past the closing quote. The keyword may be a prefix of a longer key name rather than the whole of it, so the trailing identifier class below is load-bearing: without it the lookbehind required the keyword to sit immediately before the separator, and AWS_SECRET_ACCESS_KEY=, SECRET_KEY=, and DB_PASSWORD_HASH= all passed through in full. That class matches identifier characters only, so prose that merely mentions a keyword still never reaches a separator and stays unredacted. api[_-]?key covers the apikey and api-key spellings too. `& ; # , :` play two incompatible roles. They separate one field from the next (a query string, a cookie header, an inline env list), and they are also perfectly ordinary credential characters. Rejecting them outright got the first role right and the second badly wrong: the match stopped at the first one and left everything after it in plain text, so `password=corr&horse&battery` redacted four characters and printed the rest, and `DB_PASSWORD=Aa1:xyz` matched nothing at all because the run before the `:` was under the four-character floor. A tail left sitting in the open is the outcome this module's header calls worse than no redaction, because it reads as handled.
1694
+ //
1695
+ // So the separator role is decided by what follows rather than assumed: one of these characters ends the value only when the next thing along is another `name=` / `name:` pair, which is what an actual field separator is always followed by. `,OTHER=public` and `; other=1` still end it; the `&` in the middle of a passphrase does not. Whitespace, quotes and brackets are unchanged -- they end a value unconditionally, which is also what keeps this pattern from re-matching the `[REDACTED:...]` placeholder it just wrote.
1696
+ ["generic_secret_assignment", /(?<=(?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)[a-z0-9_-]{0,64}["']?[ \t]{0,8}[:=][ \t]{0,8}["']?)(?:\\[^\n]|[^\s\\&;#,:'"[\]{}]|[&;#,:](?![ \t]*[A-Za-z_][A-Za-z0-9_.-]*[ \t]*[:=])){4,}/gi]
1697
+ ];
1698
+ function countRedactionPlaceholders(text) {
1699
+ return text.match(/\[REDACTED:[a-z0-9_]+\]/g)?.length ?? 0;
1700
+ }
1701
+ var MAX_CUSTOM_PATTERNS = 64;
1702
+ var MAX_CUSTOM_PATTERN_LENGTH = 512;
1703
+ var customCache = null;
1704
+ function compileCustomPatterns(sources) {
1705
+ const key = JSON.stringify(sources);
1706
+ if (customCache !== null && customCache.key === key) {
1707
+ return { patterns: customCache.patterns, problems: customCache.problems };
1708
+ }
1709
+ const patterns = [];
1710
+ const problems = [];
1711
+ const written = sources.map((raw) => raw.trim()).filter((source) => source.length > 0);
1712
+ for (const source of written.slice(0, MAX_CUSTOM_PATTERNS)) {
1713
+ if (source.length > MAX_CUSTOM_PATTERN_LENGTH) {
1714
+ problems.push({ pattern: source.slice(0, 60), reason: `longer than ${MAX_CUSTOM_PATTERN_LENGTH} characters` });
1715
+ continue;
1716
+ }
1717
+ if (hasNestedQuantifier(source)) {
1718
+ problems.push({
1719
+ pattern: source,
1720
+ reason: "repeats a group that already repeats, which can take exponential time to match"
1721
+ });
1722
+ continue;
1723
+ }
1724
+ let compiled;
1725
+ try {
1726
+ compiled = new RegExp(source, "g");
1727
+ } catch (e) {
1728
+ problems.push({ pattern: source, reason: e instanceof Error ? e.message : "is not a valid regular expression" });
1729
+ continue;
1730
+ }
1731
+ if (new RegExp(source).test("")) {
1732
+ problems.push({
1733
+ pattern: source,
1734
+ reason: "matches the empty string, so it would replace every position in the text"
1735
+ });
1736
+ continue;
1737
+ }
1738
+ if (growsExponentially(compiled)) {
1739
+ problems.push({
1740
+ pattern: source,
1741
+ reason: "its running time doubles as the text grows, which can stall the process on a short input"
1742
+ });
1743
+ continue;
1744
+ }
1745
+ patterns.push(compiled);
1746
+ }
1747
+ if (written.length > MAX_CUSTOM_PATTERNS) {
1748
+ problems.push({
1749
+ pattern: `(${written.length} entries)`,
1750
+ reason: `only the first ${MAX_CUSTOM_PATTERNS} custom patterns are used`
1751
+ });
1752
+ }
1753
+ customCache = { key, patterns, problems };
1754
+ return { patterns, problems };
1755
+ }
1756
+ var STRICT_CANDIDATE = /[A-Za-z0-9+/_-]{24,}={0,2}/g;
1757
+ function entropyBitsPerChar(s) {
1758
+ const counts = /* @__PURE__ */ new Map();
1759
+ for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
1760
+ let bits = 0;
1761
+ for (const n of counts.values()) {
1762
+ const p = n / s.length;
1763
+ bits -= p * Math.log2(p);
1764
+ }
1765
+ return bits;
1766
+ }
1767
+ function characterClasses(s) {
1768
+ let n = 0;
1769
+ if (/[a-z]/.test(s)) n++;
1770
+ if (/[A-Z]/.test(s)) n++;
1771
+ if (/[0-9]/.test(s)) n++;
1772
+ if (/[+/=_-]/.test(s)) n++;
1773
+ return n;
1774
+ }
1775
+ function looksLikeCredential(s) {
1776
+ return characterClasses(s) >= 3 && entropyBitsPerChar(s) >= 3.5;
1777
+ }
1778
+ function redactSecrets(text, config = loadConfig()) {
1779
+ let count = 0;
1780
+ let out = text;
1781
+ for (const [kind, pattern] of SECRET_PATTERNS) {
1782
+ out = out.replace(pattern, () => {
1783
+ count++;
1784
+ return `[REDACTED:${kind}]`;
1785
+ });
1786
+ }
1787
+ for (const pattern of compileCustomPatterns(config.redaction.custom_patterns).patterns) {
1788
+ out = out.replace(pattern, () => {
1789
+ count++;
1790
+ return "[REDACTED:custom]";
1791
+ });
1792
+ }
1793
+ if (config.redaction.strict) {
1794
+ out = out.replace(STRICT_CANDIDATE, (candidate) => {
1795
+ if (!looksLikeCredential(candidate)) return candidate;
1796
+ count++;
1797
+ return "[REDACTED:high_entropy]";
1798
+ });
1799
+ }
1800
+ return { text: out, count };
1801
+ }
1802
+
1803
+ // src/disk_cache.ts
1804
+ init_define_import_meta_env();
1805
+ import * as fs from "node:fs";
1806
+ import * as path2 from "node:path";
1807
+ var DEFAULT_MAX_COUNT = 200;
1808
+ var DEFAULT_MAX_AGE_MS = 24 * 3600 * 1e3;
1809
+ function sanitizeId(id) {
1810
+ return sanitizeIdForFilename(id, 64);
1811
+ }
1812
+ function blobDir(subdir) {
1813
+ return path2.join(tokenGoatHome(), subdir);
1814
+ }
1815
+ function blobPath(subdir, id) {
1816
+ const safe = sanitizeId(id);
1817
+ if (!safe) return null;
1818
+ const dir = blobDir(subdir);
1819
+ const candidate = path2.join(dir, `${safe}.json`);
1820
+ try {
1821
+ const rel = path2.relative(dir, candidate);
1822
+ if (rel.startsWith("..")) return null;
1823
+ } catch {
1824
+ return null;
1825
+ }
1826
+ return candidate;
1827
+ }
1828
+ function isBlobStale(subdir, id) {
1829
+ const p = blobPath(subdir, id);
1830
+ if (p === null) return false;
1831
+ try {
1832
+ const stat = fs.statSync(p);
1833
+ return Date.now() - stat.mtimeMs > DEFAULT_MAX_AGE_MS;
1834
+ } catch {
1835
+ return false;
1836
+ }
1837
+ }
1838
+ function subdirCacheDefaults(subdir) {
1839
+ try {
1840
+ if (subdir === "bash_outputs") {
1841
+ const bc = loadConfig().bash_compress;
1842
+ return { maxCount: bc.cache_max_file_count, maxBytes: bc.cache_max_bytes, maxBytesPerItem: bc.cache_max_bytes_per_output };
1843
+ }
1844
+ if (subdir === "web_outputs") {
1845
+ const wf = loadConfig().webfetch;
1846
+ return { maxCount: wf.max_file_count, maxBytes: wf.max_bytes, maxBytesPerItem: Number.POSITIVE_INFINITY };
1847
+ }
1848
+ } catch {
1849
+ }
1850
+ return { maxCount: DEFAULT_MAX_COUNT, maxBytes: Number.POSITIVE_INFINITY, maxBytesPerItem: Number.POSITIVE_INFINITY };
1851
+ }
1852
+ function storeBlob(subdir, id, value, opts = {}) {
1853
+ const p = blobPath(subdir, id);
1854
+ if (!p) return false;
1855
+ const defaults = subdirCacheDefaults(subdir);
1856
+ const maxBytesPerItem = opts.maxBytesPerItem ?? defaults.maxBytesPerItem;
1857
+ let rawJson;
1858
+ try {
1859
+ rawJson = JSON.stringify(value);
1860
+ } catch {
1861
+ return false;
1862
+ }
1863
+ let json;
1864
+ try {
1865
+ const result = redactSecrets(rawJson);
1866
+ json = result.text;
1867
+ if (result.count > 0) recordStat("secret_redacted", 0, result.count, void 0, subdir);
1868
+ } catch {
1869
+ return false;
1870
+ }
1871
+ if (Number.isFinite(maxBytesPerItem) && Buffer.byteLength(json, "utf-8") > maxBytesPerItem) return false;
1872
+ try {
1873
+ const dir = path2.dirname(p);
1874
+ if (!fs.existsSync(dir)) ensureDirSync(dir);
1875
+ atomicWriteText(p, json);
1876
+ } catch {
1877
+ return false;
1878
+ }
1879
+ pruneBlobs(
1880
+ subdir,
1881
+ opts.maxCount ?? defaults.maxCount,
1882
+ opts.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
1883
+ opts.maxBytes ?? defaults.maxBytes,
1884
+ p
1885
+ );
1886
+ return true;
1887
+ }
1888
+ function loadBlob(subdir, id) {
1889
+ const p = blobPath(subdir, id);
1890
+ if (!p) return null;
1891
+ try {
1892
+ if (!fs.existsSync(p)) return null;
1893
+ return JSON.parse(fs.readFileSync(p, "utf8"));
1894
+ } catch {
1895
+ return null;
1896
+ }
1897
+ }
1898
+ function listBlobs(subdir) {
1899
+ const dir = blobDir(subdir);
1900
+ const out = [];
1901
+ try {
1902
+ if (!fs.existsSync(dir)) return out;
1903
+ for (const file of fs.readdirSync(dir)) {
1904
+ if (!file.endsWith(".json")) continue;
1905
+ const id = file.slice(0, -5);
1906
+ let mtime = 0;
1907
+ try {
1908
+ mtime = fs.statSync(path2.join(dir, file)).mtimeMs;
1909
+ } catch {
1910
+ }
1911
+ const value = loadBlob(subdir, id);
1912
+ if (value !== null) out.push({ id, mtime, value });
1913
+ }
1914
+ } catch {
1915
+ return out;
1916
+ }
1917
+ return out;
1918
+ }
1919
+ function pruneBlobs(subdir, maxCount = DEFAULT_MAX_COUNT, maxAgeMs = DEFAULT_MAX_AGE_MS, maxBytes = Number.POSITIVE_INFINITY, protectedPath) {
1920
+ return pruneBlobDir(blobDir(subdir), maxCount, maxAgeMs, maxBytes, protectedPath);
1921
+ }
1922
+ function pruneBlobDir(dir, maxCount = DEFAULT_MAX_COUNT, maxAgeMs = DEFAULT_MAX_AGE_MS, maxBytes = Number.POSITIVE_INFINITY, protectedPath) {
1923
+ let removed = 0;
1924
+ try {
1925
+ if (!fs.existsSync(dir)) return 0;
1926
+ const cutoff = Date.now() - maxAgeMs;
1927
+ let kept = [];
1928
+ let protectedEntry;
1929
+ for (const file of fs.readdirSync(dir)) {
1930
+ const full = path2.join(dir, file);
1931
+ let stat;
1932
+ try {
1933
+ stat = fs.statSync(full);
1934
+ } catch {
1935
+ continue;
1936
+ }
1937
+ if (!stat.isFile()) continue;
1938
+ if (protectedPath !== void 0 && full === protectedPath) {
1939
+ protectedEntry = [full, stat.mtimeMs, stat.size];
1940
+ continue;
1941
+ }
1942
+ if (stat.mtimeMs < cutoff) {
1943
+ try {
1944
+ fs.unlinkSync(full);
1945
+ removed++;
1946
+ } catch {
1947
+ continue;
1948
+ }
1949
+ } else if (file.endsWith(".json")) {
1950
+ kept.push([full, stat.mtimeMs, stat.size]);
1951
+ }
1952
+ }
1953
+ const countBudget = protectedEntry ? Math.max(0, maxCount - 1) : maxCount;
1954
+ if (kept.length > countBudget) {
1955
+ kept.sort((a, b) => a[1] - b[1]);
1956
+ const excess = kept.slice(0, kept.length - countBudget);
1957
+ kept = kept.slice(kept.length - countBudget);
1958
+ for (const [full] of excess) {
1959
+ try {
1960
+ fs.unlinkSync(full);
1961
+ removed++;
1962
+ } catch {
1963
+ continue;
1964
+ }
1965
+ }
1966
+ }
1967
+ if (Number.isFinite(maxBytes)) {
1968
+ kept.sort((a, b) => a[1] - b[1]);
1969
+ let total = kept.reduce((sum, [, , size]) => sum + size, 0) + (protectedEntry ? protectedEntry[2] : 0);
1970
+ while (total > maxBytes && kept.length > 0) {
1971
+ const oldest = kept.shift();
1972
+ if (!oldest) break;
1973
+ const [full, , size] = oldest;
1974
+ try {
1975
+ fs.unlinkSync(full);
1976
+ removed++;
1977
+ total -= size;
1978
+ } catch {
1979
+ break;
1980
+ }
1981
+ }
1982
+ }
1983
+ } catch {
1984
+ return removed;
1985
+ }
1986
+ return removed;
1987
+ }
1988
+ var SWEEPABLE_CACHE_SUBDIRS = [
1989
+ { subdir: "bash_outputs", countCapped: true },
1990
+ { subdir: "web_outputs", countCapped: true },
1991
+ { subdir: "mcp_outputs", countCapped: true },
1992
+ { subdir: "sessions", countCapped: false }
1993
+ ];
1994
+ function sweepCacheRoots(extraRoots = []) {
1995
+ let removed = 0;
1996
+ const roots = [tokenGoatHome(), ...extraRoots];
1997
+ const seen = /* @__PURE__ */ new Set();
1998
+ for (const root of roots) {
1999
+ if (!root || seen.has(root)) continue;
2000
+ seen.add(root);
2001
+ for (const { subdir, countCapped } of SWEEPABLE_CACHE_SUBDIRS) {
2002
+ try {
2003
+ const defaults = subdirCacheDefaults(subdir);
2004
+ removed += pruneBlobDir(
2005
+ path2.join(root, subdir),
2006
+ countCapped ? defaults.maxCount : Number.POSITIVE_INFINITY,
2007
+ DEFAULT_MAX_AGE_MS,
2008
+ countCapped ? defaults.maxBytes : Number.POSITIVE_INFINITY
2009
+ );
2010
+ } catch {
2011
+ }
2012
+ }
2013
+ }
2014
+ return removed;
2015
+ }
2016
+
2017
+ export {
2018
+ colorStdout,
2019
+ RESET,
2020
+ stripAnsiEscapes,
2021
+ stripAnsi,
2022
+ fg,
2023
+ C,
2024
+ SOURCE_HINT,
2025
+ savedTokensFromBytes,
2026
+ formatLocalTimestamp,
2027
+ recordStat,
2028
+ recordUnmappedTool,
2029
+ readUnmappedTools,
2030
+ summarize,
2031
+ _useRichStats,
2032
+ renderShortStats,
2033
+ renderStats2 as renderStats,
2034
+ countRedactionPlaceholders,
2035
+ compileCustomPatterns,
2036
+ redactSecrets,
2037
+ DEFAULT_MAX_COUNT,
2038
+ DEFAULT_MAX_AGE_MS,
2039
+ blobPath,
2040
+ isBlobStale,
2041
+ storeBlob,
2042
+ loadBlob,
2043
+ listBlobs,
2044
+ pruneBlobs,
2045
+ sweepCacheRoots
2046
+ };