@sriinnu/fiche 0.0.0-stage → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +288 -2
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +122 -4
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,837 @@
1
+ /**
2
+ * Shared data layer for the dashboard's session views. Node-only (filesystem
3
+ * I/O) — never imported from `src/core/`.
4
+ *
5
+ * ## Why we group by first_user_sha8 (Path B)
6
+ *
7
+ * Every TrackEvent carries `first_user_sha8` (see src/core/tracker.ts), an
8
+ * sha256 prefix of the conversation's first prompt (harness envelopes skipped;
9
+ * see src/core/session-state.ts:sessionAnchorText). Within a single
10
+ * Claude Code session that hash is stable across every turn; across two
11
+ * different sessions it is virtually never the same. That makes it a
12
+ * better-than-good-enough session key without coupling inkling to Claude
13
+ * Code's internal file layout for *correctness*.
14
+ *
15
+ * We *do* read `~/.claude/projects/` opportunistically (see `claudeCodeMap`)
16
+ * to enrich the dashboard with real Claude Code session IDs + project
17
+ * paths — but it's best-effort: missing or unreadable files just leave the
18
+ * synthetic ID standing alone.
19
+ *
20
+ * ## File layout we manage
21
+ *
22
+ * - `~/.inkling/events.jsonl` — append-only JSONL written by FileTracker
23
+ * - `~/.inkling/4xx-bodies/${iso-ts}-${sha8}.json.gz` — gzipped failure
24
+ * bodies referenced from JSONL rows via `req_body_sample_path`
25
+ */
26
+ import * as fs from 'node:fs';
27
+ import { readBrandEnv } from './core/env.js';
28
+ import * as path from 'node:path';
29
+ import * as os from 'node:os';
30
+ import * as crypto from 'node:crypto';
31
+ import * as readline from 'node:readline';
32
+ import { computeActualInputEffWithCacheTier, computeBaselineInputEffWithCacheTier, deriveBaselineWarmth, observedCacheTtlSec, } from './core/baseline.js';
33
+ import { sessionAnchorText } from './core/session-state.js';
34
+ import { anthropicReadRate, priceMode, resolvePriceRates } from './core/pricing.js';
35
+ import { computeOpenAIActualInputEff, computeOpenAISessionBaselineInputEff, deriveOpenAIBaselineWarmth, OPENAI_CACHE_TTL_SEC, } from './core/openai-savings.js';
36
+ export function defaultPaths() {
37
+ const home = os.homedir();
38
+ const preferred = path.join(home, '.fiche', 'events.jsonl');
39
+ const legacy = path.join(home, '.inkling', 'events.jsonl');
40
+ const eventsFile = readBrandEnv('LOG') ?? (fs.existsSync(preferred) || !fs.existsSync(legacy) ? preferred : legacy);
41
+ // The sidecar directory is `4xx-bodies` next to the events file, matching
42
+ // what src/node.ts writes.
43
+ const sidecarDir = path.join(path.dirname(eventsFile), '4xx-bodies');
44
+ return { eventsFile, sidecarDir };
45
+ }
46
+ // ---- Core reader -----------------------------------------------------------
47
+ /** Lazily stream events.jsonl line by line. Yields parsed TrackEvents plus
48
+ * the raw line (we need byte length for jsonlBytes accounting). Malformed
49
+ * lines are silently dropped — matches `inkling stats` behavior. */
50
+ export async function* readEvents(eventsFile) {
51
+ if (!fs.existsSync(eventsFile))
52
+ return;
53
+ const stream = fs.createReadStream(eventsFile, { encoding: 'utf8' });
54
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
55
+ for await (const line of rl) {
56
+ if (!line.trim())
57
+ continue;
58
+ let ev;
59
+ try {
60
+ ev = JSON.parse(line);
61
+ }
62
+ catch {
63
+ continue;
64
+ }
65
+ // +1 for the newline FileTracker writes after each row.
66
+ yield { ev, rawBytes: Buffer.byteLength(line, 'utf8') + 1 };
67
+ }
68
+ }
69
+ // ---- Aggregation -----------------------------------------------------------
70
+ export const UNKNOWN_SESSION = '<unknown>';
71
+ function sessionIdOf(ev) {
72
+ return ev.session_key ?? ev.first_user_sha8 ?? UNKNOWN_SESSION;
73
+ }
74
+ /** Build a map of sessionId -> SessionSummary by scanning every event. Also
75
+ * tracks which sidecars belong to which session so prune can clean them. */
76
+ export async function aggregateSessions(paths) {
77
+ const sessions = new Map();
78
+ const sidecarsBySession = new Map();
79
+ // Per-session prior rows for the cache-aware text counterfactual: a fresh
80
+ // same-prefix prior makes the text path warm, and sizes the reused/grown
81
+ // split. Kept out of SessionSummary so it never leaks into the
82
+ // /api/sessions.json shape.
83
+ const warmth = new Map();
84
+ const openaiWarmth = new Map();
85
+ const googleWarmth = new Map();
86
+ const CACHE_TTL_SEC = 300; // default; a 1h-tier prior carries 3600 s (observedCacheTtlSec)
87
+ // Stat sidecar sizes once up front. Looking up size per event would be
88
+ // O(N²) syscalls; the directory is small enough to read fully.
89
+ const sidecarSizes = sidecarFileSizes(paths.sidecarDir);
90
+ for await (const { ev, rawBytes } of readEvents(paths.eventsFile)) {
91
+ const id = sessionIdOf(ev);
92
+ let s = sessions.get(id);
93
+ if (!s) {
94
+ s = {
95
+ id,
96
+ project: ev.cwd,
97
+ firstSeen: ev.ts,
98
+ lastSeen: ev.ts,
99
+ requestCount: 0,
100
+ charsSaved: 0,
101
+ tokensSavedEst: 0,
102
+ cacheReadTokens: 0,
103
+ jsonlBytes: 0,
104
+ sidecarBytes: 0,
105
+ };
106
+ sessions.set(id, s);
107
+ }
108
+ s.requestCount++;
109
+ s.jsonlBytes += rawBytes;
110
+ if (ev.ts < s.firstSeen)
111
+ s.firstSeen = ev.ts;
112
+ if (ev.ts > s.lastSeen)
113
+ s.lastSeen = ev.ts;
114
+ // Cling to whichever cwd we saw first; sessions that hop directories are
115
+ // rare and the first cwd is the most stable identifier.
116
+ if (s.project === undefined && ev.cwd)
117
+ s.project = ev.cwd;
118
+ // Real per-session savings, cache-aware. See src/core/baseline.ts for the
119
+ // full derivation: inkling is credited only for token reduction, never for
120
+ // caching. The imagined text baseline is warm when cr>0, or when a
121
+ // same-prefix prior completed within the TTL (see deriveBaselineWarmth).
122
+ // Events missing either probe stay out of the rollup — no estimation.
123
+ const inp = ev.input_tokens ?? 0;
124
+ const cc = ev.cache_create_tokens ?? 0;
125
+ const cc5m = ev.cache_create_5m_tokens;
126
+ const cc1h = ev.cache_create_1h_tokens ?? 0;
127
+ const cr = ev.cache_read_tokens ?? 0;
128
+ const cached = ev.cached_tokens ?? 0;
129
+ const cacheWrite = ev.cache_write_tokens ?? 0;
130
+ const out = ev.output_tokens ?? 0;
131
+ const isGoogle = ev.accounting_provider === 'google'
132
+ || ev.path.includes('google-ai-studio')
133
+ || ev.path.toLowerCase().includes('generatecontent');
134
+ const isOpenAI = ev.accounting_provider === 'openai'
135
+ || (!isGoogle && (ev.path.includes('responses') || ev.path.includes('chat/completions')));
136
+ const haveUsage = inp > 0 || out > 0 || cc > 0 || cr > 0 || cached > 0 || cacheWrite > 0;
137
+ const completionSec = Date.parse(ev.ts) / 1000;
138
+ const requestStartSec = completionSec - Math.max(0, ev.duration_ms || 0) / 1000;
139
+ const baseline = ev.baseline_tokens;
140
+ if (isGoogle) {
141
+ const gPrev = googleWarmth.get(id);
142
+ const pxShaG = ev.cache_prefix_sha8 ?? ev.history_image_sha8;
143
+ const gWarmth = deriveOpenAIBaselineWarmth(gPrev, requestStartSec, cached, ev.system_sha8, ev.model, CACHE_TTL_SEC, pxShaG);
144
+ const measured = ev.baseline_probe_status === 'ok' && typeof baseline === 'number' && baseline > 0
145
+ ? baseline
146
+ : 0;
147
+ const hygieneTok = ev.text_hygiene_saved_tokens ?? 0;
148
+ const estimated = ev.compressed === true
149
+ && (((ev.image_tokens ?? 0) > 0 && (ev.baseline_imaged_tokens ?? 0) > 0) || hygieneTok > 0)
150
+ ? Math.max(0, inp
151
+ - (ev.image_tokens ?? 0)
152
+ - (ev.native_injected_tokens ?? 0)
153
+ + (ev.baseline_imaged_tokens ?? 0)
154
+ + hygieneTok)
155
+ : 0;
156
+ const gBaseline = measured || estimated;
157
+ const clampedCached = Math.min(inp, Math.max(0, cached));
158
+ if (ev.compressed === true && haveUsage && gBaseline > 0) {
159
+ let tokensSaved;
160
+ if (priceMode() === 'kosha') {
161
+ const rates = resolvePriceRates(ev.model, { promptTokens: inp });
162
+ if (gWarmth.selfBusted) {
163
+ const reused = Math.min(gBaseline, gWarmth.prevPrefixTokens);
164
+ const baselineEff = reused * rates.read + (gBaseline - reused) * 1.0;
165
+ const actualEff = (inp - clampedCached) + clampedCached * rates.read;
166
+ tokensSaved = baselineEff - actualEff;
167
+ }
168
+ else {
169
+ tokensSaved = (gBaseline - inp) * (clampedCached > 0 ? rates.read : 1);
170
+ }
171
+ }
172
+ else {
173
+ tokensSaved = gBaseline - inp;
174
+ }
175
+ s.tokensSavedEst += Math.round(tokensSaved);
176
+ s.charsSaved += Math.round(tokensSaved * 4);
177
+ }
178
+ if (haveUsage) {
179
+ googleWarmth.set(id, {
180
+ ts: completionSec,
181
+ cachedOrPrefixTokens: clampedCached > 0 ? clampedCached : Math.max(gPrev?.cachedOrPrefixTokens ?? 0, inp),
182
+ prefixSha: ev.system_sha8 ?? gPrev?.prefixSha,
183
+ pxPrefixSha: pxShaG ?? gPrev?.pxPrefixSha,
184
+ model: ev.model ?? gPrev?.model,
185
+ });
186
+ }
187
+ }
188
+ else if (isOpenAI) {
189
+ const oPrev = openaiWarmth.get(id);
190
+ const pxShaO = ev.cache_prefix_sha8 ?? ev.history_image_sha8;
191
+ const oWarmth = deriveOpenAIBaselineWarmth(oPrev, requestStartSec, cached, ev.system_sha8, ev.model, OPENAI_CACHE_TTL_SEC, pxShaO);
192
+ const hygieneTok = ev.text_hygiene_saved_tokens ?? 0;
193
+ if (ev.compressed === true &&
194
+ haveUsage &&
195
+ ((ev.baseline_imaged_tokens ?? 0) > 0 || hygieneTok > 0)) {
196
+ const actualEff = computeOpenAIActualInputEff(inp, cached, ev.model, cacheWrite);
197
+ const baselineEff = computeOpenAISessionBaselineInputEff({
198
+ inputTokens: inp,
199
+ cachedTokens: cached,
200
+ imageTokens: ev.image_tokens ?? 0,
201
+ baselineImagedTokens: ev.baseline_imaged_tokens ?? 0,
202
+ nativeInjectedTokens: ev.native_injected_tokens ?? 0,
203
+ textHygieneSavedTokens: hygieneTok,
204
+ cacheWriteTokens: cacheWrite,
205
+ model: ev.model,
206
+ warmth: oWarmth,
207
+ });
208
+ const tokensSaved = baselineEff - actualEff;
209
+ s.tokensSavedEst += Math.round(tokensSaved);
210
+ s.charsSaved += Math.round(tokensSaved * 4);
211
+ }
212
+ if (haveUsage) {
213
+ openaiWarmth.set(id, {
214
+ ts: completionSec,
215
+ cachedOrPrefixTokens: cached > 0 ? cached : Math.max(oPrev?.cachedOrPrefixTokens ?? 0, inp),
216
+ prefixSha: ev.system_sha8 ?? oPrev?.prefixSha,
217
+ pxPrefixSha: pxShaO ?? oPrev?.pxPrefixSha,
218
+ model: ev.model ?? oPrev?.model,
219
+ });
220
+ }
221
+ }
222
+ else if (typeof baseline === 'number' &&
223
+ baseline > 0 &&
224
+ haveUsage &&
225
+ ev.compressed === true &&
226
+ (ev.baseline_probe_status === 'ok' || ev.baseline_probe_status === undefined)) {
227
+ const cacheable = ev.baseline_cacheable_tokens ?? 0;
228
+ const prefixSha = ev.system_sha8;
229
+ const prev = warmth.get(id);
230
+ const { warm, prevCacheable } = deriveBaselineWarmth(prev, requestStartSec, cacheable, cr, CACHE_TTL_SEC, prefixSha, ev.cache_prefix_tools_sha8, { pxPrefixSha: ev.cache_prefix_sha8, model: ev.model });
231
+ const baselineEff = computeBaselineInputEffWithCacheTier(baseline, cacheable, inp, cc, cr, warm, prevCacheable, cc1h, cc5m, anthropicReadRate(ev.model));
232
+ const actualEff = computeActualInputEffWithCacheTier(inp, cc, cr, cc1h, cc5m, anthropicReadRate(ev.model));
233
+ const tokensSaved = baselineEff - actualEff;
234
+ s.tokensSavedEst += Math.round(tokensSaved);
235
+ s.charsSaved += Math.round(tokensSaved * 4);
236
+ }
237
+ else if (haveUsage &&
238
+ ev.compressed === true &&
239
+ (ev.text_hygiene_saved_tokens ?? 0) > 0 &&
240
+ (ev.image_count ?? 0) === 0) {
241
+ const hygieneTok = ev.text_hygiene_saved_tokens ?? 0;
242
+ const readRate = anthropicReadRate(ev.model);
243
+ const prev = warmth.get(id);
244
+ const { warm, prevCacheable } = deriveBaselineWarmth(prev, requestStartSec, ev.baseline_cacheable_tokens ?? 0, cr, CACHE_TTL_SEC, ev.system_sha8, ev.cache_prefix_tools_sha8, { pxPrefixSha: ev.cache_prefix_sha8, model: ev.model });
245
+ let tokensSaved;
246
+ if (warm && cr === 0) {
247
+ const actualEff = computeActualInputEffWithCacheTier(inp, cc, cr, cc1h, cc5m, readRate);
248
+ const unproxiedRaw = inp + cc + hygieneTok;
249
+ const reusedTarget = prevCacheable > 0 ? prevCacheable : (prev?.observedCachedTokens ?? 0);
250
+ if (reusedTarget > 0) {
251
+ const reused = Math.min(unproxiedRaw, reusedTarget);
252
+ const createRate = cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
253
+ const baselineEff = reused * readRate + (unproxiedRaw - reused) * createRate;
254
+ tokensSaved = baselineEff - actualEff;
255
+ }
256
+ else {
257
+ tokensSaved = hygieneTok * readRate;
258
+ }
259
+ }
260
+ else {
261
+ const deltaWeight = cr > 0
262
+ ? readRate
263
+ : cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
264
+ tokensSaved = hygieneTok * deltaWeight;
265
+ }
266
+ s.tokensSavedEst += Math.round(tokensSaved);
267
+ s.charsSaved += Math.round(tokensSaved * 4);
268
+ }
269
+ // Record this completed row's prefix for later warmth/split decisions.
270
+ // Carry prior cacheable when this row had no probe.
271
+ if (haveUsage && !isGoogle && !isOpenAI) {
272
+ const cacheable = ev.baseline_cacheable_tokens ?? 0;
273
+ const prefixSha = ev.system_sha8;
274
+ const prev = warmth.get(id);
275
+ warmth.set(id, {
276
+ ts: completionSec,
277
+ cacheable: cacheable > 0 ? cacheable : (prev?.cacheable ?? 0),
278
+ prefixSha: prefixSha ?? prev?.prefixSha,
279
+ toolsSha: ev.cache_prefix_tools_sha8 ?? prev?.toolsSha,
280
+ pxPrefixSha: ev.cache_prefix_sha8 ?? prev?.pxPrefixSha,
281
+ model: ev.model ?? prev?.model,
282
+ ttlSec: observedCacheTtlSec(ev.cache_create_1h_tokens, prev?.ttlSec),
283
+ observedCachedTokens: cr > 0 || cc > 0 ? cr + cc : prev?.observedCachedTokens,
284
+ });
285
+ }
286
+ const cacheReadEv = ev.cache_read_tokens ?? ev.cached_tokens;
287
+ if (typeof cacheReadEv === 'number') {
288
+ s.cacheReadTokens += cacheReadEv;
289
+ }
290
+ if (ev.req_body_sample_path) {
291
+ let set = sidecarsBySession.get(id);
292
+ if (!set) {
293
+ set = new Set();
294
+ sidecarsBySession.set(id, set);
295
+ }
296
+ set.add(ev.req_body_sample_path);
297
+ const size = sidecarSizes.get(ev.req_body_sample_path);
298
+ if (typeof size === 'number')
299
+ s.sidecarBytes += size;
300
+ }
301
+ }
302
+ return { sessions, sidecarsBySession };
303
+ }
304
+ /** Sort SessionSummary entries most-recent-first and apply optional filters.
305
+ * Pure: the dashboard maps query-string params straight into ListOptions. */
306
+ export function filterSessions(sessions, opts) {
307
+ return [...sessions.values()]
308
+ .filter((s) => {
309
+ if (opts.project) {
310
+ if (!s.project)
311
+ return false;
312
+ if (s.project !== opts.project &&
313
+ path.basename(s.project) !== opts.project &&
314
+ !s.project.includes(opts.project)) {
315
+ return false;
316
+ }
317
+ }
318
+ if (opts.since && s.lastSeen < opts.since)
319
+ return false;
320
+ return true;
321
+ })
322
+ .sort((a, b) => (a.lastSeen < b.lastSeen ? 1 : -1));
323
+ }
324
+ function sidecarFileSizes(dir) {
325
+ const out = new Map();
326
+ if (!fs.existsSync(dir))
327
+ return out;
328
+ let entries;
329
+ try {
330
+ entries = fs.readdirSync(dir);
331
+ }
332
+ catch {
333
+ return out;
334
+ }
335
+ for (const name of entries) {
336
+ const full = path.join(dir, name);
337
+ try {
338
+ const st = fs.statSync(full);
339
+ if (st.isFile())
340
+ out.set(full, st.size);
341
+ }
342
+ catch {
343
+ /* concurrent delete is fine */
344
+ }
345
+ }
346
+ return out;
347
+ }
348
+ /** Decide which sessions to remove based on the prune options. Pure — no
349
+ * I/O — so it's easy to unit-test against a synthetic aggregation. */
350
+ export function selectSessionsToRemove(sessions, opts, now = new Date()) {
351
+ const toRemove = new Set();
352
+ const all = [...sessions.values()];
353
+ if (opts.sessionId) {
354
+ if (sessions.has(opts.sessionId))
355
+ toRemove.add(opts.sessionId);
356
+ }
357
+ if (Array.isArray(opts.sessionIds)) {
358
+ for (const id of opts.sessionIds) {
359
+ // Silently skip unknown IDs — the client may have raced a concurrent
360
+ // prune. The report will reflect what we actually removed.
361
+ if (typeof id === 'string' && sessions.has(id))
362
+ toRemove.add(id);
363
+ }
364
+ }
365
+ if (typeof opts.olderThanDays === 'number') {
366
+ const cutoff = new Date(now.getTime() - opts.olderThanDays * 24 * 60 * 60 * 1000).toISOString();
367
+ for (const s of all) {
368
+ if (s.lastSeen < cutoff)
369
+ toRemove.add(s.id);
370
+ }
371
+ }
372
+ if (typeof opts.keepLast === 'number') {
373
+ // Most-recently-active first; everything after keepLast goes.
374
+ const sorted = [...all].sort((a, b) => (a.lastSeen < b.lastSeen ? 1 : -1));
375
+ for (const s of sorted.slice(opts.keepLast))
376
+ toRemove.add(s.id);
377
+ }
378
+ return toRemove;
379
+ }
380
+ const eventsFileCoordinators = new Map();
381
+ const rewriteLocks = new Map();
382
+ /** Register an in-process append coordinator (e.g. `FileTracker`) for `eventsFile`. */
383
+ export function registerEventsFileCoordinator(eventsFile, coordinator) {
384
+ const key = path.resolve(eventsFile);
385
+ eventsFileCoordinators.set(key, coordinator);
386
+ return () => {
387
+ if (eventsFileCoordinators.get(key) === coordinator) {
388
+ eventsFileCoordinators.delete(key);
389
+ }
390
+ };
391
+ }
392
+ export async function prune(paths, opts, now = new Date()) {
393
+ const { sessions, sidecarsBySession } = await aggregateSessions(paths);
394
+ const toRemove = selectSessionsToRemove(sessions, opts, now);
395
+ let jsonlBytesFreed = 0;
396
+ let eventsRemoved = 0;
397
+ let eventsKept = 0;
398
+ for (const s of sessions.values()) {
399
+ if (toRemove.has(s.id)) {
400
+ jsonlBytesFreed += s.jsonlBytes;
401
+ eventsRemoved += s.requestCount;
402
+ }
403
+ else {
404
+ eventsKept += s.requestCount;
405
+ }
406
+ }
407
+ // Collect sidecar paths up for deletion (and their on-disk sizes).
408
+ const sidecarsToDelete = [];
409
+ for (const id of toRemove) {
410
+ const set = sidecarsBySession.get(id);
411
+ if (!set)
412
+ continue;
413
+ for (const p of set) {
414
+ try {
415
+ const st = fs.statSync(p);
416
+ sidecarsToDelete.push({ path: p, size: st.size });
417
+ }
418
+ catch {
419
+ /* already gone — fine */
420
+ }
421
+ }
422
+ }
423
+ const sidecarBytesFreed = sidecarsToDelete.reduce((n, s) => n + s.size, 0);
424
+ const report = {
425
+ sessionsRemoved: [...toRemove],
426
+ eventsRemoved,
427
+ eventsKept,
428
+ jsonlBytesFreed,
429
+ sidecarsRemoved: sidecarsToDelete.length,
430
+ sidecarBytesFreed,
431
+ applied: false,
432
+ };
433
+ if (!opts.force)
434
+ return report;
435
+ if (toRemove.size === 0) {
436
+ report.applied = true;
437
+ return report;
438
+ }
439
+ // Atomic rewrite: stream the original through a filter into events.jsonl.tmp,
440
+ // fsync, then rename. Any partial state on crash leaves the original intact.
441
+ await rewriteEventsFile(paths.eventsFile, toRemove);
442
+ for (const { path: p } of sidecarsToDelete) {
443
+ try {
444
+ fs.unlinkSync(p);
445
+ }
446
+ catch {
447
+ /* ignore — leftover sidecars are harmless */
448
+ }
449
+ }
450
+ report.applied = true;
451
+ return report;
452
+ }
453
+ function writeFilteredLine(outFd, line, toRemove) {
454
+ const clean = line.replace(/\r?\n$/, '');
455
+ if (!clean.trim())
456
+ return;
457
+ let ev;
458
+ try {
459
+ ev = JSON.parse(clean);
460
+ }
461
+ catch {
462
+ // Preserve malformed lines so we don't silently eat data we can't parse.
463
+ fs.writeSync(outFd, clean + '\n');
464
+ return;
465
+ }
466
+ if (toRemove.has(sessionIdOf(ev)))
467
+ return;
468
+ fs.writeSync(outFd, clean + '\n');
469
+ }
470
+ async function rewriteEventsFile(eventsFile, toRemove) {
471
+ const key = path.resolve(eventsFile);
472
+ const prevLock = rewriteLocks.get(key) ?? Promise.resolve();
473
+ let release;
474
+ const currentLock = new Promise((resolve) => {
475
+ release = resolve;
476
+ });
477
+ rewriteLocks.set(key, currentLock);
478
+ await prevLock;
479
+ try {
480
+ const runRewrite = async (flushPending) => {
481
+ if (!fs.existsSync(eventsFile))
482
+ return;
483
+ const tmp = `${eventsFile}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
484
+ // Open with O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW and 0o600 permissions so pruned logs never expose prompts.
485
+ const openFlags = fs.constants.O_WRONLY |
486
+ fs.constants.O_CREAT |
487
+ fs.constants.O_EXCL |
488
+ (fs.constants.O_NOFOLLOW ?? 0);
489
+ const outFd = fs.openSync(tmp, openFlags, 0o600);
490
+ fs.fchmodSync(outFd, 0o600);
491
+ let outFdClosed = false;
492
+ let renamed = false;
493
+ try {
494
+ let streamBytes = 0;
495
+ let streamIno = null;
496
+ let streamDev = null;
497
+ const stream = fs.createReadStream(eventsFile);
498
+ stream.on('open', (rfd) => {
499
+ try {
500
+ const fst = fs.fstatSync(rfd);
501
+ streamIno = fst.ino;
502
+ streamDev = fst.dev;
503
+ }
504
+ catch {
505
+ /* ignore fstat error */
506
+ }
507
+ });
508
+ stream.on('data', (chunk) => {
509
+ streamBytes += Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk, 'utf8');
510
+ });
511
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
512
+ for await (const line of rl) {
513
+ writeFilteredLine(outFd, line, toRemove);
514
+ }
515
+ // Catch up any lines appended externally during async streaming before locking in rename.
516
+ try {
517
+ const st = fs.statSync(eventsFile);
518
+ const sameFile = streamIno === null || (st.ino === streamIno && st.dev === streamDev);
519
+ if (sameFile && st.size > streamBytes) {
520
+ const extraBuf = Buffer.allocUnsafe(st.size - streamBytes);
521
+ const rfd = fs.openSync(eventsFile, 'r');
522
+ let readTotal = 0;
523
+ try {
524
+ const fst = fs.fstatSync(rfd);
525
+ if (streamIno === null || (fst.ino === streamIno && fst.dev === streamDev)) {
526
+ while (readTotal < extraBuf.length) {
527
+ const n = fs.readSync(rfd, extraBuf, readTotal, extraBuf.length - readTotal, streamBytes + readTotal);
528
+ if (n <= 0)
529
+ break;
530
+ readTotal += n;
531
+ }
532
+ }
533
+ }
534
+ finally {
535
+ fs.closeSync(rfd);
536
+ }
537
+ if (readTotal > 0) {
538
+ const tailText = extraBuf.subarray(0, readTotal).toString('utf8');
539
+ for (const tailLine of tailText.split(/\r?\n/)) {
540
+ writeFilteredLine(outFd, tailLine, toRemove);
541
+ }
542
+ }
543
+ }
544
+ }
545
+ catch {
546
+ /* ignore stat race */
547
+ }
548
+ if (flushPending) {
549
+ flushPending(outFd, (fd, rawLine) => writeFilteredLine(fd, rawLine, toRemove));
550
+ }
551
+ fs.fsyncSync(outFd);
552
+ fs.closeSync(outFd);
553
+ outFdClosed = true;
554
+ fs.renameSync(tmp, eventsFile);
555
+ renamed = true;
556
+ fs.chmodSync(eventsFile, 0o600);
557
+ }
558
+ catch (err) {
559
+ if (!outFdClosed) {
560
+ try {
561
+ fs.closeSync(outFd);
562
+ }
563
+ catch {
564
+ /* ignore */
565
+ }
566
+ }
567
+ if (!renamed) {
568
+ try {
569
+ fs.unlinkSync(tmp);
570
+ }
571
+ catch {
572
+ /* ignore cleanup error */
573
+ }
574
+ }
575
+ throw err;
576
+ }
577
+ };
578
+ const coordinator = eventsFileCoordinators.get(key);
579
+ if (coordinator) {
580
+ await coordinator.runDuringRewrite((flushPending) => runRewrite(flushPending));
581
+ }
582
+ else {
583
+ await runRewrite();
584
+ }
585
+ }
586
+ finally {
587
+ release();
588
+ if (rewriteLocks.get(key) === currentLock) {
589
+ rewriteLocks.delete(key);
590
+ }
591
+ }
592
+ }
593
+ // ---- disk usage ------------------------------------------------------------
594
+ export function diskUsage(paths) {
595
+ let eventsJsonlBytes = 0;
596
+ try {
597
+ eventsJsonlBytes = fs.statSync(paths.eventsFile).size;
598
+ }
599
+ catch {
600
+ /* no events file — leave at 0 */
601
+ }
602
+ const sidecarSizes = sidecarFileSizes(paths.sidecarDir);
603
+ let sidecarsBytes = 0;
604
+ for (const s of sidecarSizes.values())
605
+ sidecarsBytes += s;
606
+ return {
607
+ eventsJsonlBytes,
608
+ sidecarsBytes,
609
+ sidecarCount: sidecarSizes.size,
610
+ totalBytes: eventsJsonlBytes + sidecarsBytes,
611
+ };
612
+ }
613
+ /** Path where Claude Code stores per-session JSONL transcripts. */
614
+ export function claudeProjectsDir() {
615
+ return path.join(os.homedir(), '.claude', 'projects');
616
+ }
617
+ /**
618
+ * Compute the sha256 prefix the proxy uses for `first_user_sha8` from the
619
+ * anchor text (see src/core/session-state.ts:sessionAnchorText + sha8).
620
+ * Crucially this must match exactly — same 4 KiB cap, same first-8-hex-char
621
+ * prefix — or the map will silently miss every entry.
622
+ */
623
+ export function fingerprintFirstUser(text) {
624
+ const trimmed = text.slice(0, 4096);
625
+ const hash = crypto.createHash('sha256').update(trimmed, 'utf8').digest('hex');
626
+ return hash.slice(0, 8);
627
+ }
628
+ /** Pull the session anchor text out of a single Claude Code session JSONL
629
+ * file: the text blocks of every user row before the first assistant row,
630
+ * reduced by the same `sessionAnchorText` rule the proxy applies. */
631
+ export async function readFirstUserFromClaudeSession(filePath) {
632
+ // createReadStream doesn't throw synchronously for ENOENT — the error fires
633
+ // on the 'error' event when read() starts. Pre-check with existsSync so
634
+ // we can return undefined cleanly without an unhandled rejection.
635
+ if (!fs.existsSync(filePath))
636
+ return undefined;
637
+ let stream;
638
+ try {
639
+ stream = fs.createReadStream(filePath, { encoding: 'utf8' });
640
+ }
641
+ catch {
642
+ return undefined;
643
+ }
644
+ // Defensive: still attach an error handler so a permission/race-deletion
645
+ // surface doesn't bubble out of readline's async iterator.
646
+ stream.on('error', () => {
647
+ /* swallow — the iterator will end with no rows */
648
+ });
649
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
650
+ const texts = [];
651
+ try {
652
+ for await (const line of rl) {
653
+ if (!line.trim())
654
+ continue;
655
+ let row;
656
+ try {
657
+ row = JSON.parse(line);
658
+ }
659
+ catch {
660
+ continue;
661
+ }
662
+ if (!row || typeof row !== 'object')
663
+ continue;
664
+ const r = row;
665
+ if (r.type === 'assistant')
666
+ break;
667
+ if (r.type !== 'user')
668
+ continue;
669
+ const msg = r.message;
670
+ const content = msg && typeof msg === 'object'
671
+ ? msg.content
672
+ : r.content; // Older Claude Code format: content may live at the top level.
673
+ if (typeof content === 'string') {
674
+ texts.push(content);
675
+ }
676
+ else if (Array.isArray(content)) {
677
+ for (const block of content) {
678
+ if (block &&
679
+ typeof block === 'object' &&
680
+ block.type === 'text') {
681
+ const t = block.text;
682
+ if (typeof t === 'string')
683
+ texts.push(t);
684
+ }
685
+ }
686
+ }
687
+ // First user row unreadable — give up on this file so we don't hash a
688
+ // later message and produce a wrong mapping.
689
+ if (texts.length === 0)
690
+ return undefined;
691
+ }
692
+ }
693
+ finally {
694
+ stream.close();
695
+ }
696
+ return texts.length > 0 ? sessionAnchorText(texts) : undefined;
697
+ }
698
+ /** Convert Claude Code's project directory encoding back to a path. The
699
+ * encoding is lossy (every `/`, `_`, and original `-` all become `-` in the
700
+ * directory name) so this is display-only. */
701
+ export function decodeClaudeProjectDir(name) {
702
+ if (name.startsWith('-'))
703
+ return '/' + name.slice(1).replaceAll('-', '/');
704
+ return name.replaceAll('-', '/');
705
+ }
706
+ const CLAUDE_FILE_CACHE_CAP = 4096;
707
+ const CLAUDE_DIR_CACHE_CAP = 16;
708
+ const claudeFileCache = new Map();
709
+ const claudeDirCache = new Map();
710
+ const claudeDirInFlight = new Map();
711
+ function fileSig(st) {
712
+ return `${st.ino}:${st.size}:${st.mtimeMs}`;
713
+ }
714
+ async function scanClaudeCodeMap(rootDir, cacheKey) {
715
+ const out = new Map();
716
+ let rootStat;
717
+ let projects;
718
+ try {
719
+ rootStat = fs.statSync(rootDir);
720
+ projects = fs.readdirSync(rootDir, { withFileTypes: true });
721
+ }
722
+ catch {
723
+ claudeDirCache.delete(cacheKey);
724
+ return out; // No Claude Code install or unreadable — that's fine.
725
+ }
726
+ const sigParts = [fileSig(rootStat)];
727
+ const candidates = [];
728
+ for (const proj of projects) {
729
+ if (!proj.isDirectory())
730
+ continue;
731
+ const projDir = path.join(rootDir, proj.name);
732
+ let projStat;
733
+ let sessions;
734
+ try {
735
+ projStat = fs.statSync(projDir);
736
+ sessions = fs.readdirSync(projDir);
737
+ }
738
+ catch {
739
+ continue;
740
+ }
741
+ sigParts.push(`${proj.name}:${fileSig(projStat)}`);
742
+ for (const sess of sessions) {
743
+ if (!sess.endsWith('.jsonl'))
744
+ continue;
745
+ const file = path.join(projDir, sess);
746
+ try {
747
+ const st = fs.statSync(file);
748
+ if (!st.isFile())
749
+ continue;
750
+ const fSig = fileSig(st);
751
+ sigParts.push(`${proj.name}/${sess}:${fSig}`);
752
+ candidates.push({ projName: proj.name, sess, file, fSig });
753
+ }
754
+ catch {
755
+ continue;
756
+ }
757
+ }
758
+ }
759
+ const dirSig = sigParts.join('|');
760
+ const cachedDir = claudeDirCache.get(cacheKey);
761
+ if (cachedDir && cachedDir.sig === dirSig) {
762
+ claudeDirCache.delete(cacheKey);
763
+ claudeDirCache.set(cacheKey, cachedDir);
764
+ return cachedDir.map;
765
+ }
766
+ for (const c of candidates) {
767
+ const cachedFile = claudeFileCache.get(c.file);
768
+ let firstUser;
769
+ if (cachedFile && cachedFile.sig === c.fSig) {
770
+ claudeFileCache.delete(c.file);
771
+ claudeFileCache.set(c.file, cachedFile);
772
+ firstUser = cachedFile.firstUser;
773
+ }
774
+ else {
775
+ firstUser = await readFirstUserFromClaudeSession(c.file);
776
+ if (claudeFileCache.has(c.file))
777
+ claudeFileCache.delete(c.file);
778
+ claudeFileCache.set(c.file, { sig: c.fSig, firstUser });
779
+ while (claudeFileCache.size > CLAUDE_FILE_CACHE_CAP) {
780
+ const oldest = claudeFileCache.keys().next().value;
781
+ if (oldest === undefined)
782
+ break;
783
+ claudeFileCache.delete(oldest);
784
+ }
785
+ }
786
+ if (!firstUser)
787
+ continue;
788
+ const sha8 = fingerprintFirstUser(firstUser);
789
+ // First write wins. If two sessions in different projects start with
790
+ // the same user prompt (e.g. "hi"), the first one we read keeps the
791
+ // slot — at least the dashboard shows *some* CC ref rather than none.
792
+ if (!out.has(sha8)) {
793
+ out.set(sha8, {
794
+ sessionId: c.sess.replace(/\.jsonl$/, ''),
795
+ projectPath: decodeClaudeProjectDir(c.projName),
796
+ firstUserPreview: firstUser.slice(0, 120),
797
+ });
798
+ }
799
+ }
800
+ if (claudeDirCache.has(cacheKey))
801
+ claudeDirCache.delete(cacheKey);
802
+ claudeDirCache.set(cacheKey, { sig: dirSig, map: out });
803
+ while (claudeDirCache.size > CLAUDE_DIR_CACHE_CAP) {
804
+ const oldest = claudeDirCache.keys().next().value;
805
+ if (oldest === undefined)
806
+ break;
807
+ claudeDirCache.delete(oldest);
808
+ }
809
+ return out;
810
+ }
811
+ /**
812
+ * Best-effort scan of `~/.claude/projects/*.jsonl`. Returns a map keyed by
813
+ * the same `first_user_sha8` the proxy emits. If `~/.claude/projects/` is
814
+ * missing, returns an empty map without throwing — inkling must keep
815
+ * working for non-Claude-Code clients.
816
+ *
817
+ * Cached by `(ino, size, mtimeMs)` with in-flight singleflight coalescing so
818
+ * repeated/concurrent dashboard polls avoid redundant disk scans.
819
+ */
820
+ export async function claudeCodeMap(rootDir = claudeProjectsDir()) {
821
+ const key = path.resolve(rootDir);
822
+ const inFlight = claudeDirInFlight.get(key);
823
+ if (inFlight) {
824
+ return new Map(await inFlight);
825
+ }
826
+ const p = scanClaudeCodeMap(rootDir, key);
827
+ claudeDirInFlight.set(key, p);
828
+ try {
829
+ return new Map(await p);
830
+ }
831
+ finally {
832
+ if (claudeDirInFlight.get(key) === p) {
833
+ claudeDirInFlight.delete(key);
834
+ }
835
+ }
836
+ }
837
+ //# sourceMappingURL=sessions.js.map