@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,114 @@
1
+ /**
2
+ * Aggregate metrics over a stream of TrackEvents. Pure data-layer module —
3
+ * the dashboard's `/api/stats.json` endpoint imports `aggregateEventsFile`
4
+ * + `summaryToJson` from here. There is no longer a CLI entrypoint; the
5
+ * live dashboard at http://127.0.0.1:47821/ surfaces everything this used
6
+ * to print.
7
+ *
8
+ * Node-only (uses node:fs). Streams the file line-by-line so a 100 MB log
9
+ * doesn't blow the heap. The aggregator itself (`newSummary` / `fold`) is
10
+ * pure — fed a sequence of TrackEvents and produces a Summary — so a
11
+ * Workers-side dashboard could reuse it later by extracting it into core/.
12
+ */
13
+ import type { TrackEvent } from './core/tracker.js';
14
+ export interface Summary {
15
+ total: number;
16
+ ok2xx: number;
17
+ err4xx: number;
18
+ err5xx: number;
19
+ compressed: number;
20
+ passthrough: number;
21
+ /** Sum of orig_chars across compressed requests — the bytes we removed
22
+ * from the text path by rendering to PNG. */
23
+ origCharsTotal: number;
24
+ imageBytesTotal: number;
25
+ /** Sum of pin_chars: text inkling moved out of the cacheable prefix and
26
+ * re-emitted as the tail footer. Paid at full input price every turn, so it
27
+ * is a recurring charge against the one-time imaging win above. */
28
+ pinCharsTotal: number;
29
+ /** Requests that carried a pin footer. Zero means pins cost nothing. */
30
+ pinEvents: number;
31
+ /** Aggregated Anthropic token usage. */
32
+ inputTokensTotal: number;
33
+ outputTokensTotal: number;
34
+ cacheCreateTokensTotal: number;
35
+ cacheReadTokensTotal: number;
36
+ /** Portion of `cacheReadTokensTotal` already counted inside inclusive OpenAI/Google `input_tokens`. */
37
+ inclusiveCacheReadTotal: number;
38
+ /** Measured savings, raw-token basis. Σ baseline_tokens over rows whose
39
+ * count_tokens probe is OK — the original body priced as text. */
40
+ baselineTokensTotal: number;
41
+ /** Real input-side usage (input + cache create + cache read) over the SAME
42
+ * probe-OK rows, so numerator and denominator are paired per request. The
43
+ * honest server-sourced compression is 1 − measuredActual / baseline. */
44
+ measuredActualTokensTotal: number;
45
+ /** Count of probe-OK rows contributing to the two totals above — the honest
46
+ * denominator for the measured-savings headline. */
47
+ baselineMeasuredEvents: number;
48
+ /** Number of events whose cache_read_tokens > 0 — i.e. the prompt cache
49
+ * actually hit. */
50
+ cacheHitEvents: number;
51
+ /** Number of events that carried any usage data at all. Denominator for
52
+ * cacheHitEvents. */
53
+ eventsWithUsage: number;
54
+ durationMs: number[];
55
+ firstByteMs: number[];
56
+ skipReasons: Map<string, number>;
57
+ byCwd: Map<string, {
58
+ count: number;
59
+ origChars: number;
60
+ imageBytes: number;
61
+ }>;
62
+ /** system_sha8 → number of times seen. High repeat count = cache should
63
+ * be doing its job. */
64
+ systemShaHist: Map<string, number>;
65
+ unknownTags: Map<string, number>;
66
+ /** Deterministic prefix-safe text-hygiene token/char savings. */
67
+ textHygieneSavedTokensTotal: number;
68
+ textHygieneSavedCharsTotal: number;
69
+ /** Long-context pricing cliff avoidances. */
70
+ cliffAvoidedEvents: number;
71
+ cliffSavedUsdTotal: number;
72
+ }
73
+ export declare function newSummary(): Summary;
74
+ export declare function fold(s: Summary, ev: TrackEvent): Summary;
75
+ export declare function renderTextReport(s: Summary): string;
76
+ /**
77
+ * Stream an events JSONL file and fold every row into a Summary. Returns the
78
+ * Summary plus a parsed/dropped tally so callers can detect empty/garbage
79
+ * inputs. The dashboard wraps this for the /api/stats.json endpoint.
80
+ *
81
+ * Note: this is a full re-read on every call. The dashboard already has a
82
+ * 50-event ring buffer of the *recent* slice; stats need the full history
83
+ * to compute cache-hit-rate over thousands of requests. ~1.5 MB JSONL
84
+ * streams in well under 100 ms on an SSD.
85
+ */
86
+ export declare function aggregateEventsFile(file: string): Promise<{
87
+ summary: Summary;
88
+ parsed: number;
89
+ dropped: number;
90
+ } | undefined>;
91
+ /**
92
+ * Convert a Summary to a JSON-serializable shape for the dashboard's
93
+ * /api/stats.json endpoint. JSON.stringify drops Map entries silently, so
94
+ * we materialize the top-N entries of each map into plain [key, value]
95
+ * tuples. Caps each map at 20 entries to keep the response bounded.
96
+ */
97
+ export declare function summaryToJson(s: Summary): Record<string, unknown>;
98
+ interface StatsCliResult {
99
+ code: number;
100
+ out: string;
101
+ err: string;
102
+ }
103
+ /**
104
+ * `inkling stats [--json] [--file <p>]` — summarize an events JSONL log offline,
105
+ * with NO proxy server running. The live dashboard covers the same data while
106
+ * the proxy is up; this restores after-the-fact analysis of ~/.inkling/events.jsonl
107
+ * and adds a measured-savings headline the dashboard keeps behind its HTTP API.
108
+ *
109
+ * Returns a result rather than writing streams so it stays unit-testable; the
110
+ * node entrypoint does the stdout/stderr plumbing.
111
+ */
112
+ export declare function runStats(argv: string[], defaultFile: string): Promise<StatsCliResult>;
113
+ export {};
114
+ //# sourceMappingURL=stats.d.ts.map
package/dist/stats.js ADDED
@@ -0,0 +1,439 @@
1
+ /**
2
+ * Aggregate metrics over a stream of TrackEvents. Pure data-layer module —
3
+ * the dashboard's `/api/stats.json` endpoint imports `aggregateEventsFile`
4
+ * + `summaryToJson` from here. There is no longer a CLI entrypoint; the
5
+ * live dashboard at http://127.0.0.1:47821/ surfaces everything this used
6
+ * to print.
7
+ *
8
+ * Node-only (uses node:fs). Streams the file line-by-line so a 100 MB log
9
+ * doesn't blow the heap. The aggregator itself (`newSummary` / `fold`) is
10
+ * pure — fed a sequence of TrackEvents and produces a Summary — so a
11
+ * Workers-side dashboard could reuse it later by extracting it into core/.
12
+ */
13
+ import * as fs from 'node:fs';
14
+ import * as readline from 'node:readline';
15
+ import { isUsableAnthropicBaselineProbe } from './core/baseline.js';
16
+ export function newSummary() {
17
+ return {
18
+ total: 0,
19
+ ok2xx: 0,
20
+ err4xx: 0,
21
+ err5xx: 0,
22
+ compressed: 0,
23
+ passthrough: 0,
24
+ origCharsTotal: 0,
25
+ imageBytesTotal: 0,
26
+ pinCharsTotal: 0,
27
+ pinEvents: 0,
28
+ inputTokensTotal: 0,
29
+ outputTokensTotal: 0,
30
+ cacheCreateTokensTotal: 0,
31
+ cacheReadTokensTotal: 0,
32
+ inclusiveCacheReadTotal: 0,
33
+ baselineTokensTotal: 0,
34
+ measuredActualTokensTotal: 0,
35
+ baselineMeasuredEvents: 0,
36
+ cacheHitEvents: 0,
37
+ eventsWithUsage: 0,
38
+ durationMs: [],
39
+ firstByteMs: [],
40
+ skipReasons: new Map(),
41
+ byCwd: new Map(),
42
+ systemShaHist: new Map(),
43
+ unknownTags: new Map(),
44
+ textHygieneSavedTokensTotal: 0,
45
+ textHygieneSavedCharsTotal: 0,
46
+ cliffAvoidedEvents: 0,
47
+ cliffSavedUsdTotal: 0,
48
+ };
49
+ }
50
+ const RESERVOIR_CAP = 4096;
51
+ const reservoirSeen = new WeakMap();
52
+ function reservoirSample(arr, seen, value) {
53
+ const nextSeen = seen + 1;
54
+ if (arr.length < RESERVOIR_CAP) {
55
+ arr.push(value);
56
+ }
57
+ else {
58
+ const idx = Math.floor(Math.random() * nextSeen);
59
+ if (idx < RESERVOIR_CAP)
60
+ arr[idx] = value;
61
+ }
62
+ return nextSeen;
63
+ }
64
+ export function fold(s, ev) {
65
+ s.total++;
66
+ if (ev.status >= 200 && ev.status < 300)
67
+ s.ok2xx++;
68
+ else if (ev.status >= 400 && ev.status < 500)
69
+ s.err4xx++;
70
+ else if (ev.status >= 500)
71
+ s.err5xx++;
72
+ if (ev.compressed === true) {
73
+ s.compressed++;
74
+ if (typeof ev.orig_chars === 'number')
75
+ s.origCharsTotal += ev.orig_chars;
76
+ if (typeof ev.image_bytes === 'number')
77
+ s.imageBytesTotal += ev.image_bytes;
78
+ }
79
+ else if (ev.compressed === false) {
80
+ s.passthrough++;
81
+ if (ev.reason)
82
+ s.skipReasons.set(ev.reason, (s.skipReasons.get(ev.reason) ?? 0) + 1);
83
+ }
84
+ // Outside the compressed branch on purpose: the pin footer is appended on
85
+ // both the compressed and passthrough paths, so it is charged either way.
86
+ if (typeof ev.pin_chars === 'number' && ev.pin_chars > 0) {
87
+ s.pinCharsTotal += ev.pin_chars;
88
+ s.pinEvents++;
89
+ }
90
+ let counts = reservoirSeen.get(s);
91
+ if (!counts) {
92
+ counts = { dur: s.durationMs.length, fb: s.firstByteMs.length };
93
+ reservoirSeen.set(s, counts);
94
+ }
95
+ if (typeof ev.duration_ms === 'number' && Number.isFinite(ev.duration_ms)) {
96
+ counts.dur = reservoirSample(s.durationMs, counts.dur, ev.duration_ms);
97
+ }
98
+ if (typeof ev.first_byte_ms === 'number' && Number.isFinite(ev.first_byte_ms)) {
99
+ counts.fb = reservoirSample(s.firstByteMs, counts.fb, ev.first_byte_ms);
100
+ }
101
+ const hasUsage = typeof ev.input_tokens === 'number' ||
102
+ typeof ev.cache_read_tokens === 'number' ||
103
+ typeof ev.cached_tokens === 'number' ||
104
+ typeof ev.cache_create_tokens === 'number' ||
105
+ typeof ev.output_tokens === 'number';
106
+ const isInclusiveUsage = ev.accounting_provider === 'openai' ||
107
+ ev.accounting_provider === 'google' ||
108
+ (ev.cached_tokens !== undefined && ev.cache_read_tokens === undefined);
109
+ const cacheRead = ev.cache_read_tokens ?? ev.cached_tokens ?? 0;
110
+ const inclusiveOverlap = isInclusiveUsage
111
+ ? Math.min(ev.input_tokens ?? 0, cacheRead)
112
+ : 0;
113
+ const actualInput = (ev.input_tokens ?? 0) +
114
+ (ev.cache_create_tokens ?? 0) +
115
+ cacheRead -
116
+ inclusiveOverlap;
117
+ if (hasUsage) {
118
+ s.eventsWithUsage++;
119
+ const evInput = ev.input_tokens ?? 0;
120
+ s.inputTokensTotal += evInput;
121
+ s.outputTokensTotal += ev.output_tokens ?? 0;
122
+ s.cacheCreateTokensTotal += ev.cache_create_tokens ?? 0;
123
+ s.cacheReadTokensTotal += cacheRead;
124
+ if (isInclusiveUsage && cacheRead > 0) {
125
+ s.inclusiveCacheReadTotal += Math.min(evInput, cacheRead);
126
+ }
127
+ if (cacheRead > 0)
128
+ s.cacheHitEvents++;
129
+ }
130
+ if (typeof ev.text_hygiene_saved_tokens === 'number' && ev.text_hygiene_saved_tokens > 0) {
131
+ s.textHygieneSavedTokensTotal += ev.text_hygiene_saved_tokens;
132
+ }
133
+ if (typeof ev.text_hygiene_saved_chars === 'number' && ev.text_hygiene_saved_chars > 0) {
134
+ s.textHygieneSavedCharsTotal += ev.text_hygiene_saved_chars;
135
+ }
136
+ if (typeof ev.cliff_avoided_at === 'number' && ev.cliff_avoided_at > 0) {
137
+ s.cliffAvoidedEvents++;
138
+ s.cliffSavedUsdTotal += ev.cliff_saved_usd ?? 0;
139
+ }
140
+ // Measured savings: pair count_tokens(original body) against real usage on
141
+ // the SAME row, gated on an OK probe, 2xx status, real usage, and non-passthrough.
142
+ const baseline = ev.baseline_tokens;
143
+ const probeOk = isInclusiveUsage
144
+ ? (ev.baseline_probe_status === 'ok' ||
145
+ (ev.baseline_probe_status === undefined &&
146
+ typeof baseline === 'number' &&
147
+ baseline > 0))
148
+ : isUsableAnthropicBaselineProbe({
149
+ baselineTokens: baseline,
150
+ probeStatus: ev.baseline_probe_status,
151
+ threadContinue: ev.thread_continue === true,
152
+ cacheReadTokens: cacheRead,
153
+ });
154
+ const statusOk = ev.status >= 200 && ev.status < 300;
155
+ const compressionEligible = ev.compressed === true || (ev.compressed === undefined && !ev.reason);
156
+ if (compressionEligible &&
157
+ statusOk &&
158
+ hasUsage &&
159
+ actualInput > 0 &&
160
+ typeof baseline === 'number' &&
161
+ baseline > 0 &&
162
+ probeOk) {
163
+ s.baselineTokensTotal += baseline;
164
+ s.measuredActualTokensTotal += actualInput;
165
+ s.baselineMeasuredEvents++;
166
+ }
167
+ if (ev.cwd) {
168
+ const k = ev.cwd;
169
+ const e = s.byCwd.get(k) ?? { count: 0, origChars: 0, imageBytes: 0 };
170
+ e.count++;
171
+ e.origChars += ev.orig_chars ?? 0;
172
+ e.imageBytes += ev.image_bytes ?? 0;
173
+ s.byCwd.set(k, e);
174
+ }
175
+ if (ev.system_sha8) {
176
+ s.systemShaHist.set(ev.system_sha8, (s.systemShaHist.get(ev.system_sha8) ?? 0) + 1);
177
+ }
178
+ if (ev.unknown_static_tags) {
179
+ for (const t of ev.unknown_static_tags) {
180
+ s.unknownTags.set(t, (s.unknownTags.get(t) ?? 0) + 1);
181
+ }
182
+ }
183
+ return s;
184
+ }
185
+ function percentile(sorted, p) {
186
+ if (sorted.length === 0)
187
+ return 0;
188
+ const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
189
+ return sorted[idx];
190
+ }
191
+ /** Format a number with thousands separators. Used for big token counts. */
192
+ function fmtN(n) {
193
+ return n.toLocaleString('en-US');
194
+ }
195
+ function fmtPct(num, denom) {
196
+ if (denom === 0)
197
+ return ' —';
198
+ return ((num / denom) * 100).toFixed(1).padStart(4) + '%';
199
+ }
200
+ // ---- text report ----------------------------------------------------------
201
+ export function renderTextReport(s) {
202
+ const lines = [];
203
+ const sortedDur = [...s.durationMs].sort((a, b) => a - b);
204
+ const sortedFB = [...s.firstByteMs].sort((a, b) => a - b);
205
+ lines.push('━━━ fiche stats ━━━');
206
+ lines.push('');
207
+ lines.push(`requests: ${fmtN(s.total)}`);
208
+ lines.push(` 2xx: ${fmtN(s.ok2xx).padStart(8)} ` +
209
+ `4xx: ${fmtN(s.err4xx).padStart(6)} 5xx: ${fmtN(s.err5xx).padStart(6)}`);
210
+ lines.push(` compressed: ${fmtN(s.compressed).padStart(8)} (${fmtPct(s.compressed, s.total)})`);
211
+ lines.push(` passthrough: ${fmtN(s.passthrough).padStart(8)} (${fmtPct(s.passthrough, s.total)})`);
212
+ lines.push('');
213
+ lines.push('latency (ms):');
214
+ lines.push(` duration p50=${percentile(sortedDur, 50)} p95=${percentile(sortedDur, 95)} p99=${percentile(sortedDur, 99)}`);
215
+ lines.push(` first-byte p50=${percentile(sortedFB, 50)} p95=${percentile(sortedFB, 95)} p99=${percentile(sortedFB, 99)}`);
216
+ lines.push('');
217
+ lines.push('compression:');
218
+ lines.push(` orig text rendered: ${fmtN(s.origCharsTotal)} chars`);
219
+ lines.push(` image bytes: ${fmtN(s.imageBytesTotal)} B`);
220
+ const ratio = s.origCharsTotal > 0 ? (s.imageBytesTotal / s.origCharsTotal).toFixed(3) : '—';
221
+ lines.push(` bytes/char ratio: ${ratio}`);
222
+ if (s.pinEvents > 0) {
223
+ const perTurn = Math.round(s.pinCharsTotal / s.pinEvents);
224
+ lines.push(` pin footer: ${fmtN(s.pinCharsTotal)} chars over ${fmtN(s.pinEvents)} req (~${fmtN(perTurn)}/req)`);
225
+ lines.push(' moved out of the cached prefix, so charged as fresh input every turn');
226
+ }
227
+ if (s.textHygieneSavedTokensTotal > 0) {
228
+ lines.push(` text hygiene saved: ${fmtN(s.textHygieneSavedTokensTotal)} tok (${fmtN(s.textHygieneSavedCharsTotal)} chars)`);
229
+ }
230
+ if (s.cliffAvoidedEvents > 0) {
231
+ lines.push(` cliff avoidance: ${fmtN(s.cliffAvoidedEvents)} req ($${s.cliffSavedUsdTotal.toFixed(4)} saved)`);
232
+ }
233
+ lines.push('');
234
+ lines.push('token usage:');
235
+ lines.push(` input: ${fmtN(s.inputTokensTotal).padStart(12)}`);
236
+ lines.push(` output: ${fmtN(s.outputTokensTotal).padStart(12)}`);
237
+ lines.push(` cache create: ${fmtN(s.cacheCreateTokensTotal).padStart(12)}`);
238
+ lines.push(` cache read: ${fmtN(s.cacheReadTokensTotal).padStart(12)}`);
239
+ const totalIn = Math.max(0, s.inputTokensTotal + s.cacheCreateTokensTotal + s.cacheReadTokensTotal - s.inclusiveCacheReadTotal);
240
+ lines.push(` cache hit rate (by tokens): ${fmtPct(s.cacheReadTokensTotal, totalIn)}`);
241
+ lines.push(` cache hit rate (by events): ${fmtPct(s.cacheHitEvents, s.eventsWithUsage)}`);
242
+ lines.push('');
243
+ lines.push('measured savings — raw tokens (count_tokens baseline vs real usage):');
244
+ const savedTokens = s.baselineTokensTotal - s.measuredActualTokensTotal;
245
+ lines.push(` measured requests: ${fmtN(s.baselineMeasuredEvents).padStart(12)}`);
246
+ lines.push(` baseline tokens: ${fmtN(s.baselineTokensTotal).padStart(12)}`);
247
+ lines.push(` actual tokens: ${fmtN(s.measuredActualTokensTotal).padStart(12)}`);
248
+ lines.push(` saved: ${fmtN(savedTokens).padStart(12)} (${fmtPct(savedTokens, s.baselineTokensTotal)})`);
249
+ // Raw-token basis: cache reads counted at face value, NOT cost-weighted, so
250
+ // this % is deliberately a different quantity from the dashboard's
251
+ // cost-weighted saved_pct. Naming it out here prevents "the CLI disagrees
252
+ // with the dashboard" confusion when the two numbers differ.
253
+ lines.push(' (raw-token basis: cache reads at face value, not cost-weighted —');
254
+ lines.push(' differs from the dashboard\'s cost-weighted saved %)');
255
+ if (s.baselineMeasuredEvents === 0) {
256
+ lines.push(' (no probe-measured requests yet — savings unknown, not zero)');
257
+ }
258
+ lines.push('');
259
+ if (s.skipReasons.size > 0) {
260
+ lines.push('top skip reasons:');
261
+ const top = [...s.skipReasons.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5);
262
+ for (const [reason, count] of top) {
263
+ lines.push(` ${count.toString().padStart(6)} ${reason}`);
264
+ }
265
+ lines.push('');
266
+ }
267
+ if (s.byCwd.size > 0) {
268
+ lines.push('top working dirs (by request count):');
269
+ const top = [...s.byCwd.entries()].sort((a, b) => b[1].count - a[1].count).slice(0, 10);
270
+ for (const [cwd, e] of top) {
271
+ const cratio = e.origChars > 0 ? (e.imageBytes / e.origChars).toFixed(2) : '—';
272
+ lines.push(` ${e.count.toString().padStart(6)} ratio=${cratio} ${cwd}`);
273
+ }
274
+ lines.push('');
275
+ }
276
+ if (s.systemShaHist.size > 0) {
277
+ lines.push('top system prompts (system_sha8, high count = cache reuse):');
278
+ const top = [...s.systemShaHist.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5);
279
+ for (const [sha, count] of top) {
280
+ lines.push(` ${count.toString().padStart(6)} ${sha}`);
281
+ }
282
+ const unique = s.systemShaHist.size;
283
+ const reuseRate = s.total > 0 ? (((s.total - unique) / s.total) * 100).toFixed(1) : '—';
284
+ lines.push(` unique prompts: ${unique} reuse rate: ${reuseRate}%`);
285
+ lines.push('');
286
+ }
287
+ if (s.unknownTags.size > 0) {
288
+ lines.push('⚠ unknown tag-shaped blocks observed in static slab:');
289
+ const top = [...s.unknownTags.entries()].sort((a, b) => b[1] - a[1]);
290
+ for (const [tag, count] of top) {
291
+ lines.push(` ${count.toString().padStart(6)} <${tag}>`);
292
+ }
293
+ lines.push(' → consider adding these to DYNAMIC_BLOCK_TAGS in src/core/transform.ts');
294
+ lines.push('');
295
+ }
296
+ return lines.join('\n');
297
+ }
298
+ // ---- file-backed aggregation (used by the dashboard) ----------------------
299
+ /**
300
+ * Stream an events JSONL file and fold every row into a Summary. Returns the
301
+ * Summary plus a parsed/dropped tally so callers can detect empty/garbage
302
+ * inputs. The dashboard wraps this for the /api/stats.json endpoint.
303
+ *
304
+ * Note: this is a full re-read on every call. The dashboard already has a
305
+ * 50-event ring buffer of the *recent* slice; stats need the full history
306
+ * to compute cache-hit-rate over thousands of requests. ~1.5 MB JSONL
307
+ * streams in well under 100 ms on an SSD.
308
+ */
309
+ export async function aggregateEventsFile(file) {
310
+ if (!fs.existsSync(file))
311
+ return undefined;
312
+ const stream = fs.createReadStream(file, { encoding: 'utf8' });
313
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
314
+ const summary = newSummary();
315
+ let parsed = 0;
316
+ let dropped = 0;
317
+ for await (const line of rl) {
318
+ if (!line.trim())
319
+ continue;
320
+ try {
321
+ const ev = JSON.parse(line);
322
+ fold(summary, ev);
323
+ parsed++;
324
+ }
325
+ catch {
326
+ dropped++;
327
+ }
328
+ }
329
+ return { summary, parsed, dropped };
330
+ }
331
+ /**
332
+ * Convert a Summary to a JSON-serializable shape for the dashboard's
333
+ * /api/stats.json endpoint. JSON.stringify drops Map entries silently, so
334
+ * we materialize the top-N entries of each map into plain [key, value]
335
+ * tuples. Caps each map at 20 entries to keep the response bounded.
336
+ */
337
+ export function summaryToJson(s) {
338
+ const topN = (m, scoreOf, n = 20) => [...m.entries()].sort((a, b) => scoreOf(b[1]) - scoreOf(a[1])).slice(0, n);
339
+ const sortedDur = [...s.durationMs].sort((a, b) => a - b);
340
+ const sortedFB = [...s.firstByteMs].sort((a, b) => a - b);
341
+ return {
342
+ total: s.total,
343
+ ok2xx: s.ok2xx,
344
+ err4xx: s.err4xx,
345
+ err5xx: s.err5xx,
346
+ compressed: s.compressed,
347
+ passthrough: s.passthrough,
348
+ origCharsTotal: s.origCharsTotal,
349
+ imageBytesTotal: s.imageBytesTotal,
350
+ pinCharsTotal: s.pinCharsTotal,
351
+ pinEvents: s.pinEvents,
352
+ inputTokensTotal: s.inputTokensTotal,
353
+ outputTokensTotal: s.outputTokensTotal,
354
+ cacheCreateTokensTotal: s.cacheCreateTokensTotal,
355
+ cacheReadTokensTotal: s.cacheReadTokensTotal,
356
+ inclusiveCacheReadTotal: s.inclusiveCacheReadTotal,
357
+ baselineTokensTotal: s.baselineTokensTotal,
358
+ measuredActualTokensTotal: s.measuredActualTokensTotal,
359
+ baselineMeasuredEvents: s.baselineMeasuredEvents,
360
+ savedTokensTotal: s.baselineTokensTotal - s.measuredActualTokensTotal,
361
+ cacheHitEvents: s.cacheHitEvents,
362
+ eventsWithUsage: s.eventsWithUsage,
363
+ textHygieneSavedTokensTotal: s.textHygieneSavedTokensTotal,
364
+ textHygieneSavedCharsTotal: s.textHygieneSavedCharsTotal,
365
+ cliffAvoidedEvents: s.cliffAvoidedEvents,
366
+ cliffSavedUsdTotal: s.cliffSavedUsdTotal,
367
+ durationP50: percentile(sortedDur, 50),
368
+ durationP95: percentile(sortedDur, 95),
369
+ firstByteP50: percentile(sortedFB, 50),
370
+ firstByteP95: percentile(sortedFB, 95),
371
+ skipReasons: topN(s.skipReasons, (v) => v),
372
+ byCwd: topN(s.byCwd, (v) => v.count),
373
+ systemShaHist: topN(s.systemShaHist, (v) => v),
374
+ unknownTags: topN(s.unknownTags, (v) => v),
375
+ };
376
+ }
377
+ // ---- offline CLI (`inkling stats`) -----------------------------------------
378
+ const FLAG_JSON = '--json';
379
+ const FLAG_FILE = '--file';
380
+ const FLAGS_HELP = new Set(['-h', '--help']);
381
+ /** Exit codes: file missing vs empty are distinct so scripts can branch. */
382
+ const EXIT_OK = 0;
383
+ const EXIT_NO_FILE = 1;
384
+ const EXIT_NO_EVENTS = 2;
385
+ const STATS_HELP = `fiche stats — offline summary of the events JSONL (no proxy server)
386
+
387
+ Usage:
388
+ fiche stats report from $FICHE_LOG (default ~/.fiche/events.jsonl)
389
+ fiche stats --json same aggregate as machine-readable JSON
390
+ fiche stats --file <path> read a specific events log
391
+
392
+ Exit codes:
393
+ 0 report printed
394
+ 1 events file not found
395
+ 2 file present but no valid events`;
396
+ function parseStatsArgs(argv, defaultFile) {
397
+ let file = defaultFile;
398
+ let json = false;
399
+ for (let i = 0; i < argv.length; i++) {
400
+ const a = argv[i];
401
+ if (a === FLAG_JSON)
402
+ json = true;
403
+ else if (a === FLAG_FILE)
404
+ file = argv[++i] ?? file;
405
+ }
406
+ return { file, json };
407
+ }
408
+ /**
409
+ * `inkling stats [--json] [--file <p>]` — summarize an events JSONL log offline,
410
+ * with NO proxy server running. The live dashboard covers the same data while
411
+ * the proxy is up; this restores after-the-fact analysis of ~/.inkling/events.jsonl
412
+ * and adds a measured-savings headline the dashboard keeps behind its HTTP API.
413
+ *
414
+ * Returns a result rather than writing streams so it stays unit-testable; the
415
+ * node entrypoint does the stdout/stderr plumbing.
416
+ */
417
+ export async function runStats(argv, defaultFile) {
418
+ if (argv.some((a) => FLAGS_HELP.has(a))) {
419
+ return { code: EXIT_OK, out: STATS_HELP, err: '' };
420
+ }
421
+ const { file, json } = parseStatsArgs(argv, defaultFile);
422
+ const agg = await aggregateEventsFile(file);
423
+ if (agg === undefined) {
424
+ return {
425
+ code: EXIT_NO_FILE,
426
+ out: '',
427
+ err: `events file not found: ${file}\n(run fiche and send a request first, or set FICHE_LOG)`,
428
+ };
429
+ }
430
+ if (agg.parsed === 0) {
431
+ return { code: EXIT_NO_EVENTS, out: '', err: `no valid events in ${file}` };
432
+ }
433
+ const dropNote = agg.dropped > 0 ? `(${agg.dropped} unparseable line(s) skipped)` : '';
434
+ const out = json
435
+ ? JSON.stringify(summaryToJson(agg.summary), null, 2)
436
+ : renderTextReport(agg.summary);
437
+ return { code: EXIT_OK, out, err: dropNote };
438
+ }
439
+ //# sourceMappingURL=stats.js.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Fast, zero-token-overhead per-turn and session savings reporter.
3
+ * Reads the tail of `~/.inkling/events.jsonl` in <5ms so IDE/CLI plugins,
4
+ * hooks, status bars, and MCP tools can surface live savings without sending
5
+ * extra turns to the LLM.
6
+ *
7
+ * Node-only (`node:fs`, `node:os`, `node:path`).
8
+ */
9
+ import type { TrackEvent } from './core/tracker.js';
10
+ export type TurnReportFormat = 'cli' | 'agy' | 'claude-statusline' | 'json';
11
+ export interface TurnSavingsSnapshot {
12
+ readonly ts: string;
13
+ readonly model?: string;
14
+ readonly status: number;
15
+ readonly basis: 'measured' | 'estimated';
16
+ readonly savedTokens: number;
17
+ readonly savedUsd: number;
18
+ readonly cacheHitPct: number | null;
19
+ readonly stages: readonly string[];
20
+ readonly cliffAvoidedAt?: number;
21
+ readonly cliffSavedUsd?: number;
22
+ readonly inputTokens: number;
23
+ readonly cachedTokens: number;
24
+ readonly sessionId?: string;
25
+ }
26
+ export interface SessionSavingsRollup {
27
+ readonly sessionId: string | null;
28
+ readonly turns: number;
29
+ readonly compressedTurns: number;
30
+ readonly savedTokens: number;
31
+ readonly savedUsd: number;
32
+ readonly cliffSavedUsd: number;
33
+ readonly avgCacheHitPct: number | null;
34
+ }
35
+ export interface TurnReportPayload {
36
+ readonly eventsFile: string;
37
+ readonly hasNewTurn: boolean;
38
+ readonly lastTurn: TurnSavingsSnapshot | null;
39
+ readonly session: SessionSavingsRollup;
40
+ }
41
+ export interface ReadTurnReportOptions {
42
+ readonly cursorFile?: string;
43
+ readonly updateCursor?: boolean;
44
+ readonly maxTailBytes?: number;
45
+ }
46
+ /** Compute deterministic token, cache-hit, and USD savings for one TrackEvent. */
47
+ export declare function computeTurnSnapshot(ev: TrackEvent): TurnSavingsSnapshot;
48
+ /** Read latest turn + session rollup from `eventsFile` with optional cursor de-duplication. */
49
+ export declare function readTurnReport(eventsFile: string, opts?: ReadTurnReportOptions): TurnReportPayload;
50
+ /** Markdown summary suitable for Antigravity `metadata.user_markdown`. */
51
+ export declare function formatTurnReportMarkdown(payload: TurnReportPayload): string;
52
+ /** Antigravity `PostInvocation` hook JSON output (zero LLM tokens via empty `systemMessage`). */
53
+ export declare function formatAgyHookJson(payload: TurnReportPayload): Record<string, unknown>;
54
+ /** Compact single-line output for Claude Code `statusLine`. */
55
+ export declare function formatClaudeStatusLine(payload: TurnReportPayload): string;
56
+ /** Compact single-line CLI output (optionally ANSI colored). */
57
+ export declare function formatCliLine(payload: TurnReportPayload, color?: boolean): string;
58
+ export declare function defaultEventsFilePath(): string;
59
+ /** CLI runner for `fiche turn-report`. */
60
+ export declare function runTurnReportCli(argv: readonly string[], defaultEventsFile: string): {
61
+ code: number;
62
+ out: string;
63
+ err: string;
64
+ };
65
+ //# sourceMappingURL=turn-report.d.ts.map