@sriinnu/fiche 0.18.0-bootstrap.0 → 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.
- package/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +289 -0
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +115 -3
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,724 @@
|
|
|
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 * as crypto from 'node:crypto';
|
|
10
|
+
import * as fs from 'node:fs';
|
|
11
|
+
import * as os from 'node:os';
|
|
12
|
+
import * as path from 'node:path';
|
|
13
|
+
import { computeActualInputEffWithCacheTier, computeBaselineInputEffWithCacheTier, deriveBaselineWarmth, isUsableAnthropicBaselineProbe, observedCacheTtlSec, } from './core/baseline.js';
|
|
14
|
+
import { readBrandEnv } from './core/env.js';
|
|
15
|
+
import { computeOpenAIActualInputEff, computeOpenAISessionBaselineInputEff, deriveOpenAIBaselineWarmth, OPENAI_CACHE_TTL_SEC, } from './core/openai-savings.js';
|
|
16
|
+
import { anthropicReadRate, inputUsdPerMtok, priceMode, resolvePriceRates } from './core/pricing.js';
|
|
17
|
+
const ASSUMED_INPUT_USD_PER_MTOK = 10.0;
|
|
18
|
+
const DEFAULT_MAX_TAIL_BYTES = 2 * 1024 * 1024;
|
|
19
|
+
const SESSION_FALLBACK_WINDOW_MS = 30 * 60 * 1000;
|
|
20
|
+
function round1(n) {
|
|
21
|
+
return Math.round(n * 10) / 10;
|
|
22
|
+
}
|
|
23
|
+
function round6(n) {
|
|
24
|
+
return Math.round(n * 1e6) / 1e6;
|
|
25
|
+
}
|
|
26
|
+
function isInferenceEvent(ev) {
|
|
27
|
+
if (!ev || typeof ev !== 'object')
|
|
28
|
+
return false;
|
|
29
|
+
if (typeof ev.ts !== 'string' || typeof ev.status !== 'number')
|
|
30
|
+
return false;
|
|
31
|
+
if (ev.status < 200 || ev.status >= 300)
|
|
32
|
+
return false;
|
|
33
|
+
if (typeof ev.path === 'string' && (ev.path.includes('count_tokens') || ev.path.includes('countTokens'))) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
return (ev.compressed === true ||
|
|
37
|
+
(ev.text_hygiene_saved_tokens ?? 0) > 0 ||
|
|
38
|
+
(ev.input_tokens ?? 0) > 0 ||
|
|
39
|
+
(ev.cache_read_tokens ?? 0) > 0 ||
|
|
40
|
+
(ev.cached_tokens ?? 0) > 0);
|
|
41
|
+
}
|
|
42
|
+
function computeTurnSnapshotWithCache(ev, rateCache, warmthState) {
|
|
43
|
+
const isGoogle = ev.accounting_provider === 'google' ||
|
|
44
|
+
(typeof ev.path === 'string' &&
|
|
45
|
+
(ev.path.includes('google-ai-studio') || ev.path.toLowerCase().includes('generatecontent')));
|
|
46
|
+
const isOpenAI = ev.accounting_provider === 'openai' ||
|
|
47
|
+
(!isGoogle &&
|
|
48
|
+
typeof ev.path === 'string' &&
|
|
49
|
+
(ev.path.includes('responses') || ev.path.includes('chat/completions')));
|
|
50
|
+
const isInclusiveUsage = isOpenAI ||
|
|
51
|
+
isGoogle ||
|
|
52
|
+
(ev.cached_tokens !== undefined && ev.cache_read_tokens === undefined);
|
|
53
|
+
const inp = ev.input_tokens ?? 0;
|
|
54
|
+
const cc = ev.cache_create_tokens ?? 0;
|
|
55
|
+
const cc5m = ev.cache_create_5m_tokens;
|
|
56
|
+
const cc1h = ev.cache_create_1h_tokens ?? 0;
|
|
57
|
+
const cr = ev.cache_read_tokens ?? 0;
|
|
58
|
+
const cacheWrite = ev.cache_write_tokens ?? 0;
|
|
59
|
+
const rawCached = ev.cached_tokens ?? ev.cache_read_tokens ?? 0;
|
|
60
|
+
const cachedTokens = isInclusiveUsage ? Math.max(0, Math.min(inp, rawCached)) : cr;
|
|
61
|
+
const inputTokens = isInclusiveUsage ? inp : inp + cc + cr;
|
|
62
|
+
const parsedMs = Date.parse(ev.ts);
|
|
63
|
+
const eventMs = Number.isFinite(parsedMs) ? parsedMs : Date.now();
|
|
64
|
+
const completionSec = eventMs / 1000;
|
|
65
|
+
const requestStartSec = completionSec - Math.max(0, ev.duration_ms || 0) / 1000;
|
|
66
|
+
const hasMeasuredBaseline = ev.compressed !== false &&
|
|
67
|
+
ev.baseline_probe_status === 'ok' &&
|
|
68
|
+
typeof ev.baseline_tokens === 'number' &&
|
|
69
|
+
ev.baseline_tokens > 0 &&
|
|
70
|
+
inputTokens > 0 &&
|
|
71
|
+
(isOpenAI ||
|
|
72
|
+
isGoogle ||
|
|
73
|
+
isUsableAnthropicBaselineProbe({
|
|
74
|
+
baselineTokens: ev.baseline_tokens,
|
|
75
|
+
probeStatus: ev.baseline_probe_status,
|
|
76
|
+
threadContinue: ev.thread_continue === true,
|
|
77
|
+
cacheReadTokens: cr,
|
|
78
|
+
}));
|
|
79
|
+
const hygieneTok = Math.max(0, ev.text_hygiene_saved_tokens ?? 0);
|
|
80
|
+
const baselineImaged = ev.baseline_imaged_tokens ?? Math.round((ev.compressed_chars ?? 0) / 4);
|
|
81
|
+
const nativeTok = Math.max(0, ev.native_injected_tokens ?? 0);
|
|
82
|
+
const imageTok = ev.image_tokens ?? 0;
|
|
83
|
+
const imgSaved = ev.compressed ? baselineImaged - imageTok - nativeTok : 0;
|
|
84
|
+
const savedTokens = hasMeasuredBaseline
|
|
85
|
+
? Math.round((ev.baseline_tokens ?? 0) - inputTokens)
|
|
86
|
+
: Math.round(hygieneTok + imgSaved);
|
|
87
|
+
let weightedSaved = 0;
|
|
88
|
+
if (isOpenAI) {
|
|
89
|
+
const pxSha = ev.cache_prefix_sha8 ?? ev.history_image_sha8;
|
|
90
|
+
const oPrev = warmthState?.openai;
|
|
91
|
+
const oWarmth = deriveOpenAIBaselineWarmth(oPrev, requestStartSec, cachedTokens, ev.system_sha8, ev.model, OPENAI_CACHE_TTL_SEC, pxSha);
|
|
92
|
+
const priceCtx = { promptTokens: inp, at: eventMs };
|
|
93
|
+
const actualEff = inp > 0
|
|
94
|
+
? computeOpenAIActualInputEff(inp, cachedTokens, ev.model, cacheWrite, priceCtx)
|
|
95
|
+
: 0;
|
|
96
|
+
if (hasMeasuredBaseline) {
|
|
97
|
+
const rates = resolvePriceRates(ev.model, priceCtx);
|
|
98
|
+
if (oWarmth.selfBusted) {
|
|
99
|
+
const unproxiedRaw = Math.max(0, ev.baseline_tokens);
|
|
100
|
+
const reused = Math.min(unproxiedRaw, oWarmth.prevPrefixTokens);
|
|
101
|
+
const newRate = cacheWrite > 0 ? rates.write : 1;
|
|
102
|
+
const baselineEff = reused * rates.read + (unproxiedRaw - reused) * newRate;
|
|
103
|
+
weightedSaved = baselineEff - actualEff;
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
const deltaWeight = cachedTokens > 0 ? rates.read : cacheWrite > 0 ? rates.write : 1;
|
|
107
|
+
weightedSaved = (ev.baseline_tokens - inp) * deltaWeight;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (inp > 0 &&
|
|
111
|
+
((ev.compressed && (baselineImaged > 0 || (ev.compressed_chars ?? 0) > 0)) || hygieneTok > 0)) {
|
|
112
|
+
const baselineEff = computeOpenAISessionBaselineInputEff({
|
|
113
|
+
inputTokens: inp,
|
|
114
|
+
cachedTokens,
|
|
115
|
+
imageTokens: ev.compressed ? imageTok : 0,
|
|
116
|
+
baselineImagedTokens: ev.compressed ? baselineImaged : 0,
|
|
117
|
+
nativeInjectedTokens: ev.compressed ? nativeTok : 0,
|
|
118
|
+
textHygieneSavedTokens: hygieneTok,
|
|
119
|
+
cacheWriteTokens: cacheWrite,
|
|
120
|
+
model: ev.model,
|
|
121
|
+
warmth: oWarmth,
|
|
122
|
+
});
|
|
123
|
+
weightedSaved = baselineEff - actualEff;
|
|
124
|
+
}
|
|
125
|
+
else if (hygieneTok > 0 || imgSaved !== 0) {
|
|
126
|
+
weightedSaved = savedTokens;
|
|
127
|
+
}
|
|
128
|
+
if (warmthState && inputTokens > 0) {
|
|
129
|
+
warmthState.openai = {
|
|
130
|
+
ts: completionSec,
|
|
131
|
+
cachedOrPrefixTokens: cachedTokens > 0 ? cachedTokens : Math.max(oPrev?.cachedOrPrefixTokens ?? 0, inp),
|
|
132
|
+
prefixSha: ev.system_sha8 ?? oPrev?.prefixSha,
|
|
133
|
+
pxPrefixSha: pxSha ?? oPrev?.pxPrefixSha,
|
|
134
|
+
model: ev.model ?? oPrev?.model,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
else if (isGoogle) {
|
|
139
|
+
const pxSha = ev.cache_prefix_sha8 ?? ev.history_image_sha8;
|
|
140
|
+
const gPrev = warmthState?.google;
|
|
141
|
+
const gWarmth = deriveOpenAIBaselineWarmth(gPrev
|
|
142
|
+
? {
|
|
143
|
+
ts: gPrev.ts,
|
|
144
|
+
cachedOrPrefixTokens: gPrev.cachedTokens,
|
|
145
|
+
prefixSha: gPrev.prefixSha,
|
|
146
|
+
pxPrefixSha: gPrev.pxPrefixSha,
|
|
147
|
+
model: gPrev.model,
|
|
148
|
+
}
|
|
149
|
+
: undefined, requestStartSec, cachedTokens, ev.system_sha8, ev.model, 300, pxSha);
|
|
150
|
+
const priceCtx = { promptTokens: inp, at: eventMs };
|
|
151
|
+
const rates = resolvePriceRates(ev.model, priceCtx);
|
|
152
|
+
if (priceMode() === 'kosha') {
|
|
153
|
+
if (gWarmth.selfBusted &&
|
|
154
|
+
inp > 0 &&
|
|
155
|
+
(hasMeasuredBaseline || (ev.compressed && baselineImaged > 0) || hygieneTok > 0)) {
|
|
156
|
+
const unproxiedRaw = Math.max(0, hasMeasuredBaseline ? ev.baseline_tokens : inp + savedTokens);
|
|
157
|
+
const reused = Math.min(unproxiedRaw, gWarmth.prevPrefixTokens);
|
|
158
|
+
const baselineEff = reused * rates.read + (unproxiedRaw - reused) * 1.0;
|
|
159
|
+
const actualEff = (inp - cachedTokens) + cachedTokens * rates.read;
|
|
160
|
+
weightedSaved = baselineEff - actualEff;
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
weightedSaved = savedTokens * (cachedTokens > 0 ? rates.read : 1.0);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
weightedSaved = savedTokens;
|
|
168
|
+
}
|
|
169
|
+
if (warmthState && inputTokens > 0) {
|
|
170
|
+
warmthState.google = {
|
|
171
|
+
ts: completionSec,
|
|
172
|
+
cachedTokens: cachedTokens > 0 ? cachedTokens : Math.max(gPrev?.cachedTokens ?? 0, inp),
|
|
173
|
+
prefixSha: ev.system_sha8 ?? gPrev?.prefixSha,
|
|
174
|
+
pxPrefixSha: pxSha ?? gPrev?.pxPrefixSha,
|
|
175
|
+
model: ev.model ?? gPrev?.model,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const readRate = anthropicReadRate(ev.model, { promptTokens: inputTokens, at: eventMs });
|
|
181
|
+
const actualEff = inputTokens > 0
|
|
182
|
+
? computeActualInputEffWithCacheTier(inp, cc, cr, cc1h, cc5m, readRate)
|
|
183
|
+
: 0;
|
|
184
|
+
const cacheable = ev.baseline_cacheable_tokens ?? 0;
|
|
185
|
+
const aPrev = warmthState?.anthropic;
|
|
186
|
+
const { warm, prevCacheable } = deriveBaselineWarmth(aPrev, requestStartSec, cacheable, cr, 300, ev.system_sha8, ev.cache_prefix_tools_sha8, { pxPrefixSha: ev.cache_prefix_sha8, model: ev.model });
|
|
187
|
+
if (hasMeasuredBaseline) {
|
|
188
|
+
if (cacheable > 0) {
|
|
189
|
+
const baselineEff = computeBaselineInputEffWithCacheTier(ev.baseline_tokens, cacheable, inp, cc, cr, warm, prevCacheable, cc1h, cc5m, readRate);
|
|
190
|
+
weightedSaved = baselineEff - actualEff;
|
|
191
|
+
}
|
|
192
|
+
else if (cc === 0 && cr === 0) {
|
|
193
|
+
weightedSaved = ev.baseline_tokens - inp;
|
|
194
|
+
}
|
|
195
|
+
else if (warm && cr === 0) {
|
|
196
|
+
const unproxiedRaw = ev.baseline_tokens;
|
|
197
|
+
const reusedTarget = warmthState?.anthropicObservedPrefix ?? 0;
|
|
198
|
+
const reused = Math.min(unproxiedRaw, reusedTarget);
|
|
199
|
+
const createRate = cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
|
|
200
|
+
const baselineEff = reused * readRate + (unproxiedRaw - reused) * createRate;
|
|
201
|
+
weightedSaved = baselineEff - actualEff;
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
weightedSaved = 0;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
else if (savedTokens !== 0 && inputTokens > 0) {
|
|
208
|
+
if (warm && cr === 0) {
|
|
209
|
+
const unproxiedRaw = inp + cc + savedTokens;
|
|
210
|
+
const reusedTarget = prevCacheable > 0 ? prevCacheable : (warmthState?.anthropicObservedPrefix ?? 0);
|
|
211
|
+
if (reusedTarget > 0) {
|
|
212
|
+
const reused = Math.min(unproxiedRaw, reusedTarget);
|
|
213
|
+
const createRate = cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
|
|
214
|
+
const baselineEff = reused * readRate + (unproxiedRaw - reused) * createRate;
|
|
215
|
+
weightedSaved = baselineEff - actualEff;
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
weightedSaved = savedTokens * readRate;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
const deltaWeight = cr > 0
|
|
223
|
+
? readRate
|
|
224
|
+
: cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
|
|
225
|
+
weightedSaved = savedTokens * deltaWeight;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
weightedSaved = savedTokens;
|
|
230
|
+
}
|
|
231
|
+
if (warmthState && inputTokens > 0) {
|
|
232
|
+
warmthState.anthropic = {
|
|
233
|
+
ts: completionSec,
|
|
234
|
+
cacheable: cacheable > 0 ? cacheable : (aPrev?.cacheable ?? 0),
|
|
235
|
+
prefixSha: ev.system_sha8 ?? aPrev?.prefixSha,
|
|
236
|
+
toolsSha: ev.cache_prefix_tools_sha8 ?? aPrev?.toolsSha,
|
|
237
|
+
pxPrefixSha: ev.cache_prefix_sha8 ?? aPrev?.pxPrefixSha,
|
|
238
|
+
model: ev.model ?? aPrev?.model,
|
|
239
|
+
ttlSec: observedCacheTtlSec(cc1h, aPrev?.ttlSec),
|
|
240
|
+
};
|
|
241
|
+
if (cr > 0 || cc > 0) {
|
|
242
|
+
warmthState.anthropicObservedPrefix = cr + cc;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const cacheHitPct = inputTokens > 0 ? round1((cachedTokens / inputTokens) * 100) : null;
|
|
247
|
+
const mode = priceMode();
|
|
248
|
+
const modelKey = `${mode}:${isGoogle ? 'g' : 'o'}:${ev.model ?? ''}:${inputTokens}`;
|
|
249
|
+
let rates = rateCache?.get(modelKey);
|
|
250
|
+
if (!rates) {
|
|
251
|
+
rates = {
|
|
252
|
+
inUsd: mode === 'kosha'
|
|
253
|
+
? inputUsdPerMtok(ev.model, { promptTokens: inputTokens, at: eventMs })
|
|
254
|
+
: (!isGoogle ? ASSUMED_INPUT_USD_PER_MTOK : undefined),
|
|
255
|
+
};
|
|
256
|
+
rateCache?.set(modelKey, rates);
|
|
257
|
+
}
|
|
258
|
+
const cliffUsd = ev.cliff_saved_usd ?? 0;
|
|
259
|
+
const tokUsd = rates.inUsd !== undefined ? (weightedSaved * rates.inUsd) / 1_000_000 : 0;
|
|
260
|
+
const savedUsd = round6(tokUsd < 0 ? tokUsd : (cliffUsd > 0 ? Math.max(tokUsd, cliffUsd) : tokUsd));
|
|
261
|
+
const stageSet = new Set();
|
|
262
|
+
if (ev.compressed && (ev.image_count ?? 0) > 0)
|
|
263
|
+
stageSet.add('image');
|
|
264
|
+
if (Array.isArray(ev.text_hygiene_stages)) {
|
|
265
|
+
for (const s of ev.text_hygiene_stages) {
|
|
266
|
+
if (typeof s === 'string' && s.length > 0)
|
|
267
|
+
stageSet.add(s);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return {
|
|
271
|
+
ts: ev.ts,
|
|
272
|
+
...(ev.model ? { model: ev.model } : {}),
|
|
273
|
+
status: ev.status,
|
|
274
|
+
basis: hasMeasuredBaseline ? 'measured' : 'estimated',
|
|
275
|
+
savedTokens,
|
|
276
|
+
savedUsd,
|
|
277
|
+
cacheHitPct,
|
|
278
|
+
stages: [...stageSet],
|
|
279
|
+
...(ev.cliff_avoided_at !== undefined ? { cliffAvoidedAt: ev.cliff_avoided_at } : {}),
|
|
280
|
+
...(cliffUsd > 0 ? { cliffSavedUsd: round6(cliffUsd) } : {}),
|
|
281
|
+
inputTokens,
|
|
282
|
+
cachedTokens,
|
|
283
|
+
...(ev.first_user_sha8 ? { sessionId: ev.first_user_sha8 } : {}),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
/** Compute deterministic token, cache-hit, and USD savings for one TrackEvent. */
|
|
287
|
+
export function computeTurnSnapshot(ev) {
|
|
288
|
+
return computeTurnSnapshotWithCache(ev);
|
|
289
|
+
}
|
|
290
|
+
function emptyRollup(sessionId = null) {
|
|
291
|
+
return {
|
|
292
|
+
sessionId,
|
|
293
|
+
turns: 0,
|
|
294
|
+
compressedTurns: 0,
|
|
295
|
+
savedTokens: 0,
|
|
296
|
+
savedUsd: 0,
|
|
297
|
+
cliffSavedUsd: 0,
|
|
298
|
+
avgCacheHitPct: null,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
// Bound turn-report reads to the trailing byte window and drop any split leading line.
|
|
302
|
+
function readTailBuffer(filePath, maxTailBytes) {
|
|
303
|
+
let fd;
|
|
304
|
+
try {
|
|
305
|
+
fd = fs.openSync(filePath, 'r');
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const stat = fs.fstatSync(fd);
|
|
312
|
+
if (!stat.isFile() || stat.size <= 0) {
|
|
313
|
+
return { buf: Buffer.alloc(0), startOffset: 0, size: 0, truncatedHead: false };
|
|
314
|
+
}
|
|
315
|
+
const bytesToRead = Math.min(stat.size, maxTailBytes);
|
|
316
|
+
let start = Math.max(0, stat.size - bytesToRead);
|
|
317
|
+
let buf = Buffer.allocUnsafe(bytesToRead);
|
|
318
|
+
let totalRead = 0;
|
|
319
|
+
while (totalRead < bytesToRead) {
|
|
320
|
+
const n = fs.readSync(fd, buf, totalRead, bytesToRead - totalRead, start + totalRead);
|
|
321
|
+
if (n <= 0)
|
|
322
|
+
break;
|
|
323
|
+
totalRead += n;
|
|
324
|
+
}
|
|
325
|
+
if (totalRead === 0 && start > 0) {
|
|
326
|
+
const shrunkStat = fs.fstatSync(fd);
|
|
327
|
+
if (shrunkStat.size <= 0) {
|
|
328
|
+
return { buf: Buffer.alloc(0), startOffset: 0, size: 0, truncatedHead: false };
|
|
329
|
+
}
|
|
330
|
+
const retryBytes = Math.min(shrunkStat.size, maxTailBytes);
|
|
331
|
+
start = Math.max(0, shrunkStat.size - retryBytes);
|
|
332
|
+
buf = Buffer.allocUnsafe(retryBytes);
|
|
333
|
+
while (totalRead < retryBytes) {
|
|
334
|
+
const n = fs.readSync(fd, buf, totalRead, retryBytes - totalRead, start + totalRead);
|
|
335
|
+
if (n <= 0)
|
|
336
|
+
break;
|
|
337
|
+
totalRead += n;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const slice = totalRead === buf.length ? buf : buf.subarray(0, totalRead);
|
|
341
|
+
if (start > 0) {
|
|
342
|
+
const firstNl = slice.indexOf(0x0a);
|
|
343
|
+
if (firstNl < 0) {
|
|
344
|
+
return {
|
|
345
|
+
buf: Buffer.alloc(0),
|
|
346
|
+
startOffset: start + totalRead,
|
|
347
|
+
size: start + totalRead,
|
|
348
|
+
truncatedHead: true,
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
buf: slice.subarray(firstNl + 1),
|
|
353
|
+
startOffset: start + firstNl + 1,
|
|
354
|
+
size: start + totalRead,
|
|
355
|
+
truncatedHead: true,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
return { buf: slice, startOffset: 0, size: totalRead, truncatedHead: false };
|
|
359
|
+
}
|
|
360
|
+
finally {
|
|
361
|
+
fs.closeSync(fd);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function readCursor(cursorFile) {
|
|
365
|
+
try {
|
|
366
|
+
const raw = fs.readFileSync(cursorFile, 'utf8');
|
|
367
|
+
const parsed = JSON.parse(raw);
|
|
368
|
+
if (typeof parsed.ts === 'string' && typeof parsed.offset === 'number' && Number.isFinite(parsed.offset)) {
|
|
369
|
+
return { ts: parsed.ts, offset: parsed.offset };
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
// Missing or corrupt cursor behaves as unseen.
|
|
374
|
+
}
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
function writeCursor(cursorFile, state) {
|
|
378
|
+
const dir = path.dirname(cursorFile);
|
|
379
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
380
|
+
const nonce = crypto.randomBytes(6).toString('hex');
|
|
381
|
+
const tmp = `${cursorFile}.${process.pid}.${nonce}.tmp`;
|
|
382
|
+
const flags = fs.constants.O_WRONLY |
|
|
383
|
+
fs.constants.O_CREAT |
|
|
384
|
+
fs.constants.O_EXCL |
|
|
385
|
+
(fs.constants.O_NOFOLLOW ?? 0);
|
|
386
|
+
const fd = fs.openSync(tmp, flags, 0o600);
|
|
387
|
+
let closed = false;
|
|
388
|
+
try {
|
|
389
|
+
fs.fchmodSync(fd, 0o600);
|
|
390
|
+
const payload = Buffer.from(JSON.stringify(state), 'utf8');
|
|
391
|
+
let written = 0;
|
|
392
|
+
while (written < payload.length) {
|
|
393
|
+
written += fs.writeSync(fd, payload, written, payload.length - written);
|
|
394
|
+
}
|
|
395
|
+
fs.fsyncSync(fd);
|
|
396
|
+
fs.closeSync(fd);
|
|
397
|
+
closed = true;
|
|
398
|
+
fs.renameSync(tmp, cursorFile);
|
|
399
|
+
}
|
|
400
|
+
catch (err) {
|
|
401
|
+
if (!closed) {
|
|
402
|
+
try {
|
|
403
|
+
fs.closeSync(fd);
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
/* ignore */
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
try {
|
|
410
|
+
fs.unlinkSync(tmp);
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
/* ignore */
|
|
414
|
+
}
|
|
415
|
+
throw err;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function parseJsonLine(lineBuf) {
|
|
419
|
+
let s = 0;
|
|
420
|
+
let e = lineBuf.length;
|
|
421
|
+
while (s < e && lineBuf[s] <= 32)
|
|
422
|
+
s++;
|
|
423
|
+
while (e > s && lineBuf[e - 1] <= 32)
|
|
424
|
+
e--;
|
|
425
|
+
if (e - s < 2 || lineBuf[s] !== 0x7b)
|
|
426
|
+
return null;
|
|
427
|
+
try {
|
|
428
|
+
const parsed = JSON.parse(lineBuf.subarray(s, e).toString('utf8'));
|
|
429
|
+
return isInferenceEvent(parsed) ? parsed : null;
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
/** Read latest turn + session rollup from `eventsFile` with optional cursor de-duplication. */
|
|
436
|
+
export function readTurnReport(eventsFile, opts = {}) {
|
|
437
|
+
const maxTailBytes = opts.maxTailBytes ?? DEFAULT_MAX_TAIL_BYTES;
|
|
438
|
+
const tail = readTailBuffer(eventsFile, maxTailBytes);
|
|
439
|
+
if (!tail || tail.buf.length === 0) {
|
|
440
|
+
return { eventsFile, hasNewTurn: false, lastTurn: null, session: emptyRollup(null) };
|
|
441
|
+
}
|
|
442
|
+
const buf = tail.buf;
|
|
443
|
+
// Pass 1: reverse scan for the latest valid inference event (usually the very last line).
|
|
444
|
+
let lastEv = null;
|
|
445
|
+
let lastLineStart = 0;
|
|
446
|
+
let lineEnd = buf.length;
|
|
447
|
+
while (lineEnd > 0) {
|
|
448
|
+
const nl = buf.lastIndexOf(0x0a, lineEnd - 1);
|
|
449
|
+
const lineStart = nl >= 0 ? nl + 1 : 0;
|
|
450
|
+
const ev = parseJsonLine(buf.subarray(lineStart, lineEnd));
|
|
451
|
+
if (ev) {
|
|
452
|
+
lastEv = ev;
|
|
453
|
+
lastLineStart = lineStart;
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
lineEnd = nl;
|
|
457
|
+
if (nl < 0)
|
|
458
|
+
break;
|
|
459
|
+
}
|
|
460
|
+
if (!lastEv) {
|
|
461
|
+
return { eventsFile, hasNewTurn: false, lastTurn: null, session: emptyRollup(null) };
|
|
462
|
+
}
|
|
463
|
+
const rateCache = new Map();
|
|
464
|
+
const sessionId = lastEv.first_user_sha8 ?? null;
|
|
465
|
+
const lastMs = Date.parse(lastEv.ts);
|
|
466
|
+
const sessionNeedle = sessionId ? Buffer.from(sessionId, 'ascii') : null;
|
|
467
|
+
// Pass 2: reverse scan prior lines, pre-filtering in native Buffer before JSON.parse.
|
|
468
|
+
const sessionEvents = [lastEv];
|
|
469
|
+
let scanEnd = lastLineStart > 0 ? lastLineStart - 1 : 0;
|
|
470
|
+
while (scanEnd > 0) {
|
|
471
|
+
const nl = buf.lastIndexOf(0x0a, scanEnd - 1);
|
|
472
|
+
const lineStart = nl >= 0 ? nl + 1 : 0;
|
|
473
|
+
const slice = buf.subarray(lineStart, scanEnd);
|
|
474
|
+
scanEnd = nl >= 0 ? nl : 0;
|
|
475
|
+
if (slice.length < 2)
|
|
476
|
+
continue;
|
|
477
|
+
if (sessionNeedle) {
|
|
478
|
+
if (!slice.includes(sessionNeedle))
|
|
479
|
+
continue;
|
|
480
|
+
const ev = parseJsonLine(slice);
|
|
481
|
+
if (ev && ev.first_user_sha8 === sessionId) {
|
|
482
|
+
sessionEvents.push(ev);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
const ev = parseJsonLine(slice);
|
|
487
|
+
if (!ev)
|
|
488
|
+
continue;
|
|
489
|
+
if (Number.isFinite(lastMs)) {
|
|
490
|
+
const evMs = Date.parse(ev.ts);
|
|
491
|
+
if (!Number.isFinite(evMs))
|
|
492
|
+
continue;
|
|
493
|
+
if (lastMs - evMs > SESSION_FALLBACK_WINDOW_MS)
|
|
494
|
+
break;
|
|
495
|
+
}
|
|
496
|
+
sessionEvents.push(ev);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
sessionEvents.reverse();
|
|
500
|
+
const warmthState = {};
|
|
501
|
+
const sessionSnapshots = sessionEvents.map((ev) => computeTurnSnapshotWithCache(ev, rateCache, warmthState));
|
|
502
|
+
const lastTurn = sessionSnapshots[sessionSnapshots.length - 1];
|
|
503
|
+
let savedTokens = 0;
|
|
504
|
+
let savedUsd = 0;
|
|
505
|
+
let cliffSavedUsd = 0;
|
|
506
|
+
let compressedTurns = 0;
|
|
507
|
+
let cacheWeightSum = 0;
|
|
508
|
+
let cacheTokTotal = 0;
|
|
509
|
+
for (let i = 0; i < sessionSnapshots.length; i++) {
|
|
510
|
+
const snap = sessionSnapshots[i];
|
|
511
|
+
savedTokens += snap.savedTokens;
|
|
512
|
+
savedUsd += snap.savedUsd;
|
|
513
|
+
cliffSavedUsd += snap.cliffSavedUsd ?? 0;
|
|
514
|
+
if (snap.savedTokens > 0 || snap.stages.length > 0)
|
|
515
|
+
compressedTurns += 1;
|
|
516
|
+
if (snap.inputTokens > 0) {
|
|
517
|
+
cacheTokTotal += snap.inputTokens;
|
|
518
|
+
cacheWeightSum += snap.cachedTokens;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
const session = {
|
|
522
|
+
sessionId,
|
|
523
|
+
turns: sessionSnapshots.length,
|
|
524
|
+
compressedTurns,
|
|
525
|
+
savedTokens,
|
|
526
|
+
savedUsd: round6(savedUsd),
|
|
527
|
+
cliffSavedUsd: round6(cliffSavedUsd),
|
|
528
|
+
avgCacheHitPct: cacheTokTotal > 0 ? round1((cacheWeightSum / cacheTokTotal) * 100) : null,
|
|
529
|
+
};
|
|
530
|
+
const lastLineAbsOffset = Math.max(0, tail.startOffset + lastLineStart);
|
|
531
|
+
let hasNewTurn = true;
|
|
532
|
+
if (opts.cursorFile) {
|
|
533
|
+
const prev = readCursor(opts.cursorFile);
|
|
534
|
+
hasNewTurn = prev === null || prev.ts !== lastTurn.ts || prev.offset !== lastLineAbsOffset;
|
|
535
|
+
if (hasNewTurn && opts.updateCursor !== false) {
|
|
536
|
+
try {
|
|
537
|
+
writeCursor(opts.cursorFile, { ts: lastTurn.ts, offset: lastLineAbsOffset });
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
// Non-fatal: cursor write failures never fail hooks or CLI status.
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return { eventsFile, hasNewTurn, lastTurn, session };
|
|
545
|
+
}
|
|
546
|
+
function formatCompactTokens(tokens) {
|
|
547
|
+
const abs = Math.abs(tokens);
|
|
548
|
+
if (abs >= 1_000_000)
|
|
549
|
+
return `${(abs / 1_000_000).toFixed(2)}M`;
|
|
550
|
+
if (abs >= 10_000)
|
|
551
|
+
return `${(abs / 1_000).toFixed(1)}k`;
|
|
552
|
+
if (abs >= 1_000)
|
|
553
|
+
return `${(abs / 1_000).toFixed(2)}k`;
|
|
554
|
+
return String(abs);
|
|
555
|
+
}
|
|
556
|
+
function formatSignedTokens(savedTokens) {
|
|
557
|
+
return savedTokens < 0
|
|
558
|
+
? `+${formatCompactTokens(savedTokens)}`
|
|
559
|
+
: `-${formatCompactTokens(savedTokens)}`;
|
|
560
|
+
}
|
|
561
|
+
function formatUsd(usd) {
|
|
562
|
+
if (usd === 0)
|
|
563
|
+
return '';
|
|
564
|
+
const sign = usd > 0 ? '-' : '+';
|
|
565
|
+
const abs = Math.abs(usd);
|
|
566
|
+
if (abs < 0.01)
|
|
567
|
+
return `${sign}$${abs.toFixed(4)}`;
|
|
568
|
+
if (abs < 1)
|
|
569
|
+
return `${sign}$${abs.toFixed(3)}`;
|
|
570
|
+
return `${sign}$${abs.toFixed(2)}`;
|
|
571
|
+
}
|
|
572
|
+
/** Markdown summary suitable for Antigravity `metadata.user_markdown`. */
|
|
573
|
+
export function formatTurnReportMarkdown(payload) {
|
|
574
|
+
const { lastTurn, session } = payload;
|
|
575
|
+
if (!lastTurn)
|
|
576
|
+
return '';
|
|
577
|
+
const modelLabel = lastTurn.model ? ` **${lastTurn.model}**` : '';
|
|
578
|
+
const turnUsd = formatUsd(lastTurn.savedUsd);
|
|
579
|
+
const turnUsdPart = turnUsd ? ` (${turnUsd})` : '';
|
|
580
|
+
const cachePart = lastTurn.cacheHitPct !== null ? ` · **${Math.round(lastTurn.cacheHitPct)}% cache**` : '';
|
|
581
|
+
const stagesPart = lastTurn.stages.length > 0 ? ` · \`${lastTurn.stages.join('+')}\`` : '';
|
|
582
|
+
const cliffPart = lastTurn.cliffAvoidedAt !== undefined ? ` · cliff <${formatCompactTokens(lastTurn.cliffAvoidedAt)} avoided` : '';
|
|
583
|
+
const sessUsd = formatUsd(session.savedUsd);
|
|
584
|
+
const sessUsdPart = sessUsd ? ` (${sessUsd})` : '';
|
|
585
|
+
const sessVerb = session.savedTokens < 0 ? 'delta' : 'session';
|
|
586
|
+
const sessPart = session.turns > 1
|
|
587
|
+
? ` · ${sessVerb} **${formatSignedTokens(session.savedTokens)} tok**${sessUsdPart}, ${session.turns}t`
|
|
588
|
+
: '';
|
|
589
|
+
const verb = lastTurn.savedTokens < 0 ? 'delta' : 'saved';
|
|
590
|
+
return `\`fiche\`${modelLabel} · ${verb} **${formatSignedTokens(lastTurn.savedTokens)} tok**${turnUsdPart}${cachePart}${stagesPart}${cliffPart}${sessPart}`;
|
|
591
|
+
}
|
|
592
|
+
/** Antigravity `PostInvocation` hook JSON output (zero LLM tokens via empty `systemMessage`). */
|
|
593
|
+
export function formatAgyHookJson(payload) {
|
|
594
|
+
if (!payload.hasNewTurn || !payload.lastTurn)
|
|
595
|
+
return {};
|
|
596
|
+
if (payload.lastTurn.savedTokens === 0 && payload.session.savedTokens === 0)
|
|
597
|
+
return {};
|
|
598
|
+
const md = formatTurnReportMarkdown(payload);
|
|
599
|
+
if (!md)
|
|
600
|
+
return {};
|
|
601
|
+
return {
|
|
602
|
+
injectSteps: [
|
|
603
|
+
{
|
|
604
|
+
systemMessage: {
|
|
605
|
+
systemMessage: '',
|
|
606
|
+
metadata: {
|
|
607
|
+
user_markdown: md,
|
|
608
|
+
},
|
|
609
|
+
},
|
|
610
|
+
},
|
|
611
|
+
],
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
/** Compact single-line output for Claude Code `statusLine`. */
|
|
615
|
+
export function formatClaudeStatusLine(payload) {
|
|
616
|
+
const { lastTurn, session } = payload;
|
|
617
|
+
if (!lastTurn)
|
|
618
|
+
return '';
|
|
619
|
+
const model = lastTurn.model ? `${lastTurn.model} ` : '';
|
|
620
|
+
const turnUsd = formatUsd(lastTurn.savedUsd);
|
|
621
|
+
const usdSuffix = turnUsd ? ` (${turnUsd})` : '';
|
|
622
|
+
const cache = lastTurn.cacheHitPct !== null ? ` | ${Math.round(lastTurn.cacheHitPct)}% cache` : '';
|
|
623
|
+
const sessUsd = formatUsd(session.savedUsd);
|
|
624
|
+
const sessPart = session.turns > 1
|
|
625
|
+
? ` | sess ${formatSignedTokens(session.savedTokens)}${sessUsd ? ` (${sessUsd})` : ''}`
|
|
626
|
+
: '';
|
|
627
|
+
return `fiche ${model}${formatSignedTokens(lastTurn.savedTokens)} tok${usdSuffix}${cache}${sessPart}`;
|
|
628
|
+
}
|
|
629
|
+
/** Compact single-line CLI output (optionally ANSI colored). */
|
|
630
|
+
export function formatCliLine(payload, color = false) {
|
|
631
|
+
const { lastTurn, session } = payload;
|
|
632
|
+
if (!lastTurn)
|
|
633
|
+
return '[fiche] no recorded turns yet';
|
|
634
|
+
const line = formatClaudeStatusLine(payload);
|
|
635
|
+
const stages = lastTurn.stages.length > 0 ? ` [${lastTurn.stages.join('+')}]` : '';
|
|
636
|
+
const full = `${line}${stages} (${session.turns}t)`;
|
|
637
|
+
return color ? `\x1b[36m${full}\x1b[0m` : full;
|
|
638
|
+
}
|
|
639
|
+
export function defaultEventsFilePath() {
|
|
640
|
+
const configured = readBrandEnv('LOG');
|
|
641
|
+
if (configured !== undefined && configured !== '')
|
|
642
|
+
return configured;
|
|
643
|
+
const preferred = path.join(os.homedir(), '.fiche', 'events.jsonl');
|
|
644
|
+
if (fs.existsSync(preferred))
|
|
645
|
+
return preferred;
|
|
646
|
+
const legacy = path.join(os.homedir(), '.inkling', 'events.jsonl');
|
|
647
|
+
if (fs.existsSync(legacy))
|
|
648
|
+
return legacy;
|
|
649
|
+
return preferred;
|
|
650
|
+
}
|
|
651
|
+
/** CLI runner for `fiche turn-report`. */
|
|
652
|
+
export function runTurnReportCli(argv, defaultEventsFile) {
|
|
653
|
+
let format = 'cli';
|
|
654
|
+
let filePath = defaultEventsFile;
|
|
655
|
+
let cursorFile;
|
|
656
|
+
let updateCursor = true;
|
|
657
|
+
let color = false;
|
|
658
|
+
for (let i = 0; i < argv.length; i++) {
|
|
659
|
+
const a = argv[i];
|
|
660
|
+
if (a === '--format' && argv[i + 1]) {
|
|
661
|
+
const f = argv[++i];
|
|
662
|
+
if (f === 'cli' || f === 'agy' || f === 'claude-statusline' || f === 'json')
|
|
663
|
+
format = f;
|
|
664
|
+
else
|
|
665
|
+
return { code: 2, out: '', err: `[fiche turn-report] unknown format: ${f}` };
|
|
666
|
+
}
|
|
667
|
+
else if (a.startsWith('--format=')) {
|
|
668
|
+
const f = a.slice('--format='.length);
|
|
669
|
+
if (f === 'cli' || f === 'agy' || f === 'claude-statusline' || f === 'json')
|
|
670
|
+
format = f;
|
|
671
|
+
else
|
|
672
|
+
return { code: 2, out: '', err: `[fiche turn-report] unknown format: ${f}` };
|
|
673
|
+
}
|
|
674
|
+
else if ((a === '--file' || a === '-f') && argv[i + 1]) {
|
|
675
|
+
filePath = argv[++i];
|
|
676
|
+
}
|
|
677
|
+
else if (a.startsWith('--file=')) {
|
|
678
|
+
filePath = a.slice('--file='.length);
|
|
679
|
+
}
|
|
680
|
+
else if (a === '--cursor' && argv[i + 1]) {
|
|
681
|
+
cursorFile = argv[++i];
|
|
682
|
+
}
|
|
683
|
+
else if (a.startsWith('--cursor=')) {
|
|
684
|
+
cursorFile = a.slice('--cursor='.length);
|
|
685
|
+
}
|
|
686
|
+
else if (a === '--no-update-cursor') {
|
|
687
|
+
updateCursor = false;
|
|
688
|
+
}
|
|
689
|
+
else if (a === '--color') {
|
|
690
|
+
color = true;
|
|
691
|
+
}
|
|
692
|
+
else if (a === '--help' || a === '-h') {
|
|
693
|
+
return {
|
|
694
|
+
code: 0,
|
|
695
|
+
out: [
|
|
696
|
+
'fiche turn-report — report latest turn & session token/$ savings from events JSONL',
|
|
697
|
+
'',
|
|
698
|
+
'Options:',
|
|
699
|
+
' --format=cli|agy|claude-statusline|json Output format (default: cli)',
|
|
700
|
+
' --file <path> Events JSONL (default: $FICHE_LOG or ~/.fiche/events.jsonl)',
|
|
701
|
+
' --cursor <path> Cursor file for deduplicating repeat hook calls',
|
|
702
|
+
' --no-update-cursor Inspect cursor without updating it',
|
|
703
|
+
' --color ANSI color for cli format',
|
|
704
|
+
].join('\n'),
|
|
705
|
+
err: '',
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
else {
|
|
709
|
+
return { code: 2, out: '', err: `[fiche turn-report] unknown option: ${a}` };
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const payload = readTurnReport(filePath, { cursorFile, updateCursor });
|
|
713
|
+
if (format === 'json') {
|
|
714
|
+
return { code: 0, out: JSON.stringify(payload, null, 2), err: '' };
|
|
715
|
+
}
|
|
716
|
+
if (format === 'agy') {
|
|
717
|
+
return { code: 0, out: JSON.stringify(formatAgyHookJson(payload)), err: '' };
|
|
718
|
+
}
|
|
719
|
+
if (format === 'claude-statusline') {
|
|
720
|
+
return { code: 0, out: formatClaudeStatusLine(payload), err: '' };
|
|
721
|
+
}
|
|
722
|
+
return { code: 0, out: formatCliLine(payload, color), err: '' };
|
|
723
|
+
}
|
|
724
|
+
//# sourceMappingURL=turn-report.js.map
|